Skip to content

Add thread read APIs and API key auth - #5

Closed
KMKoushik wants to merge 6 commits into
mainfrom
feat/thread-read-api-keys
Closed

KMKoushik wants to merge 6 commits into
mainfrom
feat/thread-read-api-keys

Conversation

@KMKoushik

@KMKoushik KMKoushik commented Mar 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • ship the Cloudflare email backend through outbound send plus Phase 5 read APIs, including threads.listByInbox, threads.listMessages, and messages.get with D1 reads and R2 oversized-body fallback
  • add user-scoped server API keys with create/list/revoke procedures and bearer or x-api-key auth for protected oRPC endpoints
  • expand the local harness and automated coverage for send, read, pagination, ownership, R2 fallback, and API key auth flows while keeping dashboard UI work deferred

Validation

  • pnpm test
  • pnpm exec tsc --noEmit
  • pnpm build

Summary by CodeRabbit

  • New Features

    • API key management: create, revoke, and list API keys for secure programmatic access
    • Outbound email sending with automatic thread management and reply functionality
    • Email reading capabilities including thread listing, message pagination, and message details
    • API key-based authentication option for protected endpoints
  • Infrastructure

    • Automated CI/CD pipeline with testing and type checking

@coderabbitai

coderabbitai Bot commented Mar 8, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces API key authentication infrastructure, centralizes database/environment access through a new runtime module, implements comprehensive email sending and reading capabilities with pagination, and refactors database access patterns across multiple modules to eliminate explicit DB parameters. Includes new oRPC endpoints and GitHub Actions CI workflow.

Changes

Cohort / File(s) Summary
API Keys System
src/lib/api-keys.ts, src/lib/api-keys.test.ts, src/db/schema.ts, drizzle/0003_sweet_microchip.sql, drizzle/meta/0003_snapshot.json, drizzle/meta/_journal.json
Introduces complete API key management with creation, listing, revocation, and authentication flows. Includes database migration creating api_keys table with user_id and key_prefix indexes, schema definitions with timestamp defaults, and comprehensive test coverage validating secure key storage, hashing, and revocation behavior.
Runtime & DB Access Pattern
src/lib/runtime.ts, src/db/client.ts
Introduces centralized runtime module exporting singleton db instance and getDb/getWorkerEnv accessors. Updates db/client.ts to re-export from runtime instead of creating local instance, establishing new dependency pattern.
Inbox Functions Refactoring
src/lib/email/inboxes.ts, src/lib/email/inboxes.test.ts
Removes database parameter from all inbox function signatures (listInboxesForUser, getInboxForUser, createInboxForUser, findInboxByLocalPart, provisionInitialInbox, updateInboxAliasForUser) to use centralized getDb(). Updates tests to mock runtime module with error-throwing stubs.
Inbound Email Refactoring
src/lib/email/inbound.ts, src/lib/email/inbound.test.ts, src/worker.ts
Removes env parameter from handleInboundEmail, switches to getDb() and getWorkerEnv() for dependencies. Updates worker to call without env argument. Modifies test harness integration with vi.hoisted mocking pattern.
Email Operations: Outbound
src/lib/email/outbound.ts, src/lib/email/outbound.test.ts
Implements complete outbound email sending pipeline: inbox ownership validation, thread management, MIME header construction, R2 body storage for large payloads, email provider integration with error handling, event emission (accepted/failed), and retry support. Includes comprehensive test coverage for success paths, validation, ownership enforcement, provider failures, and reply threading.
Email Operations: Read
src/lib/email/read.ts, src/lib/email/read.test.ts
Introduces email reading layer with three public functions: listThreadsByInboxForUser (with pagination), listThreadMessagesForUser (with cursor-based pagination), getMessageForUser (with body loading from inline/R2 storage fallback). Includes input/output schemas, ownership validation, and error classes for distinct failure modes.
Email Events & Entity IDs
src/lib/email/events.ts, src/lib/email/ids.ts, src/lib/email/ids.test.ts
Extends EMAIL_EVENT_TYPES with messageSentAccepted and messageSentFailed event types. Adds createMessageSentAcceptedEvent and createMessageSentFailedEvent factory functions. Introduces apiKey entity prefix ('ak') and createApiKeyId() generator.
Test Infrastructure
src/lib/email/test-harness.ts, src/lib/email/test-harness.test.ts
Adds TestStorageBinding type and email error scheduling capability. Extends TestHarnessEnv to include EMAIL binding. Adds failWith() method for injecting provider failures. Updates test setup to mock runtime dependencies with error-throwing stubs.
oRPC API Routes
src/orpc/procedures/api-keys.ts, src/orpc/procedures/messages.ts, src/orpc/procedures/threads.ts, src/orpc/router.ts
Adds three new route handlers: apiKeyRouter (create, list, revoke endpoints), messageRouter (get detail and send operations), threadRouter (list by inbox and list messages). Implements error mapping and input/output validation. Integrates apiKeyRouter into main router.
Authentication Context
src/orpc/context.ts, src/orpc/api-keys.test.ts
Adds API key authentication path to protectedOrpc with extractApiKey helper for Authorization and x-api-key headers. Supports both API key and session authentication paths. Introduces ProtectedORPCContext type unifying both auth methods. Includes end-to-end test exercising API key creation, usage, revocation, and access control.
Inbox Procedures Simplification
src/orpc/procedures/inboxes.ts
Simplifies inbox route handlers to use context.userId directly instead of db session lookup and removes database parameter forwarding to inbox functions.
CI & Documentation
.github/workflows/ci.yml, mvp.md
Adds GitHub Actions workflow with Node.js 22, pnpm 9 setup, dependency installation, D1 migrations, tests, TypeScript checking, and project build. Updates MVP documentation by striking through deprecated requirements and test items.

Sequence Diagrams

sequenceDiagram
    actor Client
    participant API as API Handler
    participant AuthMod as Auth Module
    participant DB as Database
    
    Client->>API: POST /api-keys with name, expiry
    API->>AuthMod: createApiKeyForUser(userId, name, expiresAt)
    AuthMod->>AuthMod: Generate secret, compute hash, create prefix/lastFour
    AuthMod->>DB: Insert into api_keys table
    DB-->>AuthMod: Row stored
    AuthMod-->>API: Return raw key + metadata
    API-->>Client: 200 with key, metadata
    
    Client->>API: GET /api/inboxes with Authorization: Bearer {apiKey}
    API->>AuthMod: extractApiKey(request)
    AuthMod-->>API: Raw API key
    API->>AuthMod: authenticateApiKey(rawKey)
    AuthMod->>AuthMod: Parse, hash, validate expiry/revocation
    AuthMod->>DB: Fetch by key_prefix, check revoked_at
    DB-->>AuthMod: api_key row
    AuthMod->>DB: Update last_used_at timestamp
    AuthMod-->>API: { id, userId, name }
    API->>API: Route as authenticated user
    API-->>Client: 200 with user inboxes
Loading
sequenceDiagram
    actor User
    participant API as API Handler
    participant OutboundMod as Outbound Module
    participant InboxDB as Inbox DB
    participant ThreadDB as Thread DB
    participant EmailProvider as Email Provider
    participant Storage as R2 Storage
    participant EventQueue as Event Queue
    
    User->>API: POST /messages/send (inboxId, recipient, body)
    API->>OutboundMod: sendMessage(userId, input)
    OutboundMod->>InboxDB: Verify inbox ownership
    InboxDB-->>OutboundMod: Inbox confirmed
    OutboundMod->>ThreadDB: Ensure thread exists, get reply context
    ThreadDB-->>OutboundMod: Thread, headers (In-Reply-To, References)
    OutboundMod->>OutboundMod: Normalize body, store inline or check size
    alt Body > MAX_SIZE
        OutboundMod->>Storage: PUT large body to R2
        Storage-->>OutboundMod: URL
    end
    OutboundMod->>OutboundMod: Build MIME headers, create Message-ID
    OutboundMod->>EmailProvider: send(to, from, subject, headers, body)
    alt Provider accepts
        EmailProvider-->>OutboundMod: Success
        OutboundMod->>ThreadDB: Update message status=sent
        OutboundMod->>EventQueue: Emit message.sent.accepted event
    else Provider rejects
        EmailProvider-->>OutboundMod: Error
        OutboundMod->>ThreadDB: Update message status=failed, error_code
        OutboundMod->>EventQueue: Emit message.sent.failed event
    end
    OutboundMod-->>API: SendMessageResult
    API-->>User: 200 with message metadata
Loading
sequenceDiagram
    actor User
    participant API as API Handler
    participant ReadMod as Read Module
    participant DB as Database
    participant Storage as R2 Storage
    
    User->>API: GET /inboxes/{inboxId}/threads?limit=10
    API->>ReadMod: listThreadsByInboxForUser(userId, inboxId)
    ReadMod->>DB: Validate inbox ownership
    DB-->>ReadMod: Confirmed
    ReadMod->>DB: Query threads, count messages per thread, fetch latest message
    DB-->>ReadMod: Thread list with counts, cursors
    ReadMod-->>API: ThreadListResult with nextCursor
    API-->>User: 200 with thread summaries
    
    User->>API: GET /messages/{messageId}
    API->>ReadMod: getMessageForUser(userId, inboxId, messageId)
    ReadMod->>DB: Fetch message row, validate ownership
    DB-->>ReadMod: Message row
    ReadMod->>ReadMod: Check body storage mode (inline/missing/oversized)
    alt Inline body
        ReadMod-->>API: Message with body
    else Missing or oversized
        ReadMod->>Storage: GET from R2
        Storage-->>ReadMod: Body bytes
        ReadMod-->>API: Message with fetched body
    end
    API-->>User: 200 with message detail
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 API keys and emails in flight,
Threads and messages shining bright,
Runtime pooling databases true,
Read and send what users pursue,
One centralized hop-hop-hop to do!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add thread read APIs and API key auth' directly and clearly summarizes the main changes: thread read APIs (threads.listByInbox, threads.listMessages, messages.get) and API key authentication support.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/thread-read-api-keys

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (6)
src/lib/runtime.ts (1)

1-8: Consider lazy-initializing the Workers DB binding to reduce import-time coupling.

createDb(env.APP_DB) runs during module evaluation, causing any code path that imports #/lib/runtime (directly or indirectly) before mocking it to fail at import time. The repeated vi.mock('#/lib/runtime') calls in test files confirm this brittleness. While db is currently exported and re-exported via #/db/client, most code already uses getDb() instead. Moving DB creation behind getDb() and deprecating the direct db export keeps Workers-only dependencies at the edge without breaking existing patterns.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/runtime.ts` around lines 1 - 8, The module currently instantiates the
Workers DB at import time via createDb(env.APP_DB) and exports db, which breaks
tests that mock this module; change to lazy-initialize by removing the top-level
createDb call and instead create and cache the DB inside getDb() (e.g., if
cachedDb return it else set cachedDb = createDb(env.APP_DB) and return), keep
exporting getDb() as the primary accessor, keep or mark the direct db export
deprecated (do not instantiate it at module load) so imports that want the
binding still work but tests can mock getDb() without import-time side effects;
update references to use getDb() where feasible.
src/lib/email/read.test.ts (1)

47-112: Add a same-timestamp pagination case.

Both cursor tests use strictly increasing timestamps, but src/lib/email/read.ts breaks ties with id in both the query and cursor predicate. Without a fixture where multiple rows share the same timestamp, these tests won't catch duplicate/skip bugs in the tie-break path.

Also applies to: 133-195

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/read.test.ts` around lines 47 - 112, Add a test case that
inserts at least two threads/messages with identical createdAt timestamps (use
insertThreadWithMessage and the same createdAt value for two different
threadId/messageId pairs) and then call listThreadsByInboxForUser to exercise
cursor pagination; assert ordering uses the tie-break (id) consistently by
checking the exact thread id sequence across pages and that nextCursor does not
cause duplicates or skips. Ensure the duplicate-timestamp fixtures appear in the
same test (or a new test) near the existing cursor pagination assertions so the
tie-break path in listThreadsByInboxForUser is executed and validated.
src/lib/api-keys.test.ts (1)

66-91: Consider adding test coverage for expired API keys.

The authenticateApiKey function checks expiresAt (per src/lib/api-keys.ts Lines 157-159), but there's no test verifying that expired keys are rejected. This edge case is worth covering.

📝 Suggested additional test case
it('rejects expired api keys', async () => {
  const userId = await createUserRecord(harness.db, {
    id: 'user_api_keys_03',
  })

  const created = await createApiKeyForUser({
    name: 'Expiring key',
    userId,
    expiresAt: new Date(Date.now() - 1000).toISOString(), // Already expired
  })

  await expect(authenticateApiKey(created.apiKey)).resolves.toBeNull()
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/api-keys.test.ts` around lines 66 - 91, Add a test that verifies
authenticateApiKey rejects keys whose expiresAt is in the past: use
createApiKeyForUser to create a key with expiresAt set to a timestamp before now
(e.g. Date.now() - 1000), then call authenticateApiKey(created.apiKey) and
assert it resolves to null; place this alongside the existing tests for
valid/revoked keys in the same suite so expiresAt handling is covered.
src/orpc/context.ts (1)

65-73: Consider more robust Bearer token case handling.

The current implementation handles Bearer and bearer , but RFC 7235 specifies the scheme is case-insensitive. Other variations like BEARER or BeArEr would not be matched.

♻️ Suggested case-insensitive check
 function extractApiKey(request: Request) {
   const authorization = request.headers.get('authorization')
-  const bearerToken = authorization?.startsWith('Bearer ')
-    ? authorization.slice('Bearer '.length).trim()
-    : authorization?.startsWith('bearer ')
-      ? authorization.slice('bearer '.length).trim()
-      : null
+  const bearerToken = authorization?.toLowerCase().startsWith('bearer ')
+    ? authorization.slice('Bearer '.length).trim()
+    : null

   return bearerToken || request.headers.get('x-api-key')?.trim() || null
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/orpc/context.ts` around lines 65 - 73, The extractApiKey function
currently only matches "Bearer " and "bearer " exactly; make the Bearer-scheme
check case-insensitive per RFC 7235 by normalizing the authorization scheme
(e.g., convert authorization to lowercase or use a case-insensitive regex)
before slicing the token, or by splitting on whitespace and comparing the first
token case-insensitively; update extractApiKey so it returns the token when the
scheme equals "bearer" in any casing, falling back to x-api-key as before.
src/orpc/procedures/threads.ts (1)

54-56: Redundant schema transformation can be simplified.

The .omit({ threadId: true }).extend({ threadId: threadMessageListInputSchema.shape.threadId }) pattern produces an identical schema to threadMessageListInputSchema directly. Since oRPC automatically merges path parameters into the input object with compact input structure (the default), the explicit re-declaration is unnecessary.

♻️ Simplified schema usage
-    .input(threadMessageListInputSchema.omit({ threadId: true }).extend({
-      threadId: threadMessageListInputSchema.shape.threadId,
-    }))
+    .input(threadMessageListInputSchema)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/orpc/procedures/threads.ts` around lines 54 - 56, The input schema for
the procedure is redundantly rebuilt by omitting and then re-extending threadId;
replace the .input call that uses threadMessageListInputSchema.omit({ threadId:
true }).extend({ threadId: threadMessageListInputSchema.shape.threadId }) with
the original threadMessageListInputSchema directly (remove the omit/extend
pattern) so the procedure's .input uses threadMessageListInputSchema; update the
.input invocation in the procedure definition in threads.ts where
threadMessageListInputSchema is referenced.
src/orpc/api-keys.test.ts (1)

96-131: Cover the x-api-key auth path in this E2E test.

This only exercises the Bearer branch, so the alternate header in the public contract can regress without this test noticing.

Suggested test addition
     expect(inboxResponse.status).toBe(200)
     await expect(inboxResponse.json()).resolves.toMatchObject([
       {
         id: inboxId,
         userId,
       },
     ])
+
+    const headerResponse = await sendOpenApiRequest(
+      new Request('https://clankr.test/api/inboxes', {
+        headers: {
+          'x-api-key': createdKey.apiKey,
+        },
+      }),
+    )
+
+    expect(headerResponse.status).toBe(200)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/orpc/api-keys.test.ts` around lines 96 - 131, Add assertions exercising
the alternate API-key header path: use sendOpenApiRequest to call the inboxes
endpoint with header 'x-api-key' set to createdKey.apiKey (in addition to the
existing Bearer requests), assert status 200 and the expected JSON matches the
inbox, then after calling the revoke endpoint (API key id from
createdKey.metadata.id) repeat the inbox request with 'x-api-key' and assert a
401 unauthorized response; update src/orpc/api-keys.test.ts around the existing
sendOpenApiRequest/inboxes and revoke blocks to include these 'x-api-key' checks
so both auth branches are covered.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/api-keys.ts`:
- Around line 169-177: The current auth flow updates lastUsedAt synchronously
using database.update(apiKeys).set({...}).where(eq(apiKeys.id, storedApiKey.id))
which can cause valid requests to fail if that write errors; make this update
best-effort by not letting write errors block auth: either fire-and-forget the
update (do not await the promise) or await it inside a try/catch and swallow/log
errors (use processLogger.warn or similar) so authentication returns success
regardless of the update outcome. Locate the update call in src/lib/api-keys.ts
(references: storedApiKey, lastUsedAt, apiKeys, database.update) and change it
to a non-fatal, best-effort write with errors handled but not propagated.

In `@src/lib/email/outbound.ts`:
- Around line 334-374: The ensureThread function races between
findExistingThreadId and insert: replace the read-then-insert with an atomic
upsert using emailThreads' dedupe key (subjectNormalized + inboxId +
participantHash) so concurrent sends cannot create multiple threadId rows; add a
unique constraint for that key in the DB schema (update src/db/schema.ts) and
change ensureThread to attempt an insert of a generated createThreadId() with
subjectNormalized, inboxId, participantHash and lastMessageAt, using your DB
client's upsert/ON CONFLICT...DO UPDATE (or equivalent) to return the canonical
threadId and update lastMessageAt, falling back to findExistingThreadId only if
necessary.
- Around line 153-231: The current flow calls env.EMAIL.send() after inserting a
pending row, but if updateOutboundMessageStatus() fails the send can be accepted
twice on retry; fix by using the persisted message row as the idempotency
source: before calling env.EMAIL.send() read the pending message (by
messageId/internetMessageId/threadId) and only call env.EMAIL.send() if its
status is still 'pending' (or providerMessageId is null), otherwise treat it as
already accepted and reuse the stored providerMessageId/sentAt; ensure
updateOutboundMessageStatus(messageId, ...) and emitSendEvent(...) operate on
that same persisted row; use pendingMessage.id or internetMessageId as the
stable idempotency key and add the status check/early-return around
env.EMAIL.send()/statusUpdate to avoid duplicate sends.

In `@src/lib/email/read.test.ts`:
- Around line 359-360: The fixture currently uses the nullish coalescing
operator on params.textBody and params.htmlBody which treats explicit null as
"use default"; change the defaults to only apply when the param is undefined so
explicit null stays null: replace uses of params.textBody ?? 'Hello world' and
params.htmlBody ?? null with undefined checks (e.g., params.textBody !==
undefined ? params.textBody : 'Hello world' and params.htmlBody !== undefined ?
params.htmlBody : null) in the fixture construction (refer to the
textBody/htmlBody fields where params is used in the test).

In `@src/lib/email/read.ts`:
- Around line 155-217: The thread previews and pagination currently pick and
sort messages by createdAt (see latestMessages query, the
orderBy(desc(emailMessages.createdAt), desc(emailMessages.id)) and nextCursor
construction using pageRows.at(-1)?.lastMessageAt); change both the selection
and ordering to use the same chronology key the thread uses (lastMessageAt which
is derived from receivedAt/sentAt) so you pick the true latest message and page
consistently: update the latestMessages query orderBy to
desc(emailMessages.lastMessageAt), desc(emailMessages.id) (and any other
selection that currently uses createdAt for chronology), ensure
latestMessageByThreadId population remains but keyed by threadId, and build
nextCursor using pageRows.at(-1)?.lastMessageAt (ISO string) so previews,
sorting and cursor paging all use lastMessageAt instead of createdAt (also apply
the same change in the other read path noted around lines 231-258).
- Around line 365-390: The current code calls
env.EMAIL_STORAGE.get(message.oversizedBodyR2Key) outside the try block so
transient R2 errors cause a 500; wrap the storage fetch in the same try that
parses the body so any error from EMAIL_STORAGE.get or from
oversizedBodySchema.parse is caught and returns the missing-body shape
(textBody: null, htmlBody: null, source: 'missing'). Locate the getWorkerEnv()
call and the EMAIL_STORAGE.get(...) invocation and move the fetch into the
try/catch (or add a surrounding try) that currently runs
oversizedBodySchema.parse to ensure both fetch and parse failures fall back to
the missing source.

In `@src/lib/email/test-harness.ts`:
- Around line 38-52: The send() method currently guards on this.nextError's
truthiness and will skip throwing scheduled falsy values (e.g., '', 0, false);
update the guard to explicitly check for null (e.g., this.nextError !== null) so
that any value set by failWith(error) (which accepts unknown) is thrown; adjust
the send() method’s conditional and keep clearing this.nextError after capturing
it, referencing the nextError property, failWith(), and send() methods.

---

Nitpick comments:
In `@src/lib/api-keys.test.ts`:
- Around line 66-91: Add a test that verifies authenticateApiKey rejects keys
whose expiresAt is in the past: use createApiKeyForUser to create a key with
expiresAt set to a timestamp before now (e.g. Date.now() - 1000), then call
authenticateApiKey(created.apiKey) and assert it resolves to null; place this
alongside the existing tests for valid/revoked keys in the same suite so
expiresAt handling is covered.

In `@src/lib/email/read.test.ts`:
- Around line 47-112: Add a test case that inserts at least two threads/messages
with identical createdAt timestamps (use insertThreadWithMessage and the same
createdAt value for two different threadId/messageId pairs) and then call
listThreadsByInboxForUser to exercise cursor pagination; assert ordering uses
the tie-break (id) consistently by checking the exact thread id sequence across
pages and that nextCursor does not cause duplicates or skips. Ensure the
duplicate-timestamp fixtures appear in the same test (or a new test) near the
existing cursor pagination assertions so the tie-break path in
listThreadsByInboxForUser is executed and validated.

In `@src/lib/runtime.ts`:
- Around line 1-8: The module currently instantiates the Workers DB at import
time via createDb(env.APP_DB) and exports db, which breaks tests that mock this
module; change to lazy-initialize by removing the top-level createDb call and
instead create and cache the DB inside getDb() (e.g., if cachedDb return it else
set cachedDb = createDb(env.APP_DB) and return), keep exporting getDb() as the
primary accessor, keep or mark the direct db export deprecated (do not
instantiate it at module load) so imports that want the binding still work but
tests can mock getDb() without import-time side effects; update references to
use getDb() where feasible.

In `@src/orpc/api-keys.test.ts`:
- Around line 96-131: Add assertions exercising the alternate API-key header
path: use sendOpenApiRequest to call the inboxes endpoint with header
'x-api-key' set to createdKey.apiKey (in addition to the existing Bearer
requests), assert status 200 and the expected JSON matches the inbox, then after
calling the revoke endpoint (API key id from createdKey.metadata.id) repeat the
inbox request with 'x-api-key' and assert a 401 unauthorized response; update
src/orpc/api-keys.test.ts around the existing sendOpenApiRequest/inboxes and
revoke blocks to include these 'x-api-key' checks so both auth branches are
covered.

In `@src/orpc/context.ts`:
- Around line 65-73: The extractApiKey function currently only matches "Bearer "
and "bearer " exactly; make the Bearer-scheme check case-insensitive per RFC
7235 by normalizing the authorization scheme (e.g., convert authorization to
lowercase or use a case-insensitive regex) before slicing the token, or by
splitting on whitespace and comparing the first token case-insensitively; update
extractApiKey so it returns the token when the scheme equals "bearer" in any
casing, falling back to x-api-key as before.

In `@src/orpc/procedures/threads.ts`:
- Around line 54-56: The input schema for the procedure is redundantly rebuilt
by omitting and then re-extending threadId; replace the .input call that uses
threadMessageListInputSchema.omit({ threadId: true }).extend({ threadId:
threadMessageListInputSchema.shape.threadId }) with the original
threadMessageListInputSchema directly (remove the omit/extend pattern) so the
procedure's .input uses threadMessageListInputSchema; update the .input
invocation in the procedure definition in threads.ts where
threadMessageListInputSchema is referenced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c6a1896-43bc-47c3-bd8e-dd0ae0633906

📥 Commits

Reviewing files that changed from the base of the PR and between 250a149 and 07d084b.

📒 Files selected for processing (32)
  • .github/workflows/ci.yml
  • drizzle/0003_sweet_microchip.sql
  • drizzle/meta/0003_snapshot.json
  • drizzle/meta/_journal.json
  • mvp.md
  • src/db/client.ts
  • src/db/schema.ts
  • src/lib/api-keys.test.ts
  • src/lib/api-keys.ts
  • src/lib/auth.ts
  • src/lib/email/events.ts
  • src/lib/email/ids.test.ts
  • src/lib/email/ids.ts
  • src/lib/email/inbound.test.ts
  • src/lib/email/inbound.ts
  • src/lib/email/inboxes.test.ts
  • src/lib/email/inboxes.ts
  • src/lib/email/outbound.test.ts
  • src/lib/email/outbound.ts
  • src/lib/email/read.test.ts
  • src/lib/email/read.ts
  • src/lib/email/test-harness.test.ts
  • src/lib/email/test-harness.ts
  • src/lib/runtime.ts
  • src/orpc/api-keys.test.ts
  • src/orpc/context.ts
  • src/orpc/procedures/api-keys.ts
  • src/orpc/procedures/inboxes.ts
  • src/orpc/procedures/messages.ts
  • src/orpc/procedures/threads.ts
  • src/orpc/router.ts
  • src/worker.ts

Comment thread src/lib/api-keys.ts
Comment on lines +169 to +177
const now = new Date()

await database
.update(apiKeys)
.set({
lastUsedAt: now,
updatedAt: now,
})
.where(eq(apiKeys.id, storedApiKey.id))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don't fail auth when the usage timestamp write fails.

This adds a write to every authenticated request, and any transient update error here will reject an otherwise valid API key. lastUsedAt should be best-effort (or deferred) so auth availability doesn't depend on a secondary metadata write.

Suggested change
-  await database
-    .update(apiKeys)
-    .set({
-      lastUsedAt: now,
-      updatedAt: now,
-    })
-    .where(eq(apiKeys.id, storedApiKey.id))
+  try {
+    await database
+      .update(apiKeys)
+      .set({
+        lastUsedAt: now,
+        updatedAt: now,
+      })
+      .where(eq(apiKeys.id, storedApiKey.id))
+  } catch (error) {
+    console.warn('Failed to update API key usage metadata.', {
+      apiKeyId: storedApiKey.id,
+      error,
+    })
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const now = new Date()
await database
.update(apiKeys)
.set({
lastUsedAt: now,
updatedAt: now,
})
.where(eq(apiKeys.id, storedApiKey.id))
const now = new Date()
try {
await database
.update(apiKeys)
.set({
lastUsedAt: now,
updatedAt: now,
})
.where(eq(apiKeys.id, storedApiKey.id))
} catch (error) {
console.warn('Failed to update API key usage metadata.', {
apiKeyId: storedApiKey.id,
error,
})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/api-keys.ts` around lines 169 - 177, The current auth flow updates
lastUsedAt synchronously using
database.update(apiKeys).set({...}).where(eq(apiKeys.id, storedApiKey.id)) which
can cause valid requests to fail if that write errors; make this update
best-effort by not letting write errors block auth: either fire-and-forget the
update (do not await the promise) or await it inside a try/catch and swallow/log
errors (use processLogger.warn or similar) so authentication returns success
regardless of the update outcome. Locate the update call in src/lib/api-keys.ts
(references: storedApiKey, lastUsedAt, apiKeys, database.update) and change it
to a non-fatal, best-effort write with errors handled but not propagated.

Comment thread src/lib/email/outbound.ts
Comment on lines +153 to +231
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Make provider acceptance retry-safe.

If env.EMAIL.send() succeeds and updateOutboundMessageStatus() throws, this call fails after a non-idempotent send has already been accepted. A client retry will create a fresh pending row and send the same email again. This flow needs a stable idempotency key or recovery path that resumes the existing send instead of calling EMAIL.send() twice.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/outbound.ts` around lines 153 - 231, The current flow calls
env.EMAIL.send() after inserting a pending row, but if
updateOutboundMessageStatus() fails the send can be accepted twice on retry; fix
by using the persisted message row as the idempotency source: before calling
env.EMAIL.send() read the pending message (by
messageId/internetMessageId/threadId) and only call env.EMAIL.send() if its
status is still 'pending' (or providerMessageId is null), otherwise treat it as
already accepted and reuse the stored providerMessageId/sentAt; ensure
updateOutboundMessageStatus(messageId, ...) and emitSendEvent(...) operate on
that same persisted row; use pendingMessage.id or internetMessageId as the
stable idempotency key and add the status check/early-return around
env.EMAIL.send()/statusUpdate to avoid duplicate sends.

Comment thread src/lib/email/outbound.ts
Comment on lines +334 to +374
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Thread creation can split one conversation into multiple rows.

findExistingThreadId() and the insert happen as separate steps with no DB uniqueness backing them. Two concurrent sends with the same inbox/participants/subject can both see “no thread” and insert different threadIds. If subject+participant hashing is the dedupe key, enforce it with a unique constraint/upsert instead of read-then-insert logic.

Based on learnings, keep DB schema updates in src/db/schema.ts and run drizzle commands.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/outbound.ts` around lines 334 - 374, The ensureThread function
races between findExistingThreadId and insert: replace the read-then-insert with
an atomic upsert using emailThreads' dedupe key (subjectNormalized + inboxId +
participantHash) so concurrent sends cannot create multiple threadId rows; add a
unique constraint for that key in the DB schema (update src/db/schema.ts) and
change ensureThread to attempt an insert of a generated createThreadId() with
subjectNormalized, inboxId, participantHash and lastMessageAt, using your DB
client's upsert/ON CONFLICT...DO UPDATE (or equivalent) to return the canonical
threadId and update lastMessageAt, falling back to findExistingThreadId only if
necessary.

Comment on lines +359 to +360
textBody: params.textBody ?? 'Hello world',
htmlBody: params.htmlBody ?? null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Keep explicit null bodies null in the fixture.

Using ?? here turns the R2 fallback seed data back into an inline text body when the caller passes textBody: null. That makes the oversized-body fixture less realistic and weakens the assertion around storage-mode behavior.

Suggested fix
-    textBody: params.textBody ?? 'Hello world',
-    htmlBody: params.htmlBody ?? null,
+    textBody: params.textBody === undefined ? 'Hello world' : params.textBody,
+    htmlBody: params.htmlBody === undefined ? null : params.htmlBody,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
textBody: params.textBody ?? 'Hello world',
htmlBody: params.htmlBody ?? null,
textBody: params.textBody === undefined ? 'Hello world' : params.textBody,
htmlBody: params.htmlBody === undefined ? null : params.htmlBody,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/read.test.ts` around lines 359 - 360, The fixture currently
uses the nullish coalescing operator on params.textBody and params.htmlBody
which treats explicit null as "use default"; change the defaults to only apply
when the param is undefined so explicit null stays null: replace uses of
params.textBody ?? 'Hello world' and params.htmlBody ?? null with undefined
checks (e.g., params.textBody !== undefined ? params.textBody : 'Hello world'
and params.htmlBody !== undefined ? params.htmlBody : null) in the fixture
construction (refer to the textBody/htmlBody fields where params is used in the
test).

Comment thread src/lib/email/read.ts
Comment on lines +155 to +217
threadIds.length > 0
? database
.select({
id: emailMessages.id,
threadId: emailMessages.threadId,
direction: emailMessages.direction,
fromEmail: emailMessages.fromEmail,
subject: emailMessages.subject,
snippet: emailMessages.snippet,
status: emailMessages.status,
sentAt: emailMessages.sentAt,
receivedAt: emailMessages.receivedAt,
createdAt: emailMessages.createdAt,
})
.from(emailMessages)
.where(inArray(emailMessages.threadId, threadIds))
.orderBy(desc(emailMessages.createdAt), desc(emailMessages.id))
: Promise.resolve([]),
])

const countByThreadId = new Map(messageCounts.map((row) => [row.threadId, Number(row.count)]))
const latestMessageByThreadId = new Map<string, (typeof latestMessages)[number]>()

for (const message of latestMessages) {
if (!latestMessageByThreadId.has(message.threadId)) {
latestMessageByThreadId.set(message.threadId, message)
}
}

return {
nextCursor: rows.length > input.limit
? encodeCursor({
id: pageRows.at(-1)?.id ?? '',
lastMessageAt: pageRows.at(-1)?.lastMessageAt.toISOString() ?? '',
})
: null,
threads: pageRows.map((thread) => {
const latestMessage = latestMessageByThreadId.get(thread.id)

return {
id: thread.id,
inboxId: thread.inboxId,
subject: latestMessage?.subject ?? thread.subjectNormalized,
subjectNormalized: thread.subjectNormalized,
messageCount: countByThreadId.get(thread.id) ?? 0,
lastMessageAt: thread.lastMessageAt.toISOString(),
createdAt: thread.createdAt.toISOString(),
updatedAt: thread.updatedAt.toISOString(),
latestMessage: latestMessage
? {
id: latestMessage.id,
direction: latestMessage.direction as 'inbound' | 'outbound',
fromEmail: latestMessage.fromEmail,
subject: latestMessage.subject,
snippet: latestMessage.snippet,
status: latestMessage.status as z.infer<typeof messageStatusSchema>,
sentAt: latestMessage.sentAt?.toISOString() ?? null,
receivedAt: latestMessage.receivedAt?.toISOString() ?? null,
createdAt: latestMessage.createdAt.toISOString(),
}
: null,
}
}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Use message chronology for previews and pagination.

Both read paths sort on createdAt, but the thread model itself uses receivedAt/sentAt via lastMessageAt. Backfilled or delayed mail will show the wrong latestMessage preview and can appear out of order inside a thread. Pick and page messages with the same chronology key the thread uses.

Also applies to: 231-258

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/read.ts` around lines 155 - 217, The thread previews and
pagination currently pick and sort messages by createdAt (see latestMessages
query, the orderBy(desc(emailMessages.createdAt), desc(emailMessages.id)) and
nextCursor construction using pageRows.at(-1)?.lastMessageAt); change both the
selection and ordering to use the same chronology key the thread uses
(lastMessageAt which is derived from receivedAt/sentAt) so you pick the true
latest message and page consistently: update the latestMessages query orderBy to
desc(emailMessages.lastMessageAt), desc(emailMessages.id) (and any other
selection that currently uses createdAt for chronology), ensure
latestMessageByThreadId population remains but keyed by threadId, and build
nextCursor using pageRows.at(-1)?.lastMessageAt (ISO string) so previews,
sorting and cursor paging all use lastMessageAt instead of createdAt (also apply
the same change in the other read path noted around lines 231-258).

Comment thread src/lib/email/read.ts
Comment on lines +365 to +390
const env = getWorkerEnv() as Pick<Env, 'EMAIL_STORAGE'>
const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key)

if (!bodyObject) {
return {
textBody: null,
htmlBody: null,
source: 'missing' as const,
}
}

try {
const parsedBody = oversizedBodySchema.parse(JSON.parse(await bodyObject.text()))

return {
textBody: parsedBody.textBody,
htmlBody: parsedBody.htmlBody,
source: 'r2' as const,
}
} catch {
return {
textBody: null,
htmlBody: null,
source: 'missing' as const,
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Handle storage read failures as a missing body.

EMAIL_STORAGE.get() is outside the try, so a transient R2 error turns messages.get into a 500 even though this API already models bodySource: 'missing'. Wrap the fetch itself and fall back to the missing-body shape.

Suggested change
-  const env = getWorkerEnv() as Pick<Env, 'EMAIL_STORAGE'>
-  const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key)
-
-  if (!bodyObject) {
-    return {
-      textBody: null,
-      htmlBody: null,
-      source: 'missing' as const,
-    }
-  }
-
-  try {
+  const env = getWorkerEnv() as Pick<Env, 'EMAIL_STORAGE'>
+
+  try {
+    const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key)
+
+    if (!bodyObject) {
+      return {
+        textBody: null,
+        htmlBody: null,
+        source: 'missing' as const,
+      }
+    }
+
     const parsedBody = oversizedBodySchema.parse(JSON.parse(await bodyObject.text()))
 
     return {
       textBody: parsedBody.textBody,
       htmlBody: parsedBody.htmlBody,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/read.ts` around lines 365 - 390, The current code calls
env.EMAIL_STORAGE.get(message.oversizedBodyR2Key) outside the try block so
transient R2 errors cause a 500; wrap the storage fetch in the same try that
parses the body so any error from EMAIL_STORAGE.get or from
oversizedBodySchema.parse is caught and returns the missing-body shape
(textBody: null, htmlBody: null, source: 'missing'). Locate the getWorkerEnv()
call and the EMAIL_STORAGE.get(...) invocation and move the fetch into the
try/catch (or add a surrounding try) that currently runs
oversizedBodySchema.parse to ensure both fetch and parse failures fall back to
the missing source.

Comment on lines +38 to +52
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Check nextError against null, not truthiness.

failWith() accepts unknown, but send() skips throwing for scheduled values like '', 0, or false. If this test double is meant to mirror “throw whatever was scheduled,” the guard should be explicit.

🛠️ Proposed fix
-    if (this.nextError) {
+    if (this.nextError !== null) {
       const error = this.nextError
       this.nextError = null

       throw error
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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
}
private nextError: unknown | null = null
failWith(error: unknown) {
this.nextError = error
}
async send(message: unknown) {
this.sent.push(message)
if (this.nextError !== null) {
const error = this.nextError
this.nextError = null
throw error
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/test-harness.ts` around lines 38 - 52, The send() method
currently guards on this.nextError's truthiness and will skip throwing scheduled
falsy values (e.g., '', 0, false); update the guard to explicitly check for null
(e.g., this.nextError !== null) so that any value set by failWith(error) (which
accepts unknown) is thrown; adjust the send() method’s conditional and keep
clearing this.nextError after capturing it, referencing the nextError property,
failWith(), and send() methods.

@KMKoushik KMKoushik closed this Mar 8, 2026
KMKoushik added a commit that referenced this pull request Mar 8, 2026
KMKoushik added a commit that referenced this pull request Mar 8, 2026
* Implement thread and message read APIs (#5)

* Tighten thread read test typing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant