diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..fef2bb4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI + +on: + pull_request: + +jobs: + validate: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + + - name: Install deps + run: pnpm install --frozen-lockfile + + - name: Apply local D1 migrations + run: pnpm db:migrate + + - name: Check pending local migrations + run: pnpm db:migrate:list + + - name: Test + run: pnpm test + + - name: Typecheck + run: pnpm exec tsc --noEmit + + - name: Build + run: pnpm build diff --git a/mvp.md b/mvp.md index a2cb4e3..e32d2cf 100644 --- a/mvp.md +++ b/mvp.md @@ -6,10 +6,10 @@ Build a Cloudflare-native "email for agents" MVP where each signed-up user can o ## 2) Requirements mapped to MVP -1. On signup, auto-provision an inbox: `id@clankr.email`. -2. User can assign one friendly alias per inbox: `name@clankr.email`. -3. Multi-inbox per user is supported from day 1. -4. App can send and receive email through API. +1. ~~On signup, auto-provision an inbox: `id@clankr.email`.~~ +2. ~~User can assign one friendly alias per inbox: `name@clankr.email`.~~ +3. ~~Multi-inbox per user is supported from day 1.~~ +4. ~~App can send and receive email through API.~~ 5. App can list threads and read thread messages through API. 6. App supports webhook subscriptions for email events. 7. Implementation is fully on Cloudflare primitives. @@ -241,17 +241,17 @@ All product APIs are defined as oRPC procedures (single source of truth) in `#/o ### Inbox procedures -- `inboxes.list` -> list user inboxes -- `inboxes.create` -> create additional inbox -- `inboxes.get` -> inbox detail -- `inboxes.updateAlias` -> set/clear `custom_local_part` +- ~~`inboxes.list` -> list user inboxes~~ +- ~~`inboxes.create` -> create additional inbox~~ +- ~~`inboxes.get` -> inbox detail~~ +- ~~`inboxes.updateAlias` -> set/clear `custom_local_part`~~ ### Send procedures -- `messages.send` - - input: `inboxId`, `to[]`, `cc[]`, `bcc[]`, `subject`, `text|html`, `replyToThreadId?` - - action: validate ownership + `env.EMAIL.send` - - output: internal message id + provider message id + status +- ~~`messages.send`~~ + - ~~input: `inboxId`, `to[]`, `cc[]`, `bcc[]`, `subject`, `text|html`, `replyToThreadId?`~~ + - ~~action: validate ownership + `env.EMAIL.send`~~ + - ~~output: internal message id + provider message id + status~~ ### Thread/message read procedures @@ -269,39 +269,39 @@ All product APIs are defined as oRPC procedures (single source of truth) in `#/o ## 8) Inbound email processing flow -1. Cloudflare routes incoming email to Worker `email()` handler. -2. Resolve `message.to` local part to inbox in `APP_DB` (`custom_local_part` then `default_local_part`). -3. Parse MIME body from `message.raw` (robust parser library, not regex). -4. Compute thread in `APP_DB`: - - preferred: `In-Reply-To`/`References` match existing `internet_message_id` - - fallback: normalized subject + participants hash within inbox -5. Persist message metadata and parsed body in `APP_DB`. -6. Persist raw MIME to R2, plus oversized bodies and attachments when needed. -7. Update thread `last_message_at` in `APP_DB`. -8. Emit `message.received` event to queue for webhooks. +1. ~~Cloudflare routes incoming email to Worker `email()` handler.~~ +2. ~~Resolve `message.to` local part to inbox in `APP_DB` (`custom_local_part` then `default_local_part`).~~ +3. ~~Parse MIME body from `message.raw` (robust parser library, not regex).~~ +4. ~~Compute thread in `APP_DB`:~~ + - ~~preferred: `In-Reply-To`/`References` match existing `internet_message_id`~~ + - ~~fallback: normalized subject + participants hash within inbox~~ +5. ~~Persist message metadata and parsed body in `APP_DB`.~~ +6. ~~Persist raw MIME to R2, plus oversized bodies and attachments when needed.~~ +7. ~~Update thread `last_message_at` in `APP_DB`.~~ +8. ~~Emit `message.received` event to queue for webhooks.~~ ## 9) Outbound sending flow -1. Authenticated user calls `messages.send` procedure. -2. Validate sender inbox ownership in `APP_DB` and enforce recipient limits. -3. Persist outbound metadata row in `APP_DB` (`accepted|failed`). -4. Call `env.EMAIL.send(...)`. -5. Persist provider `messageId` and error code/message if failed (`APP_DB`). -6. Store parsed outbound bodies in `APP_DB`; store raw MIME or oversized payloads in R2 when needed. -7. Thread linkage: - - if replying: include `In-Reply-To`/`References` headers - - else: create/find thread by subject + participants in `APP_DB` -8. Emit events: - - `message.sent.accepted` - - `message.sent.failed` +1. ~~Authenticated user calls `messages.send` procedure.~~ +2. ~~Validate sender inbox ownership in `APP_DB` and enforce recipient limits.~~ +3. ~~Persist outbound metadata row in `APP_DB` (`accepted|failed`).~~ +4. ~~Call `env.EMAIL.send(...)`.~~ +5. ~~Persist provider `messageId` and error code/message if failed (`APP_DB`).~~ +6. ~~Store parsed outbound bodies in `APP_DB`; store raw MIME or oversized payloads in R2 when needed.~~ +7. ~~Thread linkage:~~ + - ~~if replying: include `In-Reply-To`/`References` headers~~ + - ~~else: create/find thread by subject + participants in `APP_DB`~~ +8. ~~Emit events:~~ + - ~~`message.sent.accepted`~~ + - ~~`message.sent.failed`~~ ## 10) Webhook event system ### Event types (MVP) -- `message.received` -- `message.sent.accepted` -- `message.sent.failed` +- ~~`message.received`~~ +- ~~`message.sent.accepted`~~ +- ~~`message.sent.failed`~~ - `thread.updated` - `inbox.alias.updated` @@ -330,12 +330,12 @@ Payload shape: ## 11) Security and tenancy rules -- Every read/write query scoped by `session.user.id` ownership. -- Validate external input at procedure boundaries (oRPC + Zod) before DB writes. +- ~~Every read/write query scoped by `session.user.id` ownership.~~ +- ~~Validate external input at procedure boundaries (oRPC + Zod) before DB writes.~~ - No reliance on DB foreign keys for auth boundaries. -- Never expose raw provider errors directly without sanitizing. +- ~~Never expose raw provider errors directly without sanitizing.~~ - Rate-limit `messages.send` per user + per inbox. -- Enforce max recipients and payload size before `env.EMAIL.send`. +- ~~Enforce max recipients and payload size before `env.EMAIL.send`.~~ - For webhook URLs: - allow only `https` - block localhost/private CIDR in production @@ -360,26 +360,26 @@ Test work starts in Phase 0 and continues in every phase. New primitives should - [x] Add prefixed ULID utility (`in_`, `th_`, `em_`, `wh_`, `evt_`, `wd_`). - [x] Add `EMAIL`, R2, and Queue bindings in Wrangler. - Add migration smoke checks in CI (`migrations list` should be empty after apply). -- Write the first unit and repository tests for ID generation, alias validation, and schema-level helpers as the foundation code is added. +- ~~Write the first unit and repository tests for ID generation, alias validation, and schema-level helpers as the foundation code is added.~~ ### Phase 2: Inbox provisioning + alias - [x] Hook signup flow to auto-create first inbox. - [x] Implement `inboxes.create` procedure. - [x] Implement `inboxes.updateAlias` procedure with uniqueness validation. -- Write integration tests for signup provisioning, additional inbox creation, alias updates, reserved-word rejection, and uniqueness collisions alongside the implementation. +- ~~Write integration tests for signup provisioning, additional inbox creation, alias updates, reserved-word rejection, and uniqueness collisions alongside the implementation.~~ ### Phase 3: Receive pipeline - [x] Implement `email()` handler with inbox resolution in `APP_DB`, MIME parsing, D1 persistence, and R2 raw MIME/overflow storage. - [x] Write integration tests for routing + threading fallback before wiring the full handler. -- Add fixture-driven inbound tests for unknown inbox rejection, reply-chain threading, fallback threading, duplicate provider/internet message IDs, and oversized body spillover to R2 as each case is implemented. +- ~~Add fixture-driven inbound tests for unknown inbox rejection, reply-chain threading, fallback threading, duplicate provider/internet message IDs, and oversized body spillover to R2 as each case is implemented.~~ ### Phase 4: Send pipeline -- Implement `messages.send` procedure backed by `env.EMAIL.send` with app-db ownership checks. -- Persist send outcomes in `APP_DB` and map Cloudflare error codes to API responses. -- Write integration tests covering happy-path send, ownership rejection, recipient/payload validation, provider failure mapping, reply headers, and DB persistence of send status alongside the procedure work. +- [x] Implement `messages.send` procedure backed by `env.EMAIL.send` with app-db ownership checks. +- [x] Persist send outcomes in `APP_DB` and map Cloudflare error codes to API responses. +- [x] Write integration tests covering happy-path send, ownership rejection, recipient/payload validation, provider failure mapping, reply headers, and DB persistence of send status alongside the procedure work. ### Phase 5: Thread procedures @@ -415,14 +415,14 @@ Tests are written from the beginning of implementation, not collected at the end ### What must be independently testable -- **Inbox provisioning**: signup creates exactly one inbox with a stable default local part. -- **Alias management**: alias validation, uniqueness, reserved words, clear/reset behavior. -- **Inbound routing**: local-part resolution, unknown inbox rejection, active/inactive inbox handling. -- **Message parsing**: MIME parsing to normalized subject, participants, text/html body, snippet, message IDs. -- **Threading**: `In-Reply-To`/`References` matching first, deterministic fallback second. -- **Message persistence**: inserts, idempotency behavior, status transitions, and thread `last_message_at` updates. -- **Body storage**: normal bodies read from D1; oversized bodies/raw MIME/attachments written to and retrievable from R2. -- **Outbound sending**: auth checks, payload validation, provider success/failure mapping, reply header generation. +- ~~**Inbox provisioning**: signup creates exactly one inbox with a stable default local part.~~ +- ~~**Alias management**: alias validation, uniqueness, reserved words, clear/reset behavior.~~ +- ~~**Inbound routing**: local-part resolution, unknown inbox rejection, active/inactive inbox handling.~~ +- ~~**Message parsing**: MIME parsing to normalized subject, participants, text/html body, snippet, message IDs.~~ +- ~~**Threading**: `In-Reply-To`/`References` matching first, deterministic fallback second.~~ +- ~~**Message persistence**: inserts, idempotency behavior, status transitions, and thread `last_message_at` updates.~~ +- ~~**Body storage**: normal bodies read from D1; oversized bodies/raw MIME/attachments written to and retrievable from R2.~~ +- ~~**Outbound sending**: auth checks, payload validation, provider success/failure mapping, reply header generation.~~ - **Read APIs**: inbox/thread/message listing and detail endpoints with pagination and ownership enforcement. - **Webhooks**: subscription CRUD, event fanout, HMAC signing, retry scheduling, dead-letter behavior. @@ -451,16 +451,16 @@ Minimum validation before merging a feature: ## 14) MVP acceptance criteria -1. Signup auto-creates a working `@clankr.email` inbox. -2. User can create additional inboxes and set one friendly alias per inbox. +1. ~~Signup auto-creates a working `@clankr.email` inbox.~~ +2. ~~User can create additional inboxes and set one friendly alias per inbox.~~ 3. Inbound emails to default or custom local parts resolve via `APP_DB` and appear in thread/message APIs. -4. `messages.send` sends mail from selected inbox and persists status/message IDs in `APP_DB`. -5. Thread grouping works for standard reply chains. +4. ~~`messages.send` sends mail from selected inbox and persists status/message IDs in `APP_DB`.~~ +5. ~~Thread grouping works for standard reply chains.~~ 6. Webhook subscribers receive signed events with retries. 7. End-to-end runs on Cloudflare (Workers + Email Service + D1 + R2 + Queues). -8. All IDs are prefixed ULIDs and are time-sort friendly. -9. Local + remote migrations are repeatable for `APP_DB`. -10. MVP API surface is implemented in oRPC procedures and served via `/api/rpc/*` (with OpenAPI output at `/api/openapi.json`). +8. ~~All IDs are prefixed ULIDs and are time-sort friendly.~~ +9. ~~Local + remote migrations are repeatable for `APP_DB`.~~ +10. ~~MVP API surface is implemented in oRPC procedures and served via `/api/rpc/*` (with OpenAPI output at `/api/openapi.json`).~~ ## 15) Known MVP constraints diff --git a/src/db/client.ts b/src/db/client.ts index f1f5afb..ac4ef22 100644 --- a/src/db/client.ts +++ b/src/db/client.ts @@ -1,5 +1 @@ -import { env } from 'cloudflare:workers' - -import { createDb } from './index' - -export const db = createDb(env.APP_DB) +export { db, getDb } from '#/lib/runtime' diff --git a/src/lib/auth.ts b/src/lib/auth.ts index 2d4b109..5156875 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -17,7 +17,7 @@ export const auth = betterAuth({ return } - await provisionInitialInbox(db, user.id) + await provisionInitialInbox(user.id) }, }, }, diff --git a/src/lib/email/events.ts b/src/lib/email/events.ts index f7c7a03..fc786a5 100644 --- a/src/lib/email/events.ts +++ b/src/lib/email/events.ts @@ -2,6 +2,8 @@ import { createEventId } from './ids' export const EMAIL_EVENT_TYPES = { messageReceived: 'message.received', + messageSentAccepted: 'message.sent.accepted', + messageSentFailed: 'message.sent.failed', } as const export type MessageReceivedEvent = { @@ -15,7 +17,31 @@ export type MessageReceivedEvent = { } } -export type EmailEvent = MessageReceivedEvent +export type MessageSentAcceptedEvent = { + id: string + type: (typeof EMAIL_EVENT_TYPES)['messageSentAccepted'] + createdAt: string + data: { + inboxId: string + threadId: string + messageId: string + providerMessageId: string + } +} + +export type MessageSentFailedEvent = { + id: string + type: (typeof EMAIL_EVENT_TYPES)['messageSentFailed'] + createdAt: string + data: { + inboxId: string + threadId: string + messageId: string + errorCode: string + } +} + +export type EmailEvent = MessageReceivedEvent | MessageSentAcceptedEvent | MessageSentFailedEvent export function createMessageReceivedEvent( data: MessageReceivedEvent['data'], @@ -28,3 +54,27 @@ export function createMessageReceivedEvent( data, } } + +export function createMessageSentAcceptedEvent( + data: MessageSentAcceptedEvent['data'], + createdAt = new Date(), +): MessageSentAcceptedEvent { + return { + id: createEventId(), + type: EMAIL_EVENT_TYPES.messageSentAccepted, + createdAt: createdAt.toISOString(), + data, + } +} + +export function createMessageSentFailedEvent( + data: MessageSentFailedEvent['data'], + createdAt = new Date(), +): MessageSentFailedEvent { + return { + id: createEventId(), + type: EMAIL_EVENT_TYPES.messageSentFailed, + createdAt: createdAt.toISOString(), + data, + } +} diff --git a/src/lib/email/inbound.test.ts b/src/lib/email/inbound.test.ts index b236da1..5b8f19a 100644 --- a/src/lib/email/inbound.test.ts +++ b/src/lib/email/inbound.test.ts @@ -1,8 +1,29 @@ import { desc } from 'drizzle-orm' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { emailMessages, emailThreads } from '#/db/schema' +const testState = vi.hoisted(() => ({ + harness: null as EmailTestHarness | null, +})) + +vi.mock('#/lib/runtime', () => ({ + getDb() { + if (!testState.harness) { + throw new Error('Email test harness not initialized.') + } + + return testState.harness.db + }, + getWorkerEnv() { + if (!testState.harness) { + throw new Error('Email test harness not initialized.') + } + + return testState.harness.env + }, +})) + import { handleInboundEmail, INLINE_BODY_LIMIT_BYTES } from './inbound' import { createInboundWorkerMessage, createMimeFixture } from './test-fixtures' import { createEmailTestHarness, createInboxRecord, createUserRecord, type EmailTestHarness } from './test-harness' @@ -12,10 +33,12 @@ describe('inbound email pipeline', () => { beforeEach(() => { harness = createEmailTestHarness() + testState.harness = harness }) afterEach(() => { harness.cleanup() + testState.harness = null }) it('rejects unknown inboxes', async () => { @@ -24,7 +47,7 @@ describe('inbound email pipeline', () => { to: 'missing@clankr.email', }) - const result = await handleInboundEmail(message, harness.env) + const result = await handleInboundEmail(message) expect(result).toEqual({ status: 'rejected', @@ -50,7 +73,7 @@ describe('inbound email pipeline', () => { to: 'agent@clankr.email', }) - const result = await handleInboundEmail(message, harness.env) + const result = await handleInboundEmail(message) const [storedMessage] = await harness.db.select().from(emailMessages) expect(result.status).toBe('accepted') @@ -98,8 +121,8 @@ describe('inbound email pipeline', () => { to: 'agent@clankr.email', }) - const firstResult = await handleInboundEmail(firstMessage.message, harness.env) - const secondResult = await handleInboundEmail(secondMessage.message, harness.env) + const firstResult = await handleInboundEmail(firstMessage.message) + const secondResult = await handleInboundEmail(secondMessage.message) expect(firstResult.status).toBe('accepted') if (firstResult.status !== 'accepted') { @@ -126,7 +149,6 @@ describe('inbound email pipeline', () => { }).trim(), to: 'agent@clankr.email', }).message, - harness.env, ) const secondResult = await handleInboundEmail( @@ -138,7 +160,6 @@ describe('inbound email pipeline', () => { }).trim(), to: 'agent@clankr.email', }).message, - harness.env, ) const threads = await harness.db.select().from(emailThreads).orderBy(desc(emailThreads.createdAt)) @@ -163,14 +184,12 @@ describe('inbound email pipeline', () => { raw: rawMime, to: 'agent@clankr.email', }).message, - harness.env, ) const secondResult = await handleInboundEmail( createInboundWorkerMessage({ raw: rawMime, to: 'agent@clankr.email', }).message, - harness.env, ) const messages = await harness.db.select().from(emailMessages) @@ -204,7 +223,6 @@ describe('inbound email pipeline', () => { }), to: 'agent@clankr.email', }).message, - harness.env, ) const [storedMessage] = await harness.db.select().from(emailMessages) diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.ts index 2751d1d..de09a21 100644 --- a/src/lib/email/inbound.ts +++ b/src/lib/email/inbound.ts @@ -1,7 +1,7 @@ import { and, desc, eq, inArray } from 'drizzle-orm' import PostalMime, { addressParser, type Address, type Email, type RawEmail } from 'postal-mime' -import { createDb } from '#/db/index' +import { getDb, getWorkerEnv } from '#/lib/runtime' import { emailMessages, emailThreads } from '#/db/schema' import { createMessageReceivedEvent } from './events' @@ -31,17 +31,10 @@ export type InboundEmailResult = reason: 'invalid-recipient' | 'unknown-inbox' } -type ThreadLookupDatabase = Pick, 'select'> -type InboundEmailEnv = Pick & { - EMAIL_EVENTS: Pick>, 'send'> - EMAIL_STORAGE: Pick -} +type ThreadLookupDatabase = Pick, 'select'> type InboundEmailMessage = Pick -export async function handleInboundEmail( - message: InboundEmailMessage, - env: InboundEmailEnv, -): Promise { +export async function handleInboundEmail(message: InboundEmailMessage): Promise { const localPart = getLocalPart(message.to) if (!localPart) { @@ -53,8 +46,9 @@ export async function handleInboundEmail( } } - const db = createDb(env.APP_DB) - const inbox = await findInboxByLocalPart(db, localPart) + const db = getDb() + const env = getWorkerEnv() + const inbox = await findInboxByLocalPart(localPart) if (!inbox) { message.setReject('Unknown inbox') diff --git a/src/lib/email/inboxes.test.ts b/src/lib/email/inboxes.test.ts index c019364..6567b19 100644 --- a/src/lib/email/inboxes.test.ts +++ b/src/lib/email/inboxes.test.ts @@ -1,4 +1,13 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('#/lib/runtime', () => ({ + getDb() { + throw new Error('getDb should not be called in inbox alias tests.') + }, + getWorkerEnv() { + throw new Error('getWorkerEnv should not be called in inbox alias tests.') + }, +})) import { InboxAliasValidationError, diff --git a/src/lib/email/inboxes.ts b/src/lib/email/inboxes.ts index 9148e35..896028a 100644 --- a/src/lib/email/inboxes.ts +++ b/src/lib/email/inboxes.ts @@ -1,123 +1,119 @@ -import { and, asc, eq, ne } from "drizzle-orm"; +import { and, asc, eq, ne } from 'drizzle-orm' -import type { AppDb } from "#/db/index"; -import { inboxes } from "#/db/schema"; +import { getDb } from '#/lib/runtime' +import { inboxes } from '#/db/schema' -import { createInboxId } from "./ids"; +import { createInboxId } from './ids' const RESERVED_INBOX_ALIASES = new Set([ - "abuse", - "admin", - "billing", - "contact", - "help", - "hostmaster", - "info", - "marketing", - "no-reply", - "noreply", - "postmaster", - "privacy", - "root", - "sales", - "security", - "support", - "system", - "webmaster", - "koushik", - "kdawg", -]); - -const INBOX_ALIAS_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + 'abuse', + 'admin', + 'billing', + 'contact', + 'help', + 'hostmaster', + 'info', + 'marketing', + 'no-reply', + 'noreply', + 'postmaster', + 'privacy', + 'root', + 'sales', + 'security', + 'support', + 'system', + 'webmaster', + 'koushik', + 'kdawg', +]) + +const INBOX_ALIAS_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ export class InboxAliasValidationError extends Error {} export class InboxAliasConflictError extends Error {} export function normalizeInboxAlias(alias: string) { - return alias.trim().toLowerCase(); + return alias.trim().toLowerCase() } export function validateInboxAlias(alias: string) { - const normalizedAlias = normalizeInboxAlias(alias); + const normalizedAlias = normalizeInboxAlias(alias) if (normalizedAlias.length < 3 || normalizedAlias.length > 32) { - throw new InboxAliasValidationError( - "Inbox aliases must be 3-32 characters long.", - ); + throw new InboxAliasValidationError('Inbox aliases must be 3-32 characters long.') } if (!INBOX_ALIAS_PATTERN.test(normalizedAlias)) { throw new InboxAliasValidationError( - "Inbox aliases may only use lowercase letters, numbers, and hyphens.", - ); + 'Inbox aliases may only use lowercase letters, numbers, and hyphens.', + ) } if (RESERVED_INBOX_ALIASES.has(normalizedAlias)) { - throw new InboxAliasValidationError("That inbox alias is reserved."); + throw new InboxAliasValidationError('That inbox alias is reserved.') } - return normalizedAlias; + return normalizedAlias } export function createDefaultInboxLocalPart(inboxId: string) { - if (!inboxId.startsWith("in_")) { - throw new Error('Expected inbox IDs to start with "in_".'); + if (!inboxId.startsWith('in_')) { + throw new Error('Expected inbox IDs to start with "in_".') } - return `u_${inboxId.slice(3)}`; + return `u_${inboxId.slice(3)}` } -export async function listInboxesForUser(database: AppDb, userId: string) { - return database +export async function listInboxesForUser(userId: string) { + return getDb() .select() .from(inboxes) .where(eq(inboxes.userId, userId)) - .orderBy(asc(inboxes.createdAt), asc(inboxes.id)); + .orderBy(asc(inboxes.createdAt), asc(inboxes.id)) } -export async function getInboxForUser( - database: AppDb, - userId: string, - inboxId: string, -) { - const [inbox] = await database +export async function getInboxForUser(userId: string, inboxId: string) { + const [inbox] = await getDb() .select() .from(inboxes) .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId))) - .limit(1); + .limit(1) - return inbox ?? null; + return inbox ?? null } -export async function createInboxForUser(database: AppDb, userId: string) { - const inboxId = createInboxId(); +export async function createInboxForUser(userId: string) { + const nextDb = getDb() + const inboxId = createInboxId() - await database.insert(inboxes).values({ + await nextDb.insert(inboxes).values({ id: inboxId, userId, defaultLocalPart: createDefaultInboxLocalPart(inboxId), customLocalPart: null, isActive: true, - }); + }) - const createdInbox = await getInboxForUser(database, userId, inboxId); + const createdInbox = await getInboxForUser(userId, inboxId) if (!createdInbox) { - throw new Error("Failed to create inbox."); + throw new Error('Failed to create inbox.') } - return createdInbox; + return createdInbox } -export async function findInboxByLocalPart(database: AppDb, localPart: string) { +export async function findInboxByLocalPart(localPart: string) { + const nextDb = getDb() const normalizedLocalPart = localPart.trim().toLowerCase() if (!normalizedLocalPart) { return null } - const [customInbox] = await database + const [customInbox] = await nextDb .select() .from(inboxes) .where( @@ -132,7 +128,7 @@ export async function findInboxByLocalPart(database: AppDb, localPart: string) { return customInbox } - const [defaultInbox] = await database + const [defaultInbox] = await nextDb .select() .from(inboxes) .where( @@ -146,32 +142,33 @@ export async function findInboxByLocalPart(database: AppDb, localPart: string) { return defaultInbox ?? null } -export async function provisionInitialInbox(database: AppDb, userId: string) { - const [existingInbox] = await database +export async function provisionInitialInbox(userId: string) { + const nextDb = getDb() + const [existingInbox] = await nextDb .select() .from(inboxes) .where(eq(inboxes.userId, userId)) - .limit(1); + .limit(1) - return existingInbox ?? createInboxForUser(database, userId); + return existingInbox ?? createInboxForUser(userId) } export async function updateInboxAliasForUser( - database: AppDb, userId: string, inboxId: string, alias: string | null, ) { - const inbox = await getInboxForUser(database, userId, inboxId); + const nextDb = getDb() + const inbox = await getInboxForUser(userId, inboxId) if (!inbox) { - return null; + return null } - const normalizedAlias = alias === null ? null : validateInboxAlias(alias); + const normalizedAlias = alias === null ? null : validateInboxAlias(alias) if (normalizedAlias) { - const [existingAlias] = await database + const [existingAlias] = await nextDb .select({ id: inboxes.id }) .from(inboxes) .where( @@ -180,19 +177,19 @@ export async function updateInboxAliasForUser( ne(inboxes.id, inboxId), ), ) - .limit(1); + .limit(1) if (existingAlias) { - throw new InboxAliasConflictError("That inbox alias is already taken."); + throw new InboxAliasConflictError('That inbox alias is already taken.') } } - await database + await nextDb .update(inboxes) .set({ customLocalPart: normalizedAlias }) - .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId))); + .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId))) - return getInboxForUser(database, userId, inboxId); + return getInboxForUser(userId, inboxId) } export function serializeInbox(inbox: typeof inboxes.$inferSelect) { @@ -204,5 +201,5 @@ export function serializeInbox(inbox: typeof inboxes.$inferSelect) { isActive: inbox.isActive, createdAt: inbox.createdAt.toISOString(), updatedAt: inbox.updatedAt.toISOString(), - }; + } } diff --git a/src/lib/email/outbound.test.ts b/src/lib/email/outbound.test.ts new file mode 100644 index 0000000..8a712b9 --- /dev/null +++ b/src/lib/email/outbound.test.ts @@ -0,0 +1,308 @@ +import { eq } from 'drizzle-orm' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { emailMessages, emailThreads } from '#/db/schema' + +const testState = vi.hoisted(() => ({ + harness: null as EmailTestHarness | null, +})) + +vi.mock('#/lib/runtime', () => ({ + getDb() { + if (!testState.harness) { + throw new Error('Email test harness not initialized.') + } + + return testState.harness.db + }, + getWorkerEnv() { + if (!testState.harness) { + throw new Error('Email test harness not initialized.') + } + + return testState.harness.env + }, +})) + +import { + MAX_OUTBOUND_BODY_BYTES, + sendMessage, + SendMessageOwnershipError, + SendMessageValidationError, +} from './outbound' +import { createEmailTestHarness, createInboxRecord, createUserRecord, type EmailTestHarness } from './test-harness' + +describe('outbound email pipeline', () => { + let harness: EmailTestHarness + + beforeEach(() => { + harness = createEmailTestHarness() + testState.harness = harness + }) + + afterEach(() => { + harness.cleanup() + testState.harness = null + }) + + it('sends an outbound message, persists it, and emits an accepted event', async () => { + const userId = await createUserRecord(harness.db) + const inboxId = await createInboxRecord(harness.db, userId, { + customLocalPart: 'agent', + }) + + const result = await sendMessage({ + userId, + input: { + inboxId, + to: ['Customer@Example.com'], + subject: 'Project update', + text: 'Hello from Clankr', + }, + }) + const [storedMessage] = await harness.db.select().from(emailMessages) + const [storedThread] = await harness.db.select().from(emailThreads) + + expect(result).toMatchObject({ + inboxId, + providerMessageId: 'test-email-1', + status: 'accepted', + errorCode: null, + errorMessage: null, + }) + expect(harness.email.sent).toHaveLength(1) + expect(harness.email.sent[0]).toMatchObject({ + from: 'agent@clankr.email', + to: ['customer@example.com'], + subject: 'Project update', + text: 'Hello from Clankr', + headers: { + 'Message-ID': storedMessage?.internetMessageId, + }, + }) + expect(storedMessage).toMatchObject({ + id: result.id, + inboxId, + threadId: result.threadId, + direction: 'outbound', + providerMessageId: 'test-email-1', + fromEmail: 'agent@clankr.email', + subject: 'Project update', + textBody: 'Hello from Clankr', + status: 'accepted', + }) + expect(storedThread?.id).toBe(result.threadId) + expect(harness.queue.sent[0]?.body).toMatchObject({ + type: 'message.sent.accepted', + data: { + inboxId, + threadId: result.threadId, + messageId: result.id, + providerMessageId: 'test-email-1', + }, + }) + }) + + it('rejects sends from inboxes the user does not own', async () => { + const ownerUserId = await createUserRecord(harness.db, { + id: 'user_owner_01', + }) + const otherUserId = await createUserRecord(harness.db, { + id: 'user_other_01', + }) + const inboxId = await createInboxRecord(harness.db, ownerUserId) + + await expect( + sendMessage({ + userId: otherUserId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Unauthorized send', + text: 'This should fail', + }, + }), + ).rejects.toBeInstanceOf(SendMessageOwnershipError) + + expect(harness.email.sent).toHaveLength(0) + expect(await harness.db.select().from(emailMessages)).toHaveLength(0) + }) + + it('validates recipients and body limits before sending', async () => { + const userId = await createUserRecord(harness.db) + const inboxId = await createInboxRecord(harness.db, userId) + + await expect( + sendMessage({ + userId, + input: { + inboxId, + to: ['not-an-email'], + subject: 'Bad recipient', + text: 'Hello', + }, + }), + ).rejects.toBeInstanceOf(SendMessageValidationError) + + await expect( + sendMessage({ + userId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Too large', + text: 'a'.repeat(MAX_OUTBOUND_BODY_BYTES + 1), + }, + }), + ).rejects.toThrow(`Message bodies must be ${MAX_OUTBOUND_BODY_BYTES} bytes or smaller.`) + + expect(harness.email.sent).toHaveLength(0) + expect(await harness.db.select().from(emailMessages)).toHaveLength(0) + }) + + it('maps provider failures and persists a failed send result', async () => { + const userId = await createUserRecord(harness.db) + const inboxId = await createInboxRecord(harness.db, userId, { + customLocalPart: 'agent', + }) + + harness.email.failWith( + Object.assign(new Error('destination address not allowed'), { + code: 'destination_address_not_allowed', + }), + ) + + const result = await sendMessage({ + userId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Provider failure', + text: 'Hello anyway', + }, + }) + const [storedMessage] = await harness.db.select().from(emailMessages) + + expect(result).toMatchObject({ + inboxId, + providerMessageId: null, + status: 'failed', + errorCode: 'recipient_not_allowed', + errorMessage: 'The email provider rejected one or more recipient addresses.', + sentAt: null, + }) + expect(storedMessage).toMatchObject({ + id: result.id, + status: 'failed', + providerMessageId: null, + errorCode: 'recipient_not_allowed', + errorMessage: 'The email provider rejected one or more recipient addresses.', + sentAt: null, + }) + expect(harness.queue.sent[0]?.body).toMatchObject({ + type: 'message.sent.failed', + data: { + inboxId, + threadId: result.threadId, + messageId: result.id, + errorCode: 'recipient_not_allowed', + }, + }) + }) + + it('does not reference failed outbound messages when retrying a reply thread', async () => { + const userId = await createUserRecord(harness.db) + const inboxId = await createInboxRecord(harness.db, userId, { + customLocalPart: 'agent', + }) + + harness.email.failWith( + Object.assign(new Error('provider outage'), { + code: 'provider_error', + }), + ) + + const failedResult = await sendMessage({ + userId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Re: Retry me', + text: 'First attempt', + }, + }) + + const retryResult = await sendMessage({ + userId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Re: Retry me', + text: 'Second attempt', + replyToThreadId: failedResult.threadId, + }, + }) + + expect(retryResult.threadId).toBe(failedResult.threadId) + expect(harness.email.sent[1]).toMatchObject({ + headers: { + 'Message-ID': expect.any(String), + }, + }) + expect(harness.email.sent[1]).not.toMatchObject({ + headers: { + 'In-Reply-To': expect.any(String), + }, + }) + expect(harness.email.sent[1]).not.toMatchObject({ + headers: { + References: expect.any(String), + }, + }) + }) + + it('reuses reply threads and sends reply headers', async () => { + const userId = await createUserRecord(harness.db) + const inboxId = await createInboxRecord(harness.db, userId, { + customLocalPart: 'agent', + }) + + const firstResult = await sendMessage({ + userId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Hello there', + text: 'First message', + }, + }) + const [firstMessage] = await harness.db + .select() + .from(emailMessages) + .where(eq(emailMessages.id, firstResult.id)) + + const secondResult = await sendMessage({ + userId, + input: { + inboxId, + to: ['customer@example.com'], + subject: 'Re: Hello there', + text: 'Reply message', + replyToThreadId: firstResult.threadId, + }, + }) + const [secondMessage] = await harness.db + .select() + .from(emailMessages) + .where(eq(emailMessages.id, secondResult.id)) + + expect(secondResult.threadId).toBe(firstResult.threadId) + expect(secondMessage?.threadId).toBe(firstResult.threadId) + expect(harness.email.sent[1]).toMatchObject({ + headers: { + 'In-Reply-To': firstMessage?.internetMessageId, + References: firstMessage?.internetMessageId, + }, + }) + }) +}) diff --git a/src/lib/email/outbound.ts b/src/lib/email/outbound.ts new file mode 100644 index 0000000..b30c2b7 --- /dev/null +++ b/src/lib/email/outbound.ts @@ -0,0 +1,536 @@ +import { and, asc, desc, eq } from 'drizzle-orm' +import { z } from 'zod' + +import { getDb, getWorkerEnv } from '#/lib/runtime' +import type { AppDb } from '#/db/index' +import { emailMessages, emailThreads, inboxes } from '#/db/schema' + +import { + createMessageSentAcceptedEvent, + createMessageSentFailedEvent, +} from './events' +import { createMessageId, createThreadId } from './ids' +import { getInboxForUser } from './inboxes' +import { INLINE_BODY_LIMIT_BYTES, normalizeThreadSubject } from './inbound' + +export const MAX_OUTBOUND_RECIPIENTS = 50 +export const MAX_OUTBOUND_BODY_BYTES = 128_000 + +const recipientSchema = z.string().trim().toLowerCase().email() + +export const sendMessageInputSchema = z + .object({ + inboxId: z.string().trim().min(1), + to: z.array(recipientSchema).max(MAX_OUTBOUND_RECIPIENTS).default([]), + cc: z.array(recipientSchema).max(MAX_OUTBOUND_RECIPIENTS).default([]), + bcc: z.array(recipientSchema).max(MAX_OUTBOUND_RECIPIENTS).default([]), + subject: z.string().default('').transform((value) => value.trim()), + text: z.string().optional(), + html: z.string().optional(), + replyToThreadId: z.string().trim().min(1).optional(), + }) + .superRefine((value, ctx) => { + const totalRecipients = new Set([...value.to, ...value.cc, ...value.bcc]).size + + if (totalRecipients === 0) { + ctx.addIssue({ + code: 'custom', + message: 'At least one recipient is required.', + path: ['to'], + }) + } + + if (totalRecipients > MAX_OUTBOUND_RECIPIENTS) { + ctx.addIssue({ + code: 'custom', + message: `A message can have at most ${MAX_OUTBOUND_RECIPIENTS} recipients.`, + path: ['to'], + }) + } + + if (!hasMessageBody(value.text, value.html)) { + ctx.addIssue({ + code: 'custom', + message: 'A text or HTML body is required.', + path: ['text'], + }) + } + + if (getBodySizeBytes(value.text, value.html) > MAX_OUTBOUND_BODY_BYTES) { + ctx.addIssue({ + code: 'custom', + message: `Message bodies must be ${MAX_OUTBOUND_BODY_BYTES} bytes or smaller.`, + path: ['text'], + }) + } + }) + +type ThreadDatabase = Pick + +export type SendMessageInput = z.input + +export const sendMessageResultSchema = z.object({ + id: z.string(), + inboxId: z.string(), + threadId: z.string(), + providerMessageId: z.string().nullable(), + status: z.enum(['accepted', 'failed']), + errorCode: z.string().nullable(), + errorMessage: z.string().nullable(), + sentAt: z.string().datetime().nullable(), +}) + +export type SendMessageResult = z.infer + +type SendMessageStatusUpdate = { + providerMessageId: string | null + status: SendMessageResult['status'] + errorCode: string | null + errorMessage: string | null + sentAt: Date | null +} + +type ReplyContext = { + threadId: string + inReplyTo: string | null + references: string[] +} + +type PendingOutboundMessage = { + id: string + inboxId: string + threadId: string + internetMessageId: string +} + +export class SendMessageValidationError extends Error {} + +export class SendMessageOwnershipError extends Error {} + +export class SendMessageThreadNotFoundError extends Error {} + +export async function sendMessage(params: { + userId: string + input: SendMessageInput +}): Promise { + const database = getDb() + const env = getWorkerEnv() as Pick + const input = validateSendMessageInput(params.input) + const inbox = await getInboxForUser(params.userId, input.inboxId) + + if (!inbox || !inbox.isActive) { + throw new SendMessageOwnershipError('Inbox not found.') + } + + const fromEmail = getInboxEmailAddress(inbox) + const messageId = createMessageId() + const internetMessageId = createInternetMessageId(messageId, fromEmail) + const sentAt = new Date() + const bodyStorage = buildBodyStorage(messageId, input.text, input.html) + const participantHash = await createParticipantHash([ + fromEmail, + ...input.to, + ...input.cc, + ]) + const replyContext = input.replyToThreadId + ? await getReplyContext(input.inboxId, input.replyToThreadId) + : null + + if (input.replyToThreadId && !replyContext) { + throw new SendMessageThreadNotFoundError('Thread not found.') + } + + if (bodyStorage.oversizedBodyR2Key) { + await env.EMAIL_STORAGE.put( + bodyStorage.oversizedBodyR2Key, + JSON.stringify({ + htmlBody: input.html ?? null, + textBody: input.text ?? null, + }), + ) + } + + const pendingMessage = await database.transaction(async (tx) => { + const threadId = await ensureThread(tx, { + inboxId: input.inboxId, + participantHash, + replyContext, + sentAt, + subject: input.subject, + }) + + await tx.insert(emailMessages).values({ + id: messageId, + inboxId: input.inboxId, + threadId, + direction: 'outbound', + providerMessageId: null, + internetMessageId, + fromEmail, + toEmailsJson: JSON.stringify(input.to), + ccEmailsJson: JSON.stringify(input.cc), + bccEmailsJson: JSON.stringify(input.bcc), + subject: input.subject, + snippet: createSnippet(input.text, input.html), + textBody: bodyStorage.textBody, + htmlBody: bodyStorage.htmlBody, + bodyStorageMode: bodyStorage.mode, + rawMimeR2Key: null, + oversizedBodyR2Key: bodyStorage.oversizedBodyR2Key, + bodySizeBytes: bodyStorage.bodySizeBytes, + status: 'pending', + errorCode: null, + errorMessage: null, + sentAt: null, + receivedAt: null, + }) + + return { + id: messageId, + inboxId: input.inboxId, + threadId, + internetMessageId, + } + }) + + let statusUpdate: SendMessageStatusUpdate + + try { + const result = await env.EMAIL.send({ + from: fromEmail, + to: input.to, + cc: input.cc.length > 0 ? input.cc : undefined, + bcc: input.bcc.length > 0 ? input.bcc : undefined, + subject: input.subject, + text: input.text, + html: input.html, + headers: buildOutboundHeaders(pendingMessage.internetMessageId, replyContext), + }) + + statusUpdate = { + providerMessageId: result.messageId, + status: 'accepted', + errorCode: null, + errorMessage: null, + sentAt, + } + } catch (error) { + const mappedError = mapSendProviderError(error) + + statusUpdate = { + providerMessageId: null, + status: 'failed', + errorCode: mappedError.code, + errorMessage: mappedError.message, + sentAt: null, + } + } + + await updateOutboundMessageStatus(database, pendingMessage.id, statusUpdate) + + await emitSendEvent(env, pendingMessage, statusUpdate) + + return { + id: pendingMessage.id, + inboxId: pendingMessage.inboxId, + threadId: pendingMessage.threadId, + providerMessageId: statusUpdate.providerMessageId, + status: statusUpdate.status, + errorCode: statusUpdate.errorCode, + errorMessage: statusUpdate.errorMessage, + sentAt: statusUpdate.sentAt?.toISOString() ?? null, + } +} + +function validateSendMessageInput(input: SendMessageInput) { + const parsed = sendMessageInputSchema.safeParse(input) + + if (parsed.success) { + return parsed.data + } + + throw new SendMessageValidationError(parsed.error.issues[0]?.message ?? 'Invalid message payload.') +} + +async function getReplyContext(inboxId: string, threadId: string) { + const database = getDb() + const [thread] = await database + .select({ + id: emailThreads.id, + }) + .from(emailThreads) + .where(and(eq(emailThreads.id, threadId), eq(emailThreads.inboxId, inboxId))) + .limit(1) + + if (!thread) { + return null + } + + const threadMessages = await database + .select({ + direction: emailMessages.direction, + internetMessageId: emailMessages.internetMessageId, + status: emailMessages.status, + }) + .from(emailMessages) + .where(and(eq(emailMessages.threadId, threadId), eq(emailMessages.inboxId, inboxId))) + .orderBy(asc(emailMessages.createdAt), asc(emailMessages.id)) + + const references = threadMessages + .filter((message) => message.direction === 'inbound' || message.status === 'accepted') + .map((message) => message.internetMessageId) + .filter((value): value is string => Boolean(value)) + + return { + threadId: thread.id, + inReplyTo: references.at(-1) ?? null, + references, + } +} + +async function findExistingThreadId( + database: ThreadDatabase, + params: { + inboxId: string + participantHash: string + subjectNormalized: string + }, +) { + const [thread] = await database + .select({ id: emailThreads.id }) + .from(emailThreads) + .where( + and( + eq(emailThreads.inboxId, params.inboxId), + eq(emailThreads.participantHash, params.participantHash), + eq(emailThreads.subjectNormalized, params.subjectNormalized), + ), + ) + .orderBy(desc(emailThreads.lastMessageAt), desc(emailThreads.createdAt)) + .limit(1) + + return thread?.id ?? null +} + +function buildOutboundHeaders( + internetMessageId: string, + replyContext: ReplyContext | null, +) { + const headers: Record = { + 'Message-ID': internetMessageId, + } + + if (replyContext?.inReplyTo) { + headers['In-Reply-To'] = replyContext.inReplyTo + } + + if (replyContext && replyContext.references.length > 0) { + headers.References = replyContext.references.join(' ') + } + + return headers +} + +async function ensureThread( + database: ThreadDatabase, + params: { + inboxId: string + participantHash: string + replyContext: ReplyContext | null + sentAt: Date + subject: string + }, +) { + const threadId = params.replyContext?.threadId + ?? (await findExistingThreadId(database, { + inboxId: params.inboxId, + participantHash: params.participantHash, + subjectNormalized: normalizeThreadSubject(params.subject), + })) + ?? createThreadId() + + const [existingThread] = await database + .select({ id: emailThreads.id }) + .from(emailThreads) + .where(eq(emailThreads.id, threadId)) + .limit(1) + + if (existingThread) { + await database + .update(emailThreads) + .set({ lastMessageAt: params.sentAt }) + .where(eq(emailThreads.id, threadId)) + } else { + await database.insert(emailThreads).values({ + id: threadId, + inboxId: params.inboxId, + subjectNormalized: normalizeThreadSubject(params.subject), + participantHash: params.participantHash, + lastMessageAt: params.sentAt, + }) + } + + return threadId +} + +async function updateOutboundMessageStatus( + database: AppDb, + messageId: string, + statusUpdate: SendMessageStatusUpdate, +) { + await database + .update(emailMessages) + .set({ + providerMessageId: statusUpdate.providerMessageId, + status: statusUpdate.status, + errorCode: statusUpdate.errorCode, + errorMessage: statusUpdate.errorMessage, + sentAt: statusUpdate.sentAt, + }) + .where(eq(emailMessages.id, messageId)) +} + +async function emitSendEvent( + env: Pick, + pendingMessage: PendingOutboundMessage, + statusUpdate: SendMessageStatusUpdate, +) { + try { + if (statusUpdate.status === 'accepted' && statusUpdate.providerMessageId) { + await env.EMAIL_EVENTS.send( + createMessageSentAcceptedEvent({ + inboxId: pendingMessage.inboxId, + threadId: pendingMessage.threadId, + messageId: pendingMessage.id, + providerMessageId: statusUpdate.providerMessageId, + }), + ) + + return + } + + if (statusUpdate.status === 'failed' && statusUpdate.errorCode) { + await env.EMAIL_EVENTS.send( + createMessageSentFailedEvent({ + inboxId: pendingMessage.inboxId, + threadId: pendingMessage.threadId, + messageId: pendingMessage.id, + errorCode: statusUpdate.errorCode, + }), + ) + } + } catch (error) { + console.error('Failed to emit outbound email event.', { + error, + messageId: pendingMessage.id, + status: statusUpdate.status, + }) + } +} + +function getInboxEmailAddress(inbox: typeof inboxes.$inferSelect) { + const localPart = inbox.customLocalPart ?? inbox.defaultLocalPart + + return `${localPart}@clankr.email` +} + +function createInternetMessageId(messageId: string, fromEmail: string) { + const [, domain = 'clankr.email'] = fromEmail.split('@') + + return `<${messageId}@${domain}>` +} + +function hasMessageBody(textBody: string | undefined, htmlBody: string | undefined) { + return Boolean(textBody?.trim() || htmlBody?.trim()) +} + +function getBodySizeBytes(textBody: string | undefined, htmlBody: string | undefined) { + return new TextEncoder().encode( + JSON.stringify({ + htmlBody: htmlBody ?? null, + textBody: textBody ?? null, + }), + ).byteLength +} + +function buildBodyStorage(messageId: string, textBody: string | undefined, htmlBody: string | undefined) { + const nextTextBody = textBody ?? null + const nextHtmlBody = htmlBody ?? null + const bodySizeBytes = getBodySizeBytes(textBody, htmlBody) + + if (bodySizeBytes > INLINE_BODY_LIMIT_BYTES) { + return { + mode: 'oversized' as const, + textBody: null, + htmlBody: null, + oversizedBodyR2Key: `bodies/${messageId}.json`, + bodySizeBytes, + } + } + + return { + mode: 'inline' as const, + textBody: nextTextBody, + htmlBody: nextHtmlBody, + oversizedBodyR2Key: null, + bodySizeBytes, + } +} + +function createSnippet(textBody: string | undefined, htmlBody: string | undefined) { + const source = (textBody ?? htmlBody ?? '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() + + return source.slice(0, 160) +} + +async function createParticipantHash(addresses: string[]) { + const participants = [...new Set(addresses.map((address) => address.trim().toLowerCase()).filter(Boolean))] + .sort() + .join('|') + + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(participants), + ) + + return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, '0')).join('') +} + +function mapSendProviderError(error: unknown) { + const rawCode = normalizeErrorCode(error) + + if (rawCode.includes('sender') || rawCode.includes('from')) { + return { + code: 'sender_not_allowed', + message: 'The email provider rejected the sender address.', + } + } + + if (rawCode.includes('recipient') || rawCode.includes('destination') || rawCode.includes('to')) { + return { + code: 'recipient_not_allowed', + message: 'The email provider rejected one or more recipient addresses.', + } + } + + return { + code: 'provider_error', + message: 'The email provider failed to accept the message.', + } +} + +function normalizeErrorCode(error: unknown) { + if (!error || typeof error !== 'object') { + return '' + } + + const maybeCode = 'code' in error && typeof error.code === 'string' + ? error.code + : 'name' in error && typeof error.name === 'string' + ? error.name + : 'message' in error && typeof error.message === 'string' + ? error.message + : '' + + return maybeCode.trim().toLowerCase() +} diff --git a/src/lib/email/test-harness.test.ts b/src/lib/email/test-harness.test.ts index f81cbd8..b85a4a7 100644 --- a/src/lib/email/test-harness.test.ts +++ b/src/lib/email/test-harness.test.ts @@ -1,4 +1,13 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('#/lib/runtime', () => ({ + getDb() { + throw new Error('getDb should not be called in the test harness smoke test.') + }, + getWorkerEnv() { + throw new Error('getWorkerEnv should not be called in the test harness smoke test.') + }, +})) import { createMessageReceivedEvent } from './events' import { createEmailTestHarness, createUserRecord } from './test-harness' diff --git a/src/lib/email/test-harness.ts b/src/lib/email/test-harness.ts index bf7de0d..4a15796 100644 --- a/src/lib/email/test-harness.ts +++ b/src/lib/email/test-harness.ts @@ -15,6 +15,7 @@ type StoredObject = { } type TestHarnessEnv = Pick & { + EMAIL: Pick EMAIL_EVENTS: Pick, 'send'> EMAIL_STORAGE: Pick } @@ -29,10 +30,22 @@ export class TestQueue { export class TestEmailBinding { readonly sent: unknown[] = [] + private nextError: unknown | null = null + + failWith(error: unknown) { + this.nextError = error + } async send(message: unknown) { this.sent.push(message) + if (this.nextError) { + const error = this.nextError + this.nextError = null + + throw error + } + return { messageId: `test-email-${this.sent.length}`, } @@ -182,6 +195,7 @@ export function createEmailTestHarness(): EmailTestHarness { email, env: { APP_DB: appDb.$client, + EMAIL: email, EMAIL_EVENTS: queue, EMAIL_STORAGE: storage, }, diff --git a/src/lib/runtime.ts b/src/lib/runtime.ts new file mode 100644 index 0000000..5df68dc --- /dev/null +++ b/src/lib/runtime.ts @@ -0,0 +1,13 @@ +import { env } from 'cloudflare:workers' + +import { createDb } from '#/db/index' + +export const db = createDb(env.APP_DB) + +export function getDb() { + return db +} + +export function getWorkerEnv() { + return env +} diff --git a/src/orpc/procedures/inboxes.ts b/src/orpc/procedures/inboxes.ts index 97db180..38b6513 100644 --- a/src/orpc/procedures/inboxes.ts +++ b/src/orpc/procedures/inboxes.ts @@ -1,7 +1,6 @@ import { ORPCError } from '@orpc/server' import { z } from 'zod' -import { db } from '#/db/client' import { InboxAliasConflictError, InboxAliasValidationError, @@ -33,7 +32,7 @@ export const inboxRouter = { .input(z.object({}).optional()) .output(inboxSchema) .handler(async ({ context }) => { - const inbox = await createInboxForUser(db, context.session.user.id) + const inbox = await createInboxForUser(context.session.user.id) return serializeInbox(inbox) }), @@ -51,7 +50,7 @@ export const inboxRouter = { ) .output(inboxSchema) .handler(async ({ context, input }) => { - const inbox = await getInboxForUser(db, context.session.user.id, input.inboxId) + const inbox = await getInboxForUser(context.session.user.id, input.inboxId) if (!inbox) { throw new ORPCError('NOT_FOUND', { @@ -70,7 +69,7 @@ export const inboxRouter = { }) .output(z.array(inboxSchema)) .handler(async ({ context }) => { - const inboxes = await listInboxesForUser(db, context.session.user.id) + const inboxes = await listInboxesForUser(context.session.user.id) return inboxes.map(serializeInbox) }), @@ -90,12 +89,7 @@ export const inboxRouter = { .output(inboxSchema) .handler(async ({ context, input }) => { try { - const inbox = await updateInboxAliasForUser( - db, - context.session.user.id, - input.inboxId, - input.alias, - ) + const inbox = await updateInboxAliasForUser(context.session.user.id, input.inboxId, input.alias) if (!inbox) { throw new ORPCError('NOT_FOUND', { diff --git a/src/orpc/procedures/messages.ts b/src/orpc/procedures/messages.ts index c3b950c..eca2253 100644 --- a/src/orpc/procedures/messages.ts +++ b/src/orpc/procedures/messages.ts @@ -1 +1,43 @@ -export const messageRouter = {} +import { ORPCError } from '@orpc/server' +import { + sendMessage, + sendMessageInputSchema, + sendMessageResultSchema, + SendMessageOwnershipError, + SendMessageThreadNotFoundError, + SendMessageValidationError, +} from '#/lib/email/outbound' +import { protectedOrpc } from '#/orpc/context' + +export const messageRouter = { + send: protectedOrpc + .route({ + method: 'POST', + path: '/messages/send', + summary: 'Send message', + }) + .input(sendMessageInputSchema) + .output(sendMessageResultSchema) + .handler(async ({ context, input }) => { + try { + return await sendMessage({ + userId: context.session.user.id, + input, + }) + } catch (error) { + if (error instanceof SendMessageValidationError) { + throw new ORPCError('BAD_REQUEST', { + message: error.message, + }) + } + + if (error instanceof SendMessageOwnershipError || error instanceof SendMessageThreadNotFoundError) { + throw new ORPCError('NOT_FOUND', { + message: error.message, + }) + } + + throw error + } + }), +} diff --git a/src/worker.ts b/src/worker.ts index 399004b..c9ce50a 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -8,8 +8,9 @@ const fetch = createStartHandler(defaultStreamHandler) export default { fetch, async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) { + void env void ctx - await handleInboundEmail(message, env) + await handleInboundEmail(message) }, async queue(batch: MessageBatch) { for (const message of batch.messages) {