@@ -14,6 +14,8 @@ import { generateId } from '@sim/utils/id'
1414import { tasks } from '@trigger.dev/sdk'
1515import { and , eq , gt , ne , sql } from 'drizzle-orm'
1616import { NextResponse } from 'next/server'
17+ import addressparser from 'nodemailer/lib/addressparser'
18+ import { getDomain } from 'tldts'
1719import {
1820 agentMailEnvelopeSchema ,
1921 agentMailMessageSchema ,
@@ -30,6 +32,7 @@ import {
3032 readStreamToBufferWithLimit ,
3133} from '@/lib/core/utils/stream-limits'
3234import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
35+ import { emailDomain } from '@/lib/messaging/email/disposable'
3336import { executeInboxTask } from '@/lib/mothership/inbox/executor'
3437import type { AgentMailWebhookPayload , RejectionReason } from '@/lib/mothership/inbox/types'
3538import { WEBHOOK_MAX_BODY_BYTES } from '@/lib/webhooks/constants'
@@ -163,8 +166,15 @@ export const POST = withRouteHandler(async (req: Request) => {
163166 return NextResponse . json ( { ok : true } )
164167 }
165168
166- const fromEmail = extractSenderEmail ( message . from ) || ''
167- logger . info ( 'Webhook received' , { fromEmail, from_raw : message . from , workspaceId : result . id } )
169+ const sender = parseSender ( message . from )
170+ const fromEmail = sender . email
171+ const senderAuthenticated = isSenderAuthenticated ( sender , message )
172+ logger . info ( 'Webhook received' , {
173+ fromEmail,
174+ from_raw : message . from ,
175+ senderAuthenticated,
176+ workspaceId : result . id ,
177+ } )
168178
169179 if ( result . inboxAddress && fromEmail === result . inboxAddress . toLowerCase ( ) ) {
170180 logger . info ( 'Skipping email from inbox itself' , { workspaceId : result . id } )
@@ -195,7 +205,7 @@ export const POST = withRouteHandler(async (req: Request) => {
195205 )
196206 . limit ( 1 )
197207 : Promise . resolve ( [ ] ) ,
198- isSenderAllowed ( fromEmail , result . id ) ,
208+ isSenderAllowed ( fromEmail , senderAuthenticated , result . id ) ,
199209 getRecentTaskCount ( result . id ) ,
200210 inReplyTo
201211 ? db
@@ -235,8 +245,6 @@ export const POST = withRouteHandler(async (req: Request) => {
235245
236246 const chatId = parentTaskResult [ 0 ] ?. chatId ?? null
237247
238- const fromName = extractDisplayName ( message . from )
239-
240248 const taskId = generateId ( )
241249 const bodyText = message . text ?. substring ( 0 , 50_000 ) || null
242250 const bodyHtml = message . html ?. substring ( 0 , 50_000 ) || null
@@ -246,7 +254,8 @@ export const POST = withRouteHandler(async (req: Request) => {
246254 id : taskId ,
247255 workspaceId : result . id ,
248256 fromEmail,
249- fromName,
257+ senderAuthenticated,
258+ fromName : sender . name ,
250259 subject : message . subject || '(no subject)' ,
251260 bodyPreview,
252261 bodyText,
@@ -307,7 +316,45 @@ export const POST = withRouteHandler(async (req: Request) => {
307316 }
308317} )
309318
310- async function isSenderAllowed ( email : string , workspaceId : string ) : Promise < boolean > {
319+ /**
320+ * Whether the receiving provider proved the sender controls `fromEmail`'s domain.
321+ * The From header is written by whoever sends the mail, so a workspace member's
322+ * address only identifies that member when this holds.
323+ *
324+ * AgentMail keeps `spf` only when the envelope domain aligns with the From domain,
325+ * and `dmarc` is the From domain's own verdict, so a pass on either is trusted as
326+ * given. `dkim` is kept whoever signed, so it counts only when the signing domain
327+ * aligns with the From domain the way DMARC's relaxed mode does: one registrable
328+ * domain. The delivery's own `unauthenticated` label is not enough: AgentMail
329+ * delivers mail without it when an unaligned envelope SPF passes, which any domain
330+ * can arrange.
331+ */
332+ function isSenderAuthenticated (
333+ sender : ParsedSender ,
334+ message : AgentMailWebhookPayload [ 'message' ]
335+ ) : boolean {
336+ const results = message . authentication_results
337+ if ( ! sender . email || ! results ) return false
338+ if ( results . dmarc === 'pass' || results . spf === 'pass' ) return true
339+ if ( results . dkim !== 'pass' || ! results . dkim_domain ) return false
340+
341+ const fromOrganization = organizationalDomain ( emailDomain ( sender . email ) )
342+ return (
343+ fromOrganization !== null &&
344+ fromOrganization === organizationalDomain ( emailDomain ( results . dkim_domain ) )
345+ )
346+ }
347+
348+ /** The registrable domain DMARC aligns on; null for a bare public suffix. */
349+ function organizationalDomain ( domain : string ) : string | null {
350+ return getDomain ( domain , { allowPrivateDomains : true } )
351+ }
352+
353+ async function isSenderAllowed (
354+ email : string ,
355+ senderAuthenticated : boolean ,
356+ workspaceId : string
357+ ) : Promise < boolean > {
311358 const [ allowedSenderResult , memberResult ] = await Promise . all ( [
312359 db
313360 . select ( { id : mothershipInboxAllowedSender . id } )
@@ -319,18 +366,20 @@ async function isSenderAllowed(email: string, workspaceId: string): Promise<bool
319366 )
320367 )
321368 . limit ( 1 ) ,
322- db
323- . select ( { userId : permissions . userId } )
324- . from ( permissions )
325- . innerJoin ( user , eq ( permissions . userId , user . id ) )
326- . where (
327- and (
328- eq ( permissions . entityType , 'workspace' ) ,
329- eq ( permissions . entityId , workspaceId ) ,
330- sql `lower(${ user . email } ) = ${ email } `
331- )
332- )
333- . limit ( 1 ) ,
369+ senderAuthenticated
370+ ? db
371+ . select ( { userId : permissions . userId } )
372+ . from ( permissions )
373+ . innerJoin ( user , eq ( permissions . userId , user . id ) )
374+ . where (
375+ and (
376+ eq ( permissions . entityType , 'workspace' ) ,
377+ eq ( permissions . entityId , workspaceId ) ,
378+ sql `lower(${ user . email } ) = ${ email } `
379+ )
380+ )
381+ . limit ( 1 )
382+ : [ ] ,
334383 ] )
335384
336385 return ! ! ( allowedSenderResult [ 0 ] || memberResult [ 0 ] )
@@ -356,11 +405,12 @@ async function createRejectedTask(
356405 message : AgentMailWebhookPayload [ 'message' ] ,
357406 reason : RejectionReason
358407) : Promise < void > {
408+ const sender = parseSender ( message . from )
359409 await db . insert ( mothershipInboxTask ) . values ( {
360410 id : generateId ( ) ,
361411 workspaceId,
362- fromEmail : extractSenderEmail ( message . from ) || 'unknown' ,
363- fromName : extractDisplayName ( message . from ) ,
412+ fromEmail : sender . email || 'unknown' ,
413+ fromName : sender . name ,
364414 subject : message . subject || '(no subject)' ,
365415 bodyPreview : ( message . text || '' ) . substring ( 0 , 200 ) || null ,
366416 emailMessageId : message . message_id ,
@@ -371,29 +421,20 @@ async function createRejectedTask(
371421 } )
372422}
373423
374- /**
375- * Extract the raw email address from AgentMail's from field.
376- * Format: "username@domain.com" or "Display Name <username@domain.com>"
377- */
378- function extractSenderEmail ( from : string ) : string {
379- const openBracket = from . indexOf ( '<' )
380- const closeBracket = from . indexOf ( '>' , openBracket + 1 )
381- if ( openBracket !== - 1 && closeBracket !== - 1 ) {
382- return from
383- . substring ( openBracket + 1 , closeBracket )
384- . toLowerCase ( )
385- . trim ( )
386- }
387- return from . toLowerCase ( ) . trim ( )
424+ interface ParsedSender {
425+ email : string
426+ name : string | null
388427}
389428
390- function extractDisplayName ( from : string ) : string | null {
391- const openBracket = from . indexOf ( '<' )
392- if ( openBracket <= 0 ) return null
393- const name = from . substring ( 0 , openBracket ) . trim ( )
394- if ( ! name ) return null
395- if ( name . startsWith ( '"' ) && name . endsWith ( '"' ) ) {
396- return name . slice ( 1 , - 1 ) || null
397- }
398- return name
429+ /**
430+ * Parse AgentMail's From field (`addr@domain` or `Display Name <addr@domain>`) per
431+ * RFC 5322, so a display name that itself looks like an address — `"<admin@victim>"
432+ * <x@attacker>` — is never mistaken for the mailbox. A header naming no mailbox or
433+ * several yields no address, so no one of them speaks for the message.
434+ */
435+ function parseSender ( from : string ) : ParsedSender {
436+ const mailboxes = addressparser ( from , { flatten : true } )
437+ if ( mailboxes . length !== 1 ) return { email : '' , name : null }
438+ const [ { address, name } ] = mailboxes
439+ return { email : address . trim ( ) . toLowerCase ( ) , name : name || null }
399440}
0 commit comments