@open-mercato/channel-imap 0.8.1-develop.7263.1.bbc6db3437 → 0.8.1-develop.7267.1.2e95af80a6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/channel_imap/lib/adapter.js +6 -2
- package/dist/modules/channel_imap/lib/adapter.js.map +2 -2
- package/dist/modules/channel_imap/lib/normalize-inbound.js +1 -0
- package/dist/modules/channel_imap/lib/normalize-inbound.js.map +2 -2
- package/package.json +6 -6
- package/src/modules/channel_imap/lib/__tests__/normalize-inbound.test.ts +18 -0
- package/src/modules/channel_imap/lib/adapter.ts +6 -2
- package/src/modules/channel_imap/lib/normalize-inbound.ts +4 -1
|
@@ -142,7 +142,9 @@ class ImapChannelAdapter {
|
|
|
142
142
|
rawMessage: item.rawBody,
|
|
143
143
|
uid: item.uid,
|
|
144
144
|
accountIdentifier: credentials.fromAddress,
|
|
145
|
-
|
|
145
|
+
// INTERNALDATE is when the server received the message; the MIME Date
|
|
146
|
+
// header is the sender's and must not date the platform message (#6095).
|
|
147
|
+
receivedAt: item.internalDate
|
|
146
148
|
});
|
|
147
149
|
messages.push(normalized);
|
|
148
150
|
}
|
|
@@ -213,7 +215,9 @@ class ImapChannelAdapter {
|
|
|
213
215
|
rawMessage: item.rawBody,
|
|
214
216
|
uid: item.uid,
|
|
215
217
|
accountIdentifier: credentials.fromAddress,
|
|
216
|
-
|
|
218
|
+
// INTERNALDATE is when the server received the message; the MIME Date
|
|
219
|
+
// header is the sender's and must not date the platform message (#6095).
|
|
220
|
+
receivedAt: item.internalDate
|
|
217
221
|
});
|
|
218
222
|
messages.push(normalized);
|
|
219
223
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/channel_imap/lib/adapter.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n ChannelAdapter,\n ConvertOutboundInput,\n ChannelNativeContent,\n FetchHistoryInput,\n GetMessageStatusInput,\n HistoryPage,\n ImportHistoryInput,\n ImportHistoryPage,\n InboundMessage,\n MessageStatus,\n NormalizedInboundMessage,\n ResolveContactInput,\n ContactHint,\n SendMessageInput,\n SendMessageResult,\n ValidateCredentialsInput,\n ValidateCredentialsResult,\n VerifyWebhookInput,\n} from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { imapCapabilities } from './capabilities'\nimport { imapCredentialsSchema, imapChannelStateSchema, type ImapCredentials, type ImapChannelState } from './credentials'\nimport {\n credentialsToConnection,\n getImapClient,\n} from './imap-client'\nimport {\n credentialsToSmtpConnection,\n getSmtpClient,\n} from './smtp-client'\nimport { convertOutboundForEmail } from './convert-outbound'\nimport { normalizeInboundImapMessage } from './normalize-inbound'\nimport { validateImapCredentials } from './validate-credentials'\nimport { emailResolveContact } from '@open-mercato/core/modules/communication_channels/lib/email-contact'\nimport { decodeCursor, encodeCursor } from '@open-mercato/core/modules/communication_channels/lib/email-mime'\nimport { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('channel_imap')\n\n/**\n * IMAP+SMTP `ChannelAdapter`. Inbound is polling-driven (`realtimePush: false`),\n * outbound is SMTP. Threading is RFC2822 (In-Reply-To / References).\n *\n * Why this adapter omits some methods:\n * - `verifyWebhook` \u2014 IMAP has no webhook; we return a no-op event with\n * `eventType: 'other'` so the hub's webhook route returns 202 if anyone\n * ever POSTs at `/api/communication_channels/webhook/imap`.\n * - `getStatus` \u2014 IMAP has no delivery-status concept beyond `\\Seen`; we\n * return `{ status: 'sent' }` as a best-effort placeholder.\n * - No `sendReaction` / `editMessage` / `deleteMessage` \u2014 email doesn't\n * support these capabilities.\n */\nclass ImapChannelAdapter implements ChannelAdapter {\n readonly providerKey = 'imap'\n readonly channelType = 'email'\n readonly capabilities = imapCapabilities\n\n async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {\n const credentials = parseCredentialsOrThrow(input.credentials)\n\n // Reject attachments at the boundary BEFORE building the MIME body. The hub\n // passes attachments as URL pointers; until the IMAP/SMTP adapter wires a\n // fetcher (with size + content-type validation), inlining them is unsafe \u2014\n // a 0-byte attachment looks \"delivered\" but conveys nothing. Checking here\n // (rather than after conversion) avoids wasted MIME-build work and surfaces\n // the clearer \"attachments unsupported\" error even when recipients are also\n // missing. Documented in review M2 (2026-05-26) and tracked as a follow-up.\n if (Array.isArray(input.content.attachments) && input.content.attachments.length > 0) {\n return {\n externalMessageId: '',\n status: 'failed',\n error:\n '[internal] IMAP/SMTP adapter does not yet support attachments. Send the message without attachments or use a provider that supports them (Gmail).',\n }\n }\n\n let native: ChannelNativeContent\n try {\n native = await convertOutboundForEmail({\n body: input.content.html ?? input.content.text ?? '',\n bodyFormat: input.content.bodyFormat ?? (input.content.html ? 'html' : 'text'),\n attachments: input.content.attachments,\n channelMetadata: input.metadata,\n })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Outbound conversion failed'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n const meta = (native.metadata ?? {}) as Record<string, unknown>\n const to = Array.isArray(meta.to) ? (meta.to as string[]) : []\n if (to.length === 0) {\n return { externalMessageId: '', status: 'failed', error: '[internal] Email send requires at least one recipient' }\n }\n\n const smtp = getSmtpClient()\n const result = await smtp.send(credentialsToSmtpConnection(credentials), {\n from: credentials.fromAddress,\n to,\n cc: Array.isArray(meta.cc) ? (meta.cc as string[]) : undefined,\n bcc: Array.isArray(meta.bcc) ? (meta.bcc as string[]) : undefined,\n subject: typeof meta.subject === 'string' ? (meta.subject as string) : undefined,\n text: native.content.text,\n html: native.content.html,\n inReplyTo: typeof meta.inReplyTo === 'string' ? (meta.inReplyTo as string) : undefined,\n references: Array.isArray(meta.references) ? (meta.references as string[]) : undefined,\n messageId: typeof meta.messageId === 'string' ? (meta.messageId as string) : undefined,\n })\n\n // Best-effort append to Sent \u2014 many servers auto-store via \"Submission\" but not all do.\n const imap = getImapClient()\n try {\n // Skip when the RFC2822 bytes are empty (MailComposer build failed upstream):\n // appending a 0-byte buffer would create a corrupt Sent-folder entry, and the\n // send itself already succeeded.\n if (result.raw.length > 0) {\n await imap.appendSent(credentialsToConnection(credentials), result.raw)\n }\n } catch (appendError) {\n // Best-effort: many servers auto-store sent mail via Submission, and the\n // Sent mailbox name is provider-specific (localized, or \"[Gmail]/Sent Mail\").\n // Log so operators can diagnose missing Sent-folder archival rather than\n // failing the send.\n logger.warn('failed to append outbound message to Sent folder', { err: appendError })\n }\n\n return {\n externalMessageId: result.messageId,\n conversationId: input.conversationId,\n status: 'sent',\n metadata: { response: result.response },\n }\n }\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<InboundMessage> {\n return { raw: {}, eventType: 'other', metadata: { reason: 'imap-does-not-use-webhooks' } }\n }\n\n async getStatus(_input: GetMessageStatusInput): Promise<MessageStatus> {\n return { status: 'sent' }\n }\n\n async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> {\n return convertOutboundForEmail(input)\n }\n\n async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> {\n const rawBuffer = pickRawMimeBuffer(raw)\n const accountIdentifier = pickAccountIdentifier(raw)\n const uid = pickUid(raw)\n return normalizeInboundImapMessage({\n rawMessage: rawBuffer,\n uid,\n accountIdentifier,\n })\n }\n\n async validateCredentials(input: ValidateCredentialsInput): Promise<ValidateCredentialsResult> {\n return validateImapCredentials(input.credentials)\n }\n\n async fetchHistory(input: FetchHistoryInput): Promise<HistoryPage> {\n const credentials = parseCredentialsOrThrow(input.credentials)\n const channelState = imapChannelStateSchema.parse(input.channelState ?? {}) satisfies ImapChannelState\n const imap = getImapClient()\n const connection = credentialsToConnection(credentials)\n\n // Spec B \u00A7 Bounded, cursor-driven IMAP inbound:\n // - Bootstrap (no cursor): SELECT INBOX, persist UIDVALIDITY + UIDNEXT,\n // return ZERO messages. Backlog import happens via the explicit\n // `/import-history` endpoint, not via the silent connect flow.\n // - Incremental (cursor exists): UID FETCH `previousUidNext:*`, capped\n // at HARD_CAP = 200. If more available, set `hasMore: true` so the\n // hub re-enqueues immediately and drains the backlog.\n // - UIDVALIDITY mismatch: discard cursor and treat as bootstrap (the\n // mailbox was recreated or renamed; we cannot trust the prior cursor).\n const folderState = await imap.selectInbox(connection)\n const previousUidValidity = toNumberOrUndefined(channelState.uidValidity)\n const previousUidNext = toNumberOrUndefined(channelState.uidNext)\n const serverUidNext = toNumberOrUndefined(folderState.uidNext)\n const HARD_CAP = clampHardCap(input.limit)\n\n const uidValidityMismatch =\n previousUidValidity !== undefined &&\n folderState.uidValidity !== undefined &&\n folderState.uidValidity !== previousUidValidity\n if (uidValidityMismatch) {\n logger.warn('UIDVALIDITY changed for INBOX \u2014 discarding cursor and re-bootstrapping', {\n previousUidValidity,\n uidValidity: folderState.uidValidity,\n })\n }\n const needsBootstrap =\n uidValidityMismatch || previousUidNext === undefined || previousUidNext === null\n\n let fetched: { uid: number; rawBody: Buffer; internalDate?: Date; flags?: string[] }[]\n let hasMore = false\n if (needsBootstrap) {\n // \u2500\u2500 Bootstrap: persist cursor only, fetch zero messages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Spec B \u00A7 Bootstrap. The \"1M inbox\" failure mode is fixed by\n // construction: a fresh user sees zero history until they explicitly\n // request `/import-history`. Set `hasMore: false` so the poll worker\n // does NOT immediately re-enqueue.\n fetched = []\n hasMore = false\n } else if (previousUidNext !== undefined && serverUidNext !== undefined && previousUidNext >= serverUidNext) {\n // \u2500\u2500 Idle: UIDNEXT did not advance, so there is no new mail \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Skip the FETCH entirely. IMAP `<n>:*` always matches at least the\n // highest existing UID, so an idle mailbox would otherwise re-fetch and\n // re-normalize one already-ingested message every tick. The cursor is\n // retained downstream (an empty fetch does not advance it).\n fetched = []\n hasMore = false\n } else {\n // \u2500\u2500 Incremental: UID FETCH previousUidNext:* up to HARD_CAP \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // On a mature mailbox this is typically 0-N UIDs. The HARD_CAP bounds\n // the per-poll wall-clock + DB transaction size; if more remain, the\n // hub re-enqueues us immediately via `hasMore: true`.\n const range = `${previousUidNext}:*`\n // Fetch up to HARD_CAP + 1 so we can detect whether more remain\n // without paying for an extra round-trip later.\n const probeLimit = HARD_CAP + 1\n const raw = await imap.fetchUidRange(connection, range, { limit: probeLimit })\n if (raw.length > HARD_CAP) {\n fetched = raw.slice(0, HARD_CAP)\n hasMore = true\n } else {\n fetched = raw\n hasMore = false\n }\n }\n\n const messages: NormalizedInboundMessage[] = []\n for (const item of fetched) {\n const normalized = await normalizeInboundImapMessage({\n rawMessage: item.rawBody,\n uid: item.uid,\n accountIdentifier: credentials.fromAddress,\n fallbackDate: item.internalDate,\n })\n messages.push(normalized)\n }\n\n // Cursor advancement contract:\n // - Bootstrap: persist the server's current UIDNEXT so the next poll\n // becomes incremental from this point onward (intentionally skips the\n // pre-existing backlog; use `/import-history` to pull it).\n // - Incremental: persist `highestFetchedUid + 1` \u2014 NEVER the server's\n // UIDNEXT. When `fetched` is empty we retain `previousUidNext` so the\n // next poll resumes from the same point.\n const advancedUidNext = (() => {\n if (needsBootstrap) return serverUidNext\n if (fetched.length === 0) return previousUidNext\n const highest = fetched.reduce((max, item) => (item.uid > max ? item.uid : max), 0)\n // Anchor the cursor to the highest UID we ACTUALLY fetched \u2014 never to the\n // server's UIDNEXT. Providers like Gmail report a UIDNEXT that runs ahead\n // of the highest message currently in the folder (UID gaps from\n // labels/threads, or a message materialising into INBOX at a UID below\n // UIDNEXT). Jumping the cursor to `serverUidNext` then steps over any\n // INBOX message that sits below it: that message lands permanently below\n // the cursor and is never fetched again \u2014 the bug that silently dropped\n // inbound replies (UID 61979 skipped while cursor jumped to 61981).\n // `highest + 1` guarantees we never step over an unfetched message; if the\n // server's UIDNEXT is higher, the next poll just re-scans `highest+1:*`\n // (idempotent \u2014 the hub dedups on (channel_id, external_message_id)).\n return highest + 1\n })()\n const nextChannelState: ImapChannelState = {\n uidValidity: folderState.uidValidity ?? previousUidValidity,\n uidNext: advancedUidNext,\n lastFolder: 'INBOX',\n }\n\n // The hub's polling worker re-reads cursor through `fetchHistory`. We embed the\n // next-poll state in `nextCursor` (base64-encoded JSON) so workers can persist\n // it onto `CommunicationChannel.channelState` without depending on a hub-specific\n // contract beyond the existing `HistoryPage` shape.\n const nextCursor = encodeCursor(nextChannelState)\n return { messages, nextCursor, hasMore }\n }\n\n async importHistory(input: ImportHistoryInput): Promise<ImportHistoryPage> {\n const credentials = parseCredentialsOrThrow(input.credentials)\n const connection = credentialsToConnection(credentials)\n const imap = getImapClient()\n\n // Ceiling is provider-specific and lower than the deployment-wide one:\n // this adapter's cursor embeds the full remaining UID list, so it stays\n // capped until it gets a paging cursor of its own. See\n // `import-history-limits.ts` for the shared source of truth.\n const limits = getImportHistoryLimits(this.providerKey)\n\n const sinceDaysRaw = Number.isFinite(input.sinceDays) ? Math.trunc(input.sinceDays) : limits.defaultSinceDays\n const sinceDays = Math.max(1, Math.min(limits.maxSinceDays, sinceDaysRaw))\n const sinceDate = new Date(Date.now() - sinceDays * 24 * 60 * 60 * 1000)\n\n const maxMessagesRaw = Number.isFinite(input.maxMessages)\n ? Math.trunc(input.maxMessages as number)\n : limits.defaultMaxMessages\n const maxMessages = Math.max(1, Math.min(limits.maxMessages, maxMessagesRaw))\n\n const PAGE_SIZE = clampHardCap(undefined)\n\n // Resume previous page or perform initial SEARCH on first call. The cursor\n // encodes the full remaining UID list discovered server-side so subsequent\n // pages don't re-issue SEARCH (which on large mailboxes is expensive).\n let allUids: number[]\n let remainingUids: number[]\n let collectedSoFar: number\n let totalCandidates: number | undefined\n const cursor = decodeImportCursor(input.cursor)\n if (cursor) {\n remainingUids = cursor.remaining\n collectedSoFar = cursor.collected\n totalCandidates = cursor.total\n allUids = cursor.remaining\n } else {\n // FROM-chunking: SEARCH with very long OR chains can blow imapflow's\n // tag-buffer; chunk to \u226430 senders and union the results. When\n // contactEmails is empty we issue a single SINCE-only search.\n const senders = (input.contactEmails ?? []).filter((s): s is string => typeof s === 'string' && s.includes('@'))\n const uidSet = new Set<number>()\n if (senders.length === 0) {\n const uids = await imap.searchUidsByFromAndSince(connection, { sinceDate })\n for (const uid of uids) uidSet.add(uid)\n } else {\n const CHUNK_SIZE = 30\n for (let i = 0; i < senders.length; i += CHUNK_SIZE) {\n const chunk = senders.slice(i, i + CHUNK_SIZE)\n const uids = await imap.searchUidsByFromAndSince(connection, { fromAddresses: chunk, sinceDate })\n for (const uid of uids) uidSet.add(uid)\n }\n }\n // Process newest first (highest UIDs ~= most recent on standard servers).\n allUids = Array.from(uidSet).sort((a, b) => b - a).slice(0, maxMessages)\n remainingUids = allUids\n collectedSoFar = 0\n totalCandidates = allUids.length\n }\n\n if (remainingUids.length === 0) {\n return { messages: [], hasMore: false, totalCandidates }\n }\n\n const batchUids = remainingUids.slice(0, PAGE_SIZE)\n const stillRemaining = remainingUids.slice(PAGE_SIZE)\n const uidSetExpression = batchUids.join(',')\n const fetched = await imap.fetchUidRange(connection, uidSetExpression, { limit: PAGE_SIZE })\n\n const messages: NormalizedInboundMessage[] = []\n for (const item of fetched) {\n const normalized = await normalizeInboundImapMessage({\n rawMessage: item.rawBody,\n uid: item.uid,\n accountIdentifier: credentials.fromAddress,\n fallbackDate: item.internalDate,\n })\n messages.push(normalized)\n }\n\n const newCollected = collectedSoFar + messages.length\n const hasMore = stillRemaining.length > 0 && newCollected < maxMessages\n const nextCursor = hasMore\n ? encodeImportCursor({ remaining: stillRemaining, collected: newCollected, total: totalCandidates })\n : undefined\n\n return { messages, nextCursor, hasMore, totalCandidates }\n }\n\n async resolveContact(input: ResolveContactInput): Promise<ContactHint | null> {\n return emailResolveContact(input)\n }\n}\n\nfunction parseCredentialsOrThrow(value: unknown): ImapCredentials {\n const parsed = imapCredentialsSchema.safeParse(value)\n if (!parsed.success) {\n const first = parsed.error.issues[0]\n throw new Error(`Invalid IMAP credentials: ${first?.message ?? 'unknown validation error'}`)\n }\n return parsed.data\n}\n\nfunction pickRawMimeBuffer(raw: InboundMessage): Buffer {\n const candidate = raw.raw as { rawBody?: unknown; mime?: unknown }\n const value = candidate?.rawBody ?? candidate?.mime ?? raw.raw\n if (Buffer.isBuffer(value)) return value\n if (value instanceof Uint8Array) return Buffer.from(value)\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n throw new Error('[internal] IMAP normalizeInbound requires `raw.rawBody` to be a Buffer or string MIME payload')\n}\n\nfunction pickAccountIdentifier(raw: InboundMessage): string {\n const candidate = raw.raw as { accountIdentifier?: unknown }\n const id = typeof candidate?.accountIdentifier === 'string' ? candidate.accountIdentifier : undefined\n return id ?? 'unknown@imap'\n}\n\nfunction pickUid(raw: InboundMessage): number | undefined {\n const candidate = raw.raw as { uid?: unknown }\n return typeof candidate?.uid === 'number' ? candidate.uid : undefined\n}\n\n/**\n * Spec B \u00A7 HARD_CAP. Bound each poll's wall-clock + DB transaction size.\n * Honor the caller's `limit` hint but never exceed `HARD_CAP_MAX`. A\n * single poll will fetch at most this many UIDs; if more remain we set\n * `hasMore: true` and the hub re-enqueues immediately.\n *\n * Configurable via `OM_CHANNEL_IMAP_HARD_CAP_PER_POLL` (default 200).\n */\nfunction clampHardCap(callerLimit: number | undefined): number {\n const envOverride = Number.parseInt(process.env.OM_CHANNEL_IMAP_HARD_CAP_PER_POLL ?? '', 10)\n const HARD_CAP_MAX = Number.isFinite(envOverride) && envOverride > 0 ? envOverride : 200\n if (typeof callerLimit === 'number' && callerLimit > 0) {\n return Math.min(callerLimit, HARD_CAP_MAX)\n }\n return HARD_CAP_MAX\n}\n\ninterface ImportCursor {\n remaining: number[]\n collected: number\n total?: number\n}\n\nfunction encodeImportCursor(cursor: ImportCursor): string {\n return encodeCursor(cursor)\n}\n\nfunction decodeImportCursor(value: string | undefined): ImportCursor | null {\n const parsed = decodeCursor(value)\n if (!parsed || typeof parsed !== 'object') return null\n const obj = parsed as { remaining?: unknown; collected?: unknown; total?: unknown }\n const remaining = Array.isArray(obj.remaining)\n ? obj.remaining.filter((n): n is number => typeof n === 'number' && Number.isFinite(n))\n : []\n const collected = typeof obj.collected === 'number' ? obj.collected : 0\n const total = typeof obj.total === 'number' ? obj.total : undefined\n return { remaining, collected, total }\n}\n\nfunction toNumberOrUndefined(value: unknown): number | undefined {\n if (typeof value === 'number') return value\n if (typeof value === 'string' && value.length > 0) {\n const n = Number(value)\n return Number.isFinite(n) ? n : undefined\n }\n return undefined\n}\n\nlet cachedAdapter: ImapChannelAdapter | null = null\n\nexport function getImapChannelAdapter(): ImapChannelAdapter {\n if (!cachedAdapter) cachedAdapter = new ImapChannelAdapter()\n return cachedAdapter\n}\n\nexport { ImapChannelAdapter }\n"],
|
|
5
|
-
"mappings": "AAoBA,SAAS,wBAAwB;AACjC,SAAS,uBAAuB,8BAA2E;AAC3G;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AACxC,SAAS,mCAAmC;AAC5C,SAAS,+BAA+B;AACxC,SAAS,2BAA2B;AACpC,SAAS,cAAc,oBAAoB;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc;AAe1C,MAAM,mBAA6C;AAAA,EAAnD;AACE,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,eAAe;AAAA;AAAA,EAExB,MAAM,YAAY,OAAqD;AACrE,UAAM,cAAc,wBAAwB,MAAM,WAAW;AAS7D,QAAI,MAAM,QAAQ,MAAM,QAAQ,WAAW,KAAK,MAAM,QAAQ,YAAY,SAAS,GAAG;AACpF,aAAO;AAAA,QACL,mBAAmB;AAAA,QACnB,QAAQ;AAAA,QACR,OACE;AAAA,MACJ;AAAA,IACF;AAEA,QAAI;AACJ,QAAI;AACF,eAAS,MAAM,wBAAwB;AAAA,QACrC,MA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,YAAY,gBAAgB,UAC5B,YAAY,gBAAgB;AAC9B,QAAI,qBAAqB;AACvB,aAAO,KAAK,+EAA0E;AAAA,QACpF;AAAA,QACA,aAAa,YAAY;AAAA,MAC3B,CAAC;AAAA,IACH;AACA,UAAM,iBACJ,uBAAuB,oBAAoB,UAAa,oBAAoB;AAE9E,QAAI;AACJ,QAAI,UAAU;AACd,QAAI,gBAAgB;AAMlB,gBAAU,CAAC;AACX,gBAAU;AAAA,IACZ,WAAW,oBAAoB,UAAa,kBAAkB,UAAa,mBAAmB,eAAe;AAM3G,gBAAU,CAAC;AACX,gBAAU;AAAA,IACZ,OAAO;AAKL,YAAM,QAAQ,GAAG,eAAe;AAGhC,YAAM,aAAa,WAAW;AAC9B,YAAM,MAAM,MAAM,KAAK,cAAc,YAAY,OAAO,EAAE,OAAO,WAAW,CAAC;AAC7E,UAAI,IAAI,SAAS,UAAU;AACzB,kBAAU,IAAI,MAAM,GAAG,QAAQ;AAC/B,kBAAU;AAAA,MACZ,OAAO;AACL,kBAAU;AACV,kBAAU;AAAA,MACZ;AAAA,IACF;AAEA,UAAM,WAAuC,CAAC;AAC9C,eAAW,QAAQ,SAAS;AAC1B,YAAM,aAAa,MAAM,4BAA4B;AAAA,QACnD,YAAY,KAAK;AAAA,QACjB,KAAK,KAAK;AAAA,QACV,mBAAmB,YAAY;AAAA,
|
|
4
|
+
"sourcesContent": ["import type {\n ChannelAdapter,\n ConvertOutboundInput,\n ChannelNativeContent,\n FetchHistoryInput,\n GetMessageStatusInput,\n HistoryPage,\n ImportHistoryInput,\n ImportHistoryPage,\n InboundMessage,\n MessageStatus,\n NormalizedInboundMessage,\n ResolveContactInput,\n ContactHint,\n SendMessageInput,\n SendMessageResult,\n ValidateCredentialsInput,\n ValidateCredentialsResult,\n VerifyWebhookInput,\n} from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { imapCapabilities } from './capabilities'\nimport { imapCredentialsSchema, imapChannelStateSchema, type ImapCredentials, type ImapChannelState } from './credentials'\nimport {\n credentialsToConnection,\n getImapClient,\n} from './imap-client'\nimport {\n credentialsToSmtpConnection,\n getSmtpClient,\n} from './smtp-client'\nimport { convertOutboundForEmail } from './convert-outbound'\nimport { normalizeInboundImapMessage } from './normalize-inbound'\nimport { validateImapCredentials } from './validate-credentials'\nimport { emailResolveContact } from '@open-mercato/core/modules/communication_channels/lib/email-contact'\nimport { decodeCursor, encodeCursor } from '@open-mercato/core/modules/communication_channels/lib/email-mime'\nimport { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('channel_imap')\n\n/**\n * IMAP+SMTP `ChannelAdapter`. Inbound is polling-driven (`realtimePush: false`),\n * outbound is SMTP. Threading is RFC2822 (In-Reply-To / References).\n *\n * Why this adapter omits some methods:\n * - `verifyWebhook` \u2014 IMAP has no webhook; we return a no-op event with\n * `eventType: 'other'` so the hub's webhook route returns 202 if anyone\n * ever POSTs at `/api/communication_channels/webhook/imap`.\n * - `getStatus` \u2014 IMAP has no delivery-status concept beyond `\\Seen`; we\n * return `{ status: 'sent' }` as a best-effort placeholder.\n * - No `sendReaction` / `editMessage` / `deleteMessage` \u2014 email doesn't\n * support these capabilities.\n */\nclass ImapChannelAdapter implements ChannelAdapter {\n readonly providerKey = 'imap'\n readonly channelType = 'email'\n readonly capabilities = imapCapabilities\n\n async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {\n const credentials = parseCredentialsOrThrow(input.credentials)\n\n // Reject attachments at the boundary BEFORE building the MIME body. The hub\n // passes attachments as URL pointers; until the IMAP/SMTP adapter wires a\n // fetcher (with size + content-type validation), inlining them is unsafe \u2014\n // a 0-byte attachment looks \"delivered\" but conveys nothing. Checking here\n // (rather than after conversion) avoids wasted MIME-build work and surfaces\n // the clearer \"attachments unsupported\" error even when recipients are also\n // missing. Documented in review M2 (2026-05-26) and tracked as a follow-up.\n if (Array.isArray(input.content.attachments) && input.content.attachments.length > 0) {\n return {\n externalMessageId: '',\n status: 'failed',\n error:\n '[internal] IMAP/SMTP adapter does not yet support attachments. Send the message without attachments or use a provider that supports them (Gmail).',\n }\n }\n\n let native: ChannelNativeContent\n try {\n native = await convertOutboundForEmail({\n body: input.content.html ?? input.content.text ?? '',\n bodyFormat: input.content.bodyFormat ?? (input.content.html ? 'html' : 'text'),\n attachments: input.content.attachments,\n channelMetadata: input.metadata,\n })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Outbound conversion failed'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n const meta = (native.metadata ?? {}) as Record<string, unknown>\n const to = Array.isArray(meta.to) ? (meta.to as string[]) : []\n if (to.length === 0) {\n return { externalMessageId: '', status: 'failed', error: '[internal] Email send requires at least one recipient' }\n }\n\n const smtp = getSmtpClient()\n const result = await smtp.send(credentialsToSmtpConnection(credentials), {\n from: credentials.fromAddress,\n to,\n cc: Array.isArray(meta.cc) ? (meta.cc as string[]) : undefined,\n bcc: Array.isArray(meta.bcc) ? (meta.bcc as string[]) : undefined,\n subject: typeof meta.subject === 'string' ? (meta.subject as string) : undefined,\n text: native.content.text,\n html: native.content.html,\n inReplyTo: typeof meta.inReplyTo === 'string' ? (meta.inReplyTo as string) : undefined,\n references: Array.isArray(meta.references) ? (meta.references as string[]) : undefined,\n messageId: typeof meta.messageId === 'string' ? (meta.messageId as string) : undefined,\n })\n\n // Best-effort append to Sent \u2014 many servers auto-store via \"Submission\" but not all do.\n const imap = getImapClient()\n try {\n // Skip when the RFC2822 bytes are empty (MailComposer build failed upstream):\n // appending a 0-byte buffer would create a corrupt Sent-folder entry, and the\n // send itself already succeeded.\n if (result.raw.length > 0) {\n await imap.appendSent(credentialsToConnection(credentials), result.raw)\n }\n } catch (appendError) {\n // Best-effort: many servers auto-store sent mail via Submission, and the\n // Sent mailbox name is provider-specific (localized, or \"[Gmail]/Sent Mail\").\n // Log so operators can diagnose missing Sent-folder archival rather than\n // failing the send.\n logger.warn('failed to append outbound message to Sent folder', { err: appendError })\n }\n\n return {\n externalMessageId: result.messageId,\n conversationId: input.conversationId,\n status: 'sent',\n metadata: { response: result.response },\n }\n }\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<InboundMessage> {\n return { raw: {}, eventType: 'other', metadata: { reason: 'imap-does-not-use-webhooks' } }\n }\n\n async getStatus(_input: GetMessageStatusInput): Promise<MessageStatus> {\n return { status: 'sent' }\n }\n\n async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> {\n return convertOutboundForEmail(input)\n }\n\n async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> {\n const rawBuffer = pickRawMimeBuffer(raw)\n const accountIdentifier = pickAccountIdentifier(raw)\n const uid = pickUid(raw)\n return normalizeInboundImapMessage({\n rawMessage: rawBuffer,\n uid,\n accountIdentifier,\n })\n }\n\n async validateCredentials(input: ValidateCredentialsInput): Promise<ValidateCredentialsResult> {\n return validateImapCredentials(input.credentials)\n }\n\n async fetchHistory(input: FetchHistoryInput): Promise<HistoryPage> {\n const credentials = parseCredentialsOrThrow(input.credentials)\n const channelState = imapChannelStateSchema.parse(input.channelState ?? {}) satisfies ImapChannelState\n const imap = getImapClient()\n const connection = credentialsToConnection(credentials)\n\n // Spec B \u00A7 Bounded, cursor-driven IMAP inbound:\n // - Bootstrap (no cursor): SELECT INBOX, persist UIDVALIDITY + UIDNEXT,\n // return ZERO messages. Backlog import happens via the explicit\n // `/import-history` endpoint, not via the silent connect flow.\n // - Incremental (cursor exists): UID FETCH `previousUidNext:*`, capped\n // at HARD_CAP = 200. If more available, set `hasMore: true` so the\n // hub re-enqueues immediately and drains the backlog.\n // - UIDVALIDITY mismatch: discard cursor and treat as bootstrap (the\n // mailbox was recreated or renamed; we cannot trust the prior cursor).\n const folderState = await imap.selectInbox(connection)\n const previousUidValidity = toNumberOrUndefined(channelState.uidValidity)\n const previousUidNext = toNumberOrUndefined(channelState.uidNext)\n const serverUidNext = toNumberOrUndefined(folderState.uidNext)\n const HARD_CAP = clampHardCap(input.limit)\n\n const uidValidityMismatch =\n previousUidValidity !== undefined &&\n folderState.uidValidity !== undefined &&\n folderState.uidValidity !== previousUidValidity\n if (uidValidityMismatch) {\n logger.warn('UIDVALIDITY changed for INBOX \u2014 discarding cursor and re-bootstrapping', {\n previousUidValidity,\n uidValidity: folderState.uidValidity,\n })\n }\n const needsBootstrap =\n uidValidityMismatch || previousUidNext === undefined || previousUidNext === null\n\n let fetched: { uid: number; rawBody: Buffer; internalDate?: Date; flags?: string[] }[]\n let hasMore = false\n if (needsBootstrap) {\n // \u2500\u2500 Bootstrap: persist cursor only, fetch zero messages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Spec B \u00A7 Bootstrap. The \"1M inbox\" failure mode is fixed by\n // construction: a fresh user sees zero history until they explicitly\n // request `/import-history`. Set `hasMore: false` so the poll worker\n // does NOT immediately re-enqueue.\n fetched = []\n hasMore = false\n } else if (previousUidNext !== undefined && serverUidNext !== undefined && previousUidNext >= serverUidNext) {\n // \u2500\u2500 Idle: UIDNEXT did not advance, so there is no new mail \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Skip the FETCH entirely. IMAP `<n>:*` always matches at least the\n // highest existing UID, so an idle mailbox would otherwise re-fetch and\n // re-normalize one already-ingested message every tick. The cursor is\n // retained downstream (an empty fetch does not advance it).\n fetched = []\n hasMore = false\n } else {\n // \u2500\u2500 Incremental: UID FETCH previousUidNext:* up to HARD_CAP \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // On a mature mailbox this is typically 0-N UIDs. The HARD_CAP bounds\n // the per-poll wall-clock + DB transaction size; if more remain, the\n // hub re-enqueues us immediately via `hasMore: true`.\n const range = `${previousUidNext}:*`\n // Fetch up to HARD_CAP + 1 so we can detect whether more remain\n // without paying for an extra round-trip later.\n const probeLimit = HARD_CAP + 1\n const raw = await imap.fetchUidRange(connection, range, { limit: probeLimit })\n if (raw.length > HARD_CAP) {\n fetched = raw.slice(0, HARD_CAP)\n hasMore = true\n } else {\n fetched = raw\n hasMore = false\n }\n }\n\n const messages: NormalizedInboundMessage[] = []\n for (const item of fetched) {\n const normalized = await normalizeInboundImapMessage({\n rawMessage: item.rawBody,\n uid: item.uid,\n accountIdentifier: credentials.fromAddress,\n // INTERNALDATE is when the server received the message; the MIME Date\n // header is the sender's and must not date the platform message (#6095).\n receivedAt: item.internalDate,\n })\n messages.push(normalized)\n }\n\n // Cursor advancement contract:\n // - Bootstrap: persist the server's current UIDNEXT so the next poll\n // becomes incremental from this point onward (intentionally skips the\n // pre-existing backlog; use `/import-history` to pull it).\n // - Incremental: persist `highestFetchedUid + 1` \u2014 NEVER the server's\n // UIDNEXT. When `fetched` is empty we retain `previousUidNext` so the\n // next poll resumes from the same point.\n const advancedUidNext = (() => {\n if (needsBootstrap) return serverUidNext\n if (fetched.length === 0) return previousUidNext\n const highest = fetched.reduce((max, item) => (item.uid > max ? item.uid : max), 0)\n // Anchor the cursor to the highest UID we ACTUALLY fetched \u2014 never to the\n // server's UIDNEXT. Providers like Gmail report a UIDNEXT that runs ahead\n // of the highest message currently in the folder (UID gaps from\n // labels/threads, or a message materialising into INBOX at a UID below\n // UIDNEXT). Jumping the cursor to `serverUidNext` then steps over any\n // INBOX message that sits below it: that message lands permanently below\n // the cursor and is never fetched again \u2014 the bug that silently dropped\n // inbound replies (UID 61979 skipped while cursor jumped to 61981).\n // `highest + 1` guarantees we never step over an unfetched message; if the\n // server's UIDNEXT is higher, the next poll just re-scans `highest+1:*`\n // (idempotent \u2014 the hub dedups on (channel_id, external_message_id)).\n return highest + 1\n })()\n const nextChannelState: ImapChannelState = {\n uidValidity: folderState.uidValidity ?? previousUidValidity,\n uidNext: advancedUidNext,\n lastFolder: 'INBOX',\n }\n\n // The hub's polling worker re-reads cursor through `fetchHistory`. We embed the\n // next-poll state in `nextCursor` (base64-encoded JSON) so workers can persist\n // it onto `CommunicationChannel.channelState` without depending on a hub-specific\n // contract beyond the existing `HistoryPage` shape.\n const nextCursor = encodeCursor(nextChannelState)\n return { messages, nextCursor, hasMore }\n }\n\n async importHistory(input: ImportHistoryInput): Promise<ImportHistoryPage> {\n const credentials = parseCredentialsOrThrow(input.credentials)\n const connection = credentialsToConnection(credentials)\n const imap = getImapClient()\n\n // Ceiling is provider-specific and lower than the deployment-wide one:\n // this adapter's cursor embeds the full remaining UID list, so it stays\n // capped until it gets a paging cursor of its own. See\n // `import-history-limits.ts` for the shared source of truth.\n const limits = getImportHistoryLimits(this.providerKey)\n\n const sinceDaysRaw = Number.isFinite(input.sinceDays) ? Math.trunc(input.sinceDays) : limits.defaultSinceDays\n const sinceDays = Math.max(1, Math.min(limits.maxSinceDays, sinceDaysRaw))\n const sinceDate = new Date(Date.now() - sinceDays * 24 * 60 * 60 * 1000)\n\n const maxMessagesRaw = Number.isFinite(input.maxMessages)\n ? Math.trunc(input.maxMessages as number)\n : limits.defaultMaxMessages\n const maxMessages = Math.max(1, Math.min(limits.maxMessages, maxMessagesRaw))\n\n const PAGE_SIZE = clampHardCap(undefined)\n\n // Resume previous page or perform initial SEARCH on first call. The cursor\n // encodes the full remaining UID list discovered server-side so subsequent\n // pages don't re-issue SEARCH (which on large mailboxes is expensive).\n let allUids: number[]\n let remainingUids: number[]\n let collectedSoFar: number\n let totalCandidates: number | undefined\n const cursor = decodeImportCursor(input.cursor)\n if (cursor) {\n remainingUids = cursor.remaining\n collectedSoFar = cursor.collected\n totalCandidates = cursor.total\n allUids = cursor.remaining\n } else {\n // FROM-chunking: SEARCH with very long OR chains can blow imapflow's\n // tag-buffer; chunk to \u226430 senders and union the results. When\n // contactEmails is empty we issue a single SINCE-only search.\n const senders = (input.contactEmails ?? []).filter((s): s is string => typeof s === 'string' && s.includes('@'))\n const uidSet = new Set<number>()\n if (senders.length === 0) {\n const uids = await imap.searchUidsByFromAndSince(connection, { sinceDate })\n for (const uid of uids) uidSet.add(uid)\n } else {\n const CHUNK_SIZE = 30\n for (let i = 0; i < senders.length; i += CHUNK_SIZE) {\n const chunk = senders.slice(i, i + CHUNK_SIZE)\n const uids = await imap.searchUidsByFromAndSince(connection, { fromAddresses: chunk, sinceDate })\n for (const uid of uids) uidSet.add(uid)\n }\n }\n // Process newest first (highest UIDs ~= most recent on standard servers).\n allUids = Array.from(uidSet).sort((a, b) => b - a).slice(0, maxMessages)\n remainingUids = allUids\n collectedSoFar = 0\n totalCandidates = allUids.length\n }\n\n if (remainingUids.length === 0) {\n return { messages: [], hasMore: false, totalCandidates }\n }\n\n const batchUids = remainingUids.slice(0, PAGE_SIZE)\n const stillRemaining = remainingUids.slice(PAGE_SIZE)\n const uidSetExpression = batchUids.join(',')\n const fetched = await imap.fetchUidRange(connection, uidSetExpression, { limit: PAGE_SIZE })\n\n const messages: NormalizedInboundMessage[] = []\n for (const item of fetched) {\n const normalized = await normalizeInboundImapMessage({\n rawMessage: item.rawBody,\n uid: item.uid,\n accountIdentifier: credentials.fromAddress,\n // INTERNALDATE is when the server received the message; the MIME Date\n // header is the sender's and must not date the platform message (#6095).\n receivedAt: item.internalDate,\n })\n messages.push(normalized)\n }\n\n const newCollected = collectedSoFar + messages.length\n const hasMore = stillRemaining.length > 0 && newCollected < maxMessages\n const nextCursor = hasMore\n ? encodeImportCursor({ remaining: stillRemaining, collected: newCollected, total: totalCandidates })\n : undefined\n\n return { messages, nextCursor, hasMore, totalCandidates }\n }\n\n async resolveContact(input: ResolveContactInput): Promise<ContactHint | null> {\n return emailResolveContact(input)\n }\n}\n\nfunction parseCredentialsOrThrow(value: unknown): ImapCredentials {\n const parsed = imapCredentialsSchema.safeParse(value)\n if (!parsed.success) {\n const first = parsed.error.issues[0]\n throw new Error(`Invalid IMAP credentials: ${first?.message ?? 'unknown validation error'}`)\n }\n return parsed.data\n}\n\nfunction pickRawMimeBuffer(raw: InboundMessage): Buffer {\n const candidate = raw.raw as { rawBody?: unknown; mime?: unknown }\n const value = candidate?.rawBody ?? candidate?.mime ?? raw.raw\n if (Buffer.isBuffer(value)) return value\n if (value instanceof Uint8Array) return Buffer.from(value)\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n throw new Error('[internal] IMAP normalizeInbound requires `raw.rawBody` to be a Buffer or string MIME payload')\n}\n\nfunction pickAccountIdentifier(raw: InboundMessage): string {\n const candidate = raw.raw as { accountIdentifier?: unknown }\n const id = typeof candidate?.accountIdentifier === 'string' ? candidate.accountIdentifier : undefined\n return id ?? 'unknown@imap'\n}\n\nfunction pickUid(raw: InboundMessage): number | undefined {\n const candidate = raw.raw as { uid?: unknown }\n return typeof candidate?.uid === 'number' ? candidate.uid : undefined\n}\n\n/**\n * Spec B \u00A7 HARD_CAP. Bound each poll's wall-clock + DB transaction size.\n * Honor the caller's `limit` hint but never exceed `HARD_CAP_MAX`. A\n * single poll will fetch at most this many UIDs; if more remain we set\n * `hasMore: true` and the hub re-enqueues immediately.\n *\n * Configurable via `OM_CHANNEL_IMAP_HARD_CAP_PER_POLL` (default 200).\n */\nfunction clampHardCap(callerLimit: number | undefined): number {\n const envOverride = Number.parseInt(process.env.OM_CHANNEL_IMAP_HARD_CAP_PER_POLL ?? '', 10)\n const HARD_CAP_MAX = Number.isFinite(envOverride) && envOverride > 0 ? envOverride : 200\n if (typeof callerLimit === 'number' && callerLimit > 0) {\n return Math.min(callerLimit, HARD_CAP_MAX)\n }\n return HARD_CAP_MAX\n}\n\ninterface ImportCursor {\n remaining: number[]\n collected: number\n total?: number\n}\n\nfunction encodeImportCursor(cursor: ImportCursor): string {\n return encodeCursor(cursor)\n}\n\nfunction decodeImportCursor(value: string | undefined): ImportCursor | null {\n const parsed = decodeCursor(value)\n if (!parsed || typeof parsed !== 'object') return null\n const obj = parsed as { remaining?: unknown; collected?: unknown; total?: unknown }\n const remaining = Array.isArray(obj.remaining)\n ? obj.remaining.filter((n): n is number => typeof n === 'number' && Number.isFinite(n))\n : []\n const collected = typeof obj.collected === 'number' ? obj.collected : 0\n const total = typeof obj.total === 'number' ? obj.total : undefined\n return { remaining, collected, total }\n}\n\nfunction toNumberOrUndefined(value: unknown): number | undefined {\n if (typeof value === 'number') return value\n if (typeof value === 'string' && value.length > 0) {\n const n = Number(value)\n return Number.isFinite(n) ? n : undefined\n }\n return undefined\n}\n\nlet cachedAdapter: ImapChannelAdapter | null = null\n\nexport function getImapChannelAdapter(): ImapChannelAdapter {\n if (!cachedAdapter) cachedAdapter = new ImapChannelAdapter()\n return cachedAdapter\n}\n\nexport { ImapChannelAdapter }\n"],
|
|
5
|
+
"mappings": "AAoBA,SAAS,wBAAwB;AACjC,SAAS,uBAAuB,8BAA2E;AAC3G;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AACxC,SAAS,mCAAmC;AAC5C,SAAS,+BAA+B;AACxC,SAAS,2BAA2B;AACpC,SAAS,cAAc,oBAAoB;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc;AAe1C,MAAM,mBAA6C;AAAA,EAAnD;AACE,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,eAAe;AAAA;AAAA,EAExB,MAAM,YAAY,OAAqD;AACrE,UAAM,cAAc,wBAAwB,MAAM,WAAW;AAS7D,QAAI,MAAM,QAAQ,MAAM,QAAQ,WAAW,KAAK,MAAM,QAAQ,YAAY,SAAS,GAAG;AACpF,aAAO;AAAA,QACL,mBAAmB;AAAA,QACnB,QAAQ;AAAA,QACR,OACE;AAAA,MACJ;AAAA,IACF;AAEA,QAAI;AACJ,QAAI;AACF,eAAS,MAAM,wBAAwB;AAAA,QACrC,MAAM,MAAM,QAAQ,QAAQ,MAAM,QAAQ,QAAQ;AAAA,QAClD,YAAY,MAAM,QAAQ,eAAe,MAAM,QAAQ,OAAO,SAAS;AAAA,QACvE,aAAa,MAAM,QAAQ;AAAA,QAC3B,iBAAiB,MAAM;AAAA,MACzB,CAAC;AAAA,IACH,SAAS,OAA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UAAU,WAAW,IAAI,QAAQ;AAC1D,SAAO,EAAE,WAAW,WAAW,MAAM;AACvC;AAEA,SAAS,oBAAoB,OAAoC;AAC/D,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAAG;AACjD,UAAM,IAAI,OAAO,KAAK;AACtB,WAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAAA,EAClC;AACA,SAAO;AACT;AAEA,IAAI,gBAA2C;AAExC,SAAS,wBAA4C;AAC1D,MAAI,CAAC,cAAe,iBAAgB,IAAI,mBAAmB;AAC3D,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -9,6 +9,7 @@ async function normalizeInboundImapMessage(options) {
|
|
|
9
9
|
accountIdentifier: options.accountIdentifier,
|
|
10
10
|
fallbackMessageId: `imap:${options.uid ?? "unknown"}@${options.accountIdentifier}`,
|
|
11
11
|
resolveConversationId: ({ messageId, references }) => references[0] ?? messageId,
|
|
12
|
+
receivedAt: options.receivedAt,
|
|
12
13
|
fallbackDate: options.fallbackDate,
|
|
13
14
|
channelMetadata: () => ({ uid: options.uid })
|
|
14
15
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/channel_imap/lib/normalize-inbound.ts"],
|
|
4
|
-
"sourcesContent": ["import type { NormalizedInboundMessage } from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport {\n normalizeMimeInbound,\n type ParsedMail,\n} from '@open-mercato/core/modules/communication_channels/lib/email-mime'\n\n/**\n * Convert a raw RFC2822 MIME buffer (delivered by IMAP fetch) to the hub's\n * canonical `NormalizedInboundMessage`. Parses with `mailparser`, then delegates\n * threading / attachments / headers to the shared `normalizeMimeInbound` helper.\n *\n * Threading:\n * - `externalMessageId` := MIME `Message-ID` header (RFC2822). Required by\n * IMAP/SMTP; if missing we fall back to `imap:<uid>@<account>` so downstream\n * idempotency still has a deterministic key.\n * - `replyToExternalId` := `In-Reply-To` header (single value).\n * - `externalConversationId` := the root of the References chain when present,\n * otherwise the message id itself (single-message thread).\n */\n\nexport interface NormalizeInboundOptions {\n rawMessage: Buffer\n /** UID from the IMAP fetch \u2014 embedded into `channelMetadata.uid` for diagnostics. */\n uid?: number\n /** External identifier of the receiving channel (typically the account's email). */\n accountIdentifier: string\n /**
|
|
5
|
-
"mappings": "AACA;AAAA,EACE;AAAA,OAEK;
|
|
4
|
+
"sourcesContent": ["import type { NormalizedInboundMessage } from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport {\n normalizeMimeInbound,\n type ParsedMail,\n} from '@open-mercato/core/modules/communication_channels/lib/email-mime'\n\n/**\n * Convert a raw RFC2822 MIME buffer (delivered by IMAP fetch) to the hub's\n * canonical `NormalizedInboundMessage`. Parses with `mailparser`, then delegates\n * threading / attachments / headers to the shared `normalizeMimeInbound` helper.\n *\n * Threading:\n * - `externalMessageId` := MIME `Message-ID` header (RFC2822). Required by\n * IMAP/SMTP; if missing we fall back to `imap:<uid>@<account>` so downstream\n * idempotency still has a deterministic key.\n * - `replyToExternalId` := `In-Reply-To` header (single value).\n * - `externalConversationId` := the root of the References chain when present,\n * otherwise the message id itself (single-message thread).\n */\n\nexport interface NormalizeInboundOptions {\n rawMessage: Buffer\n /** UID from the IMAP fetch \u2014 embedded into `channelMetadata.uid` for diagnostics. */\n uid?: number\n /** External identifier of the receiving channel (typically the account's email). */\n accountIdentifier: string\n /** IMAP `INTERNALDATE`: when the server received the message. Wins over the MIME Date header. */\n receivedAt?: Date\n /** Used only when neither `receivedAt` nor a usable Date header is available. */\n fallbackDate?: Date\n}\n\nexport async function normalizeInboundImapMessage(\n options: NormalizeInboundOptions,\n): Promise<NormalizedInboundMessage> {\n const mailparser = (await import('mailparser')) as unknown as {\n simpleParser: (buf: Buffer | string) => Promise<ParsedMail>\n }\n const parsed = await mailparser.simpleParser(options.rawMessage)\n\n return normalizeMimeInbound({\n parsed,\n accountIdentifier: options.accountIdentifier,\n fallbackMessageId: `imap:${options.uid ?? 'unknown'}@${options.accountIdentifier}`,\n resolveConversationId: ({ messageId, references }) => references[0] ?? messageId,\n receivedAt: options.receivedAt,\n fallbackDate: options.fallbackDate,\n channelMetadata: () => ({ uid: options.uid }),\n })\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EACE;AAAA,OAEK;AA4BP,eAAsB,4BACpB,SACmC;AACnC,QAAM,aAAc,MAAM,OAAO,YAAY;AAG7C,QAAM,SAAS,MAAM,WAAW,aAAa,QAAQ,UAAU;AAE/D,SAAO,qBAAqB;AAAA,IAC1B;AAAA,IACA,mBAAmB,QAAQ;AAAA,IAC3B,mBAAmB,QAAQ,QAAQ,OAAO,SAAS,IAAI,QAAQ,iBAAiB;AAAA,IAChF,uBAAuB,CAAC,EAAE,WAAW,WAAW,MAAM,WAAW,CAAC,KAAK;AAAA,IACvE,YAAY,QAAQ;AAAA,IACpB,cAAc,QAAQ;AAAA,IACtB,iBAAiB,OAAO,EAAE,KAAK,QAAQ,IAAI;AAAA,EAC7C,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/channel-imap",
|
|
3
|
-
"version": "0.8.1-develop.
|
|
3
|
+
"version": "0.8.1-develop.7267.1.2e95af80a6",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -62,9 +62,9 @@
|
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@open-mercato/core": "0.8.1-develop.
|
|
66
|
-
"@open-mercato/queue": "0.8.1-develop.
|
|
67
|
-
"@open-mercato/ui": "0.8.1-develop.
|
|
65
|
+
"@open-mercato/core": "0.8.1-develop.7267.1.2e95af80a6",
|
|
66
|
+
"@open-mercato/queue": "0.8.1-develop.7267.1.2e95af80a6",
|
|
67
|
+
"@open-mercato/ui": "0.8.1-develop.7267.1.2e95af80a6",
|
|
68
68
|
"@types/mailparser": "^3.4.5",
|
|
69
69
|
"@types/nodemailer": "^8.0.1",
|
|
70
70
|
"imapflow": "^1.7.6",
|
|
@@ -73,12 +73,12 @@
|
|
|
73
73
|
},
|
|
74
74
|
"peerDependencies": {
|
|
75
75
|
"@mikro-orm/postgresql": "^7.0.14",
|
|
76
|
-
"@open-mercato/shared": "0.8.1-develop.
|
|
76
|
+
"@open-mercato/shared": "0.8.1-develop.7267.1.2e95af80a6",
|
|
77
77
|
"react": "^19.0.0",
|
|
78
78
|
"react-dom": "^19.0.0"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"@open-mercato/shared": "0.8.1-develop.
|
|
81
|
+
"@open-mercato/shared": "0.8.1-develop.7267.1.2e95af80a6",
|
|
82
82
|
"@types/jest": "^30.0.0",
|
|
83
83
|
"@types/react": "^19.2.18",
|
|
84
84
|
"@types/react-dom": "^19.2.5",
|
|
@@ -69,6 +69,24 @@ describe('normalizeInboundImapMessage', () => {
|
|
|
69
69
|
expect(result.channelContentType).toBe('email/mime')
|
|
70
70
|
})
|
|
71
71
|
|
|
72
|
+
it('dates the message with INTERNALDATE, not the sender-written Date header (#6095)', async () => {
|
|
73
|
+
const receivedAt = new Date('2026-05-21T10:00:07.000Z')
|
|
74
|
+
const result = await normalizeInboundImapMessage({
|
|
75
|
+
rawMessage: buildMimeMessage({
|
|
76
|
+
messageId: '<skewed@example.com>',
|
|
77
|
+
from: 'alice@example.com',
|
|
78
|
+
to: 'bob@example.com',
|
|
79
|
+
subject: 'skewed',
|
|
80
|
+
text: 'hi',
|
|
81
|
+
date: 'Tue, 01 Jan 2030 00:00:00 +0000',
|
|
82
|
+
}),
|
|
83
|
+
uid: 43,
|
|
84
|
+
accountIdentifier: 'bob@example.com',
|
|
85
|
+
receivedAt,
|
|
86
|
+
})
|
|
87
|
+
expect(result.timestamp).toEqual(receivedAt)
|
|
88
|
+
})
|
|
89
|
+
|
|
72
90
|
it('synthesises a deterministic fallback message id when missing', async () => {
|
|
73
91
|
const result = await normalizeInboundImapMessage({
|
|
74
92
|
rawMessage: buildMimeMessage({
|
|
@@ -236,7 +236,9 @@ class ImapChannelAdapter implements ChannelAdapter {
|
|
|
236
236
|
rawMessage: item.rawBody,
|
|
237
237
|
uid: item.uid,
|
|
238
238
|
accountIdentifier: credentials.fromAddress,
|
|
239
|
-
|
|
239
|
+
// INTERNALDATE is when the server received the message; the MIME Date
|
|
240
|
+
// header is the sender's and must not date the platform message (#6095).
|
|
241
|
+
receivedAt: item.internalDate,
|
|
240
242
|
})
|
|
241
243
|
messages.push(normalized)
|
|
242
244
|
}
|
|
@@ -353,7 +355,9 @@ class ImapChannelAdapter implements ChannelAdapter {
|
|
|
353
355
|
rawMessage: item.rawBody,
|
|
354
356
|
uid: item.uid,
|
|
355
357
|
accountIdentifier: credentials.fromAddress,
|
|
356
|
-
|
|
358
|
+
// INTERNALDATE is when the server received the message; the MIME Date
|
|
359
|
+
// header is the sender's and must not date the platform message (#6095).
|
|
360
|
+
receivedAt: item.internalDate,
|
|
357
361
|
})
|
|
358
362
|
messages.push(normalized)
|
|
359
363
|
}
|
|
@@ -24,7 +24,9 @@ export interface NormalizeInboundOptions {
|
|
|
24
24
|
uid?: number
|
|
25
25
|
/** External identifier of the receiving channel (typically the account's email). */
|
|
26
26
|
accountIdentifier: string
|
|
27
|
-
/**
|
|
27
|
+
/** IMAP `INTERNALDATE`: when the server received the message. Wins over the MIME Date header. */
|
|
28
|
+
receivedAt?: Date
|
|
29
|
+
/** Used only when neither `receivedAt` nor a usable Date header is available. */
|
|
28
30
|
fallbackDate?: Date
|
|
29
31
|
}
|
|
30
32
|
|
|
@@ -41,6 +43,7 @@ export async function normalizeInboundImapMessage(
|
|
|
41
43
|
accountIdentifier: options.accountIdentifier,
|
|
42
44
|
fallbackMessageId: `imap:${options.uid ?? 'unknown'}@${options.accountIdentifier}`,
|
|
43
45
|
resolveConversationId: ({ messageId, references }) => references[0] ?? messageId,
|
|
46
|
+
receivedAt: options.receivedAt,
|
|
44
47
|
fallbackDate: options.fallbackDate,
|
|
45
48
|
channelMetadata: () => ({ uid: options.uid }),
|
|
46
49
|
})
|