@open-mercato/channel-imap 0.10.1-develop.8259.1.382cb7589a → 0.10.1-develop.8271.1.346e524319

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.
@@ -6,13 +6,19 @@ import {
6
6
  } from "./imap-client.js";
7
7
  import {
8
8
  credentialsToSmtpConnection,
9
- getSmtpClient
9
+ getSmtpClient,
10
+ isSmtpMessageTooLarge
10
11
  } from "./smtp-client.js";
11
12
  import { convertOutboundForEmail } from "./convert-outbound.js";
12
13
  import { normalizeInboundImapMessage } from "./normalize-inbound.js";
13
14
  import { validateImapCredentials } from "./validate-credentials.js";
14
15
  import { emailResolveContact } from "@open-mercato/core/modules/communication_channels/lib/email-contact";
15
- import { decodeCursor, encodeCursor } from "@open-mercato/core/modules/communication_channels/lib/email-mime";
16
+ import {
17
+ decodeCursor,
18
+ encodeCursor,
19
+ sanitizeHeaderValue
20
+ } from "@open-mercato/core/modules/communication_channels/lib/email-mime";
21
+ import { resolveOutboundAttachmentBytes } from "@open-mercato/core/modules/communication_channels/lib/outbound-attachments";
16
22
  import { getImportHistoryLimits } from "@open-mercato/core/modules/communication_channels/lib/import-history-limits";
17
23
  import { createLogger } from "@open-mercato/shared/lib/logger";
18
24
  const logger = createLogger("channel_imap");
@@ -24,13 +30,6 @@ class ImapChannelAdapter {
24
30
  }
25
31
  async sendMessage(input) {
26
32
  const credentials = parseCredentialsOrThrow(input.credentials);
27
- if (Array.isArray(input.content.attachments) && input.content.attachments.length > 0) {
28
- return {
29
- externalMessageId: "",
30
- status: "failed",
31
- error: "[internal] IMAP/SMTP adapter does not yet support attachments. Send the message without attachments or use a provider that supports them (Gmail)."
32
- };
33
- }
34
33
  let native;
35
34
  try {
36
35
  native = await convertOutboundForEmail({
@@ -48,19 +47,44 @@ class ImapChannelAdapter {
48
47
  if (to.length === 0) {
49
48
  return { externalMessageId: "", status: "failed", error: "[internal] Email send requires at least one recipient" };
50
49
  }
50
+ let attachments;
51
+ try {
52
+ attachments = native.content.attachments?.map((attachment) => ({
53
+ filename: sanitizeHeaderValue(attachment.fileName) || "attachment",
54
+ content: asBuffer(resolveOutboundAttachmentBytes(attachment)),
55
+ contentType: attachment.mimeType,
56
+ inline: attachment.inline
57
+ }));
58
+ } catch (error) {
59
+ const message = error instanceof Error ? error.message : "[internal] Outbound attachment is not readable";
60
+ return { externalMessageId: "", status: "failed", error: message };
61
+ }
51
62
  const smtp = getSmtpClient();
52
- const result = await smtp.send(credentialsToSmtpConnection(credentials), {
53
- from: credentials.fromAddress,
54
- to,
55
- cc: Array.isArray(meta.cc) ? meta.cc : void 0,
56
- bcc: Array.isArray(meta.bcc) ? meta.bcc : void 0,
57
- subject: typeof meta.subject === "string" ? meta.subject : void 0,
58
- text: native.content.text,
59
- html: native.content.html,
60
- inReplyTo: typeof meta.inReplyTo === "string" ? meta.inReplyTo : void 0,
61
- references: Array.isArray(meta.references) ? meta.references : void 0,
62
- messageId: typeof meta.messageId === "string" ? meta.messageId : void 0
63
- });
63
+ let result;
64
+ try {
65
+ result = await smtp.send(credentialsToSmtpConnection(credentials), {
66
+ from: credentials.fromAddress,
67
+ to,
68
+ cc: Array.isArray(meta.cc) ? meta.cc : void 0,
69
+ bcc: Array.isArray(meta.bcc) ? meta.bcc : void 0,
70
+ subject: typeof meta.subject === "string" ? meta.subject : void 0,
71
+ text: native.content.text,
72
+ html: native.content.html,
73
+ inReplyTo: typeof meta.inReplyTo === "string" ? meta.inReplyTo : void 0,
74
+ references: Array.isArray(meta.references) ? meta.references : void 0,
75
+ messageId: typeof meta.messageId === "string" ? meta.messageId : void 0,
76
+ attachments
77
+ });
78
+ } catch (error) {
79
+ if (isSmtpMessageTooLarge(error)) {
80
+ return {
81
+ externalMessageId: "",
82
+ status: "failed",
83
+ error: "[internal] The mail server rejected the message as too large (message_too_large)"
84
+ };
85
+ }
86
+ throw error;
87
+ }
64
88
  const imap = getImapClient();
65
89
  try {
66
90
  if (result.raw.length > 0) {
@@ -238,6 +262,9 @@ function parseCredentialsOrThrow(value) {
238
262
  }
239
263
  return parsed.data;
240
264
  }
265
+ function asBuffer(bytes) {
266
+ return Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
267
+ }
241
268
  function pickRawMimeBuffer(raw) {
242
269
  const candidate = raw.raw;
243
270
  const value = candidate?.rawBody ?? candidate?.mime ?? raw.raw;
@@ -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 // 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;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put,\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 isSmtpMessageTooLarge,\n type SmtpMessage,\n type SmtpSendResult,\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 {\n decodeCursor,\n encodeCursor,\n sanitizeHeaderValue,\n} from '@open-mercato/core/modules/communication_channels/lib/email-mime'\nimport { resolveOutboundAttachmentBytes } from '@open-mercato/core/modules/communication_channels/lib/outbound-attachments'\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 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 // Attachments arrive as bytes the hub read from the attachments module (or\n // as `data:` URLs); a remote URL is refused rather than fetched.\n let attachments: SmtpMessage['attachments']\n try {\n attachments = native.content.attachments?.map((attachment) => ({\n filename: sanitizeHeaderValue(attachment.fileName) || 'attachment',\n content: asBuffer(resolveOutboundAttachmentBytes(attachment)),\n contentType: attachment.mimeType,\n inline: attachment.inline,\n }))\n } catch (error) {\n const message = error instanceof Error ? error.message : '[internal] Outbound attachment is not readable'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n\n const smtp = getSmtpClient()\n let result: SmtpSendResult\n try {\n 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 attachments,\n })\n } catch (error) {\n if (isSmtpMessageTooLarge(error)) {\n return {\n externalMessageId: '',\n status: 'failed',\n error: '[internal] The mail server rejected the message as too large (message_too_large)',\n }\n }\n throw error\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 asBuffer(bytes: Uint8Array): Buffer {\n return Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)\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,EACA;AAAA,OAGK;AACP,SAAS,+BAA+B;AACxC,SAAS,mCAAmC;AAC5C,SAAS,+BAA+B;AACxC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sCAAsC;AAC/C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,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,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
  }
@@ -1,6 +1,7 @@
1
1
  import { baseEmailCapabilities } from "@open-mercato/core/modules/communication_channels/lib/email-capabilities";
2
2
  const imapCapabilities = {
3
- ...baseEmailCapabilities
3
+ ...baseEmailCapabilities,
4
+ fileSharing: true
4
5
  };
5
6
  export {
6
7
  imapCapabilities
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/channel_imap/lib/capabilities.ts"],
4
- "sourcesContent": ["import type { ChannelCapabilities } from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { baseEmailCapabilities } from '@open-mercato/core/modules/communication_channels/lib/email-capabilities'\n\n/**\n * IMAP+SMTP capabilities. Polling-based (no real-time push), threaded via\n * RFC2822 In-Reply-To / References, rich HTML/plain-text body, inline + regular\n * attachments. No reactions, no edit/delete (only the IMAP `\\Seen` flag, which\n * the user controls locally and is not reliably surfaced).\n *\n * `fileSharing: false` (R2-M4 / F11, 2026-05-26): the adapter's `sendMessage`\n * fails-fast on attachments (it doesn't yet fetch + inline attachment URLs into\n * MIME bodies). Re-enable when URL-fetch + size-validation lands.\n */\nexport const imapCapabilities: ChannelCapabilities = {\n ...baseEmailCapabilities,\n}\n"],
5
- "mappings": "AACA,SAAS,6BAA6B;AAY/B,MAAM,mBAAwC;AAAA,EACnD,GAAG;AACL;",
4
+ "sourcesContent": ["import type { ChannelCapabilities } from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { baseEmailCapabilities } from '@open-mercato/core/modules/communication_channels/lib/email-capabilities'\n\n/**\n * IMAP+SMTP capabilities. Polling-based (no real-time push), threaded via\n * RFC2822 In-Reply-To / References, rich HTML/plain-text body, inline + regular\n * attachments. No reactions, no edit/delete (only the IMAP `\\Seen` flag, which\n * the user controls locally and is not reliably surfaced).\n *\n * `fileSharing: true`: `sendMessage` hands nodemailer the attachment bytes the\n * hub reads from the attachments module; a remote attachment URL is refused.\n */\nexport const imapCapabilities: ChannelCapabilities = {\n ...baseEmailCapabilities,\n fileSharing: true,\n}\n"],
5
+ "mappings": "AACA,SAAS,6BAA6B;AAW/B,MAAM,mBAAwC;AAAA,EACnD,GAAG;AAAA,EACH,aAAa;AACf;",
6
6
  "names": []
7
7
  }
@@ -13,6 +13,15 @@ async function loadMailComposer() {
13
13
  return void 0;
14
14
  }
15
15
  }
16
+ function isSmtpMessageTooLarge(error) {
17
+ if (!error || typeof error !== "object") return false;
18
+ const { responseCode, response, message } = error;
19
+ const text = `${response ?? ""} ${message ?? ""}`;
20
+ if (/size larger than allowed/i.test(text)) return true;
21
+ if (responseCode !== 552 && responseCode !== 554) return false;
22
+ if (/\b5\.2\.2\b/.test(text)) return false;
23
+ return /5\.3\.4|5\.2\.3|too (large|big)|message size|size exceeds/i.test(text);
24
+ }
16
25
  function generateMessageId(from) {
17
26
  const domain = /@([^\s<>@]+)>?\s*$/.exec(from)?.[1] ?? "localhost";
18
27
  return `<${randomUUID()}@${domain}>`;
@@ -47,7 +56,11 @@ class NodemailerClient {
47
56
  cid: a.cid,
48
57
  contentDisposition: a.inline ? "inline" : "attachment"
49
58
  })),
50
- headers: message.headers
59
+ headers: message.headers,
60
+ // Attachments are always bytes; never let a value make nodemailer read
61
+ // the local disk or fetch a URL.
62
+ disableFileAccess: true,
63
+ disableUrlAccess: true
51
64
  };
52
65
  let raw = Buffer.alloc(0);
53
66
  let composedMessageId = message.messageId;
@@ -123,6 +136,7 @@ export {
123
136
  credentialsToSmtpConnection,
124
137
  generateMessageId,
125
138
  getSmtpClient,
139
+ isSmtpMessageTooLarge,
126
140
  setSmtpClient
127
141
  };
128
142
  //# sourceMappingURL=smtp-client.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/channel_imap/lib/smtp-client.ts"],
4
- "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { ImapCredentials } from './credentials'\nimport { resolveSafeHostAddress } from './host-pinning'\nimport { assertTransportAllowed } from './transport'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('channel_imap')\n\n/**\n * Outbound SMTP client wrapper. Same trade-offs as `imap-client.ts`: we wrap\n * `nodemailer` behind a tiny interface so tests can swap in a mock and the\n * adapter doesn't import SDK types directly.\n */\n\nexport interface SmtpConnectionOptions {\n host: string\n port: number\n user: string\n pass: string\n transport: 'tls' | 'starttls' | 'none'\n timeoutMs?: number\n}\n\nexport interface SmtpMessage {\n from: string\n to: string[]\n cc?: string[]\n bcc?: string[]\n subject?: string\n text?: string\n html?: string\n /** RFC2822 Message-ID; if omitted the client generates one from the sender domain. */\n messageId?: string\n /** RFC2822 In-Reply-To (single value). */\n inReplyTo?: string\n /** RFC2822 References (whitespace-delimited list). */\n references?: string[]\n attachments?: Array<{\n filename: string\n content: Buffer\n contentType?: string\n cid?: string\n inline?: boolean\n }>\n headers?: Record<string, string>\n}\n\nexport interface SmtpSendResult {\n /** Effective Message-ID. */\n messageId: string\n /** Raw RFC2822 message buffer (used for Sent-folder append). */\n raw: Buffer\n /** Provider response string. */\n response?: string\n}\n\nexport interface SmtpClient {\n verify(options: SmtpConnectionOptions): Promise<void>\n send(options: SmtpConnectionOptions, message: SmtpMessage): Promise<SmtpSendResult>\n}\n\ntype MailComposerCtor = new (mail: Record<string, unknown>) => unknown\n\n// nodemailer 10 dropped the root `MailComposer` re-export that v9 exposed; it is\n// still published under the `nodemailer/lib/mail-composer` subpath. Without this\n// fallback the Sent-folder append silently uploads a 0-byte message.\nasync function loadMailComposer(): Promise<MailComposerCtor | undefined> {\n try {\n const mod = (await import('nodemailer/lib/mail-composer')) as unknown as {\n default?: MailComposerCtor\n } & MailComposerCtor\n const ctor = mod.default ?? mod\n return typeof ctor === 'function' ? ctor : undefined\n } catch (err) {\n logger.warn('failed to load nodemailer MailComposer', { err })\n return undefined\n }\n}\n\n// send() composes the message twice (MailComposer for the Sent-folder bytes, then\n// transporter.sendMail), and each composition would generate its own Message-ID.\n// Pinning one up front keeps the Sent copy, the delivered message and the\n// returned id identical so replies thread with the Sent copy.\nexport function generateMessageId(from: string): string {\n const domain = /@([^\\s<>@]+)>?\\s*$/.exec(from)?.[1] ?? 'localhost'\n return `<${randomUUID()}@${domain}>`\n}\n\nclass NodemailerClient implements SmtpClient {\n async verify(options: SmtpConnectionOptions): Promise<void> {\n const { transporter } = await this.createTransporter(options)\n try {\n await transporter.verify()\n } finally {\n // Mirror send(): close on every path so a failed verify (wrong password,\n // unreachable host \u2014 the common case) does not leak the socket pool.\n transporter.close()\n }\n }\n\n async send(options: SmtpConnectionOptions, message: SmtpMessage): Promise<SmtpSendResult> {\n const { transporter, MailComposer } = await this.createTransporter(options)\n try {\n const mailOptions: Record<string, unknown> = {\n from: message.from,\n to: message.to,\n cc: message.cc,\n bcc: message.bcc,\n subject: message.subject,\n text: message.text,\n html: message.html,\n messageId: message.messageId ?? generateMessageId(message.from),\n inReplyTo: message.inReplyTo,\n references: message.references,\n attachments: message.attachments?.map((a) => ({\n filename: a.filename,\n content: a.content,\n contentType: a.contentType,\n cid: a.cid,\n contentDisposition: a.inline ? 'inline' : 'attachment',\n })),\n headers: message.headers,\n }\n\n // Build the RFC2822 bytes ourselves via MailComposer so we can capture\n // them for the Sent-folder append (review H1, 2026-05-26).\n // nodemailer's `transporter.sendMail` info object does NOT contain `raw`\n // unless you configure a streamTransport, so naively reading\n // `info.raw` produces a 0-byte buffer and the Sent-folder append uploads\n // a corrupt message.\n let raw: Buffer = Buffer.alloc(0)\n let composedMessageId = message.messageId\n if (typeof MailComposer === 'function') {\n try {\n const composed = new MailComposer(mailOptions) as unknown as {\n compile: () => {\n build: (callback: (err: Error | null, output: Buffer) => void) => void\n messageId?: () => string | undefined\n }\n }\n const compiled = composed.compile()\n raw = await new Promise<Buffer>((resolve, reject) => {\n compiled.build((err, output) => {\n if (err) reject(err)\n else resolve(output)\n })\n })\n const messageIdFn = compiled.messageId\n if (typeof messageIdFn === 'function') {\n composedMessageId = messageIdFn.call(compiled) ?? composedMessageId\n }\n } catch (composeError) {\n // MailComposer build failed: the send below still delivers the mail, but we\n // cannot capture the RFC2822 bytes, so the caller skips the Sent-folder append.\n // Log so operators can diagnose missing Sent archival.\n raw = Buffer.alloc(0)\n logger.warn('failed to build RFC2822 bytes for Sent-folder append', { err: composeError })\n }\n }\n\n const info = (await transporter.sendMail(mailOptions)) as {\n messageId?: string\n envelope?: { messageId?: string }\n response?: string\n }\n const id = info.messageId ?? composedMessageId ?? info.envelope?.messageId\n if (!id) throw new Error('[internal] SMTP server did not return a Message-ID')\n return { messageId: id, raw, response: info.response }\n } finally {\n transporter.close()\n }\n }\n\n private async createTransporter(\n options: SmtpConnectionOptions,\n ): Promise<{\n transporter: NodemailerTransporter\n MailComposer: (new (mail: Record<string, unknown>) => unknown) | undefined\n }> {\n const mod = (await import('nodemailer')) as unknown as {\n default?: {\n createTransport: (opts: Record<string, unknown>) => NodemailerTransporter\n MailComposer?: new (mail: Record<string, unknown>) => unknown\n }\n createTransport?: (opts: Record<string, unknown>) => NodemailerTransporter\n MailComposer?: new (mail: Record<string, unknown>) => unknown\n }\n const createTransport = mod.createTransport ?? mod.default?.createTransport\n if (typeof createTransport !== 'function') {\n throw new Error('nodemailer.createTransport is unavailable')\n }\n const MailComposer = mod.MailComposer ?? mod.default?.MailComposer ?? await loadMailComposer()\n // Resolve + pin the SMTP host to a validated public IP at connect time\n // (DNS-rebinding-safe), keeping the hostname as the TLS servername for SNI +\n // certificate hostname verification.\n const pinned = await resolveSafeHostAddress(options.host)\n const transporter = createTransport({\n host: pinned.host,\n port: options.port,\n secure: options.transport === 'tls',\n requireTLS: options.transport === 'starttls',\n auth: { user: options.user, pass: options.pass },\n connectionTimeout: options.timeoutMs ?? 10_000,\n // Reject downgrade attacks: only allow cleartext when the operator\n // explicitly opts into `transport: 'none'`. Even then, refuse to skip\n // certificate verification on STARTTLS / TLS.\n tls:\n options.transport === 'none'\n ? undefined\n : { rejectUnauthorized: true, ...(pinned.servername ? { servername: pinned.servername } : {}) },\n })\n return { transporter, MailComposer }\n }\n}\n\ninterface NodemailerTransporter {\n verify(): Promise<true>\n sendMail(options: Record<string, unknown>): Promise<unknown>\n close(): void\n}\n\nlet cachedClient: SmtpClient | null = null\n\nexport function getSmtpClient(): SmtpClient {\n if (!cachedClient) cachedClient = new NodemailerClient()\n return cachedClient\n}\n\nexport function setSmtpClient(client: SmtpClient | null): void {\n cachedClient = client\n}\n\nexport function credentialsToSmtpConnection(credentials: ImapCredentials): SmtpConnectionOptions {\n assertTransportAllowed(credentials)\n return {\n host: credentials.smtpHost,\n port: Number(credentials.smtpPort),\n user: credentials.smtpUser,\n pass: credentials.smtpPassword,\n transport: credentials.smtpTls,\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,8BAA8B;AACvC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc;AA4D1C,eAAe,mBAA0D;AACvE,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,8BAA8B;AAGxD,UAAM,OAAO,IAAI,WAAW;AAC5B,WAAO,OAAO,SAAS,aAAa,OAAO;AAAA,EAC7C,SAAS,KAAK;AACZ,WAAO,KAAK,0CAA0C,EAAE,IAAI,CAAC;AAC7D,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBAAkB,MAAsB;AACtD,QAAM,SAAS,qBAAqB,KAAK,IAAI,IAAI,CAAC,KAAK;AACvD,SAAO,IAAI,WAAW,CAAC,IAAI,MAAM;AACnC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AQA,IAAI,eAAkC;AAE/B,SAAS,gBAA4B;AAC1C,MAAI,CAAC,aAAc,gBAAe,IAAI,iBAAiB;AACvD,SAAO;AACT;AAEO,SAAS,cAAc,QAAiC;AAC7D,iBAAe;AACjB;AAEO,SAAS,4BAA4B,aAAqD;AAC/F,yBAAuB,WAAW;AAClC,SAAO;AAAA,IACL,MAAM,YAAY;AAAA,IAClB,MAAM,OAAO,YAAY,QAAQ;AAAA,IACjC,MAAM,YAAY;AAAA,IAClB,MAAM,YAAY;AAAA,IAClB,WAAW,YAAY;AAAA,EACzB;AACF;",
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { ImapCredentials } from './credentials'\nimport { resolveSafeHostAddress } from './host-pinning'\nimport { assertTransportAllowed } from './transport'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('channel_imap')\n\n/**\n * Outbound SMTP client wrapper. Same trade-offs as `imap-client.ts`: we wrap\n * `nodemailer` behind a tiny interface so tests can swap in a mock and the\n * adapter doesn't import SDK types directly.\n */\n\nexport interface SmtpConnectionOptions {\n host: string\n port: number\n user: string\n pass: string\n transport: 'tls' | 'starttls' | 'none'\n timeoutMs?: number\n}\n\nexport interface SmtpMessage {\n from: string\n to: string[]\n cc?: string[]\n bcc?: string[]\n subject?: string\n text?: string\n html?: string\n /** RFC2822 Message-ID; if omitted the client generates one from the sender domain. */\n messageId?: string\n /** RFC2822 In-Reply-To (single value). */\n inReplyTo?: string\n /** RFC2822 References (whitespace-delimited list). */\n references?: string[]\n attachments?: Array<{\n filename: string\n content: Buffer\n contentType?: string\n cid?: string\n inline?: boolean\n }>\n headers?: Record<string, string>\n}\n\nexport interface SmtpSendResult {\n /** Effective Message-ID. */\n messageId: string\n /** Raw RFC2822 message buffer (used for Sent-folder append). */\n raw: Buffer\n /** Provider response string. */\n response?: string\n}\n\nexport interface SmtpClient {\n verify(options: SmtpConnectionOptions): Promise<void>\n send(options: SmtpConnectionOptions, message: SmtpMessage): Promise<SmtpSendResult>\n}\n\ntype MailComposerCtor = new (mail: Record<string, unknown>) => unknown\n\n// nodemailer 10 dropped the root `MailComposer` re-export that v9 exposed; it is\n// still published under the `nodemailer/lib/mail-composer` subpath. Without this\n// fallback the Sent-folder append silently uploads a 0-byte message.\nasync function loadMailComposer(): Promise<MailComposerCtor | undefined> {\n try {\n const mod = (await import('nodemailer/lib/mail-composer')) as unknown as {\n default?: MailComposerCtor\n } & MailComposerCtor\n const ctor = mod.default ?? mod\n return typeof ctor === 'function' ? ctor : undefined\n } catch (err) {\n logger.warn('failed to load nodemailer MailComposer', { err })\n return undefined\n }\n}\n\n/**\n * Whether an SMTP send failed because the message is too large: a local\n * `SIZE` pre-check, or a server answer of 552 / 554 with a size status\n * (RFC 1870 `5.3.4`, `5.2.3`) or wording. A full recipient mailbox (`5.2.2`)\n * is not a message size problem, even when its text mentions a size.\n */\nexport function isSmtpMessageTooLarge(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const { responseCode, response, message } = error as { responseCode?: number; response?: string; message?: string }\n const text = `${response ?? ''} ${message ?? ''}`\n if (/size larger than allowed/i.test(text)) return true\n if (responseCode !== 552 && responseCode !== 554) return false\n if (/\\b5\\.2\\.2\\b/.test(text)) return false\n return /5\\.3\\.4|5\\.2\\.3|too (large|big)|message size|size exceeds/i.test(text)\n}\n\n// send() composes the message twice (MailComposer for the Sent-folder bytes, then\n// transporter.sendMail), and each composition would generate its own Message-ID.\n// Pinning one up front keeps the Sent copy, the delivered message and the\n// returned id identical so replies thread with the Sent copy.\nexport function generateMessageId(from: string): string {\n const domain = /@([^\\s<>@]+)>?\\s*$/.exec(from)?.[1] ?? 'localhost'\n return `<${randomUUID()}@${domain}>`\n}\n\nclass NodemailerClient implements SmtpClient {\n async verify(options: SmtpConnectionOptions): Promise<void> {\n const { transporter } = await this.createTransporter(options)\n try {\n await transporter.verify()\n } finally {\n // Mirror send(): close on every path so a failed verify (wrong password,\n // unreachable host \u2014 the common case) does not leak the socket pool.\n transporter.close()\n }\n }\n\n async send(options: SmtpConnectionOptions, message: SmtpMessage): Promise<SmtpSendResult> {\n const { transporter, MailComposer } = await this.createTransporter(options)\n try {\n const mailOptions: Record<string, unknown> = {\n from: message.from,\n to: message.to,\n cc: message.cc,\n bcc: message.bcc,\n subject: message.subject,\n text: message.text,\n html: message.html,\n messageId: message.messageId ?? generateMessageId(message.from),\n inReplyTo: message.inReplyTo,\n references: message.references,\n attachments: message.attachments?.map((a) => ({\n filename: a.filename,\n content: a.content,\n contentType: a.contentType,\n cid: a.cid,\n contentDisposition: a.inline ? 'inline' : 'attachment',\n })),\n headers: message.headers,\n // Attachments are always bytes; never let a value make nodemailer read\n // the local disk or fetch a URL.\n disableFileAccess: true,\n disableUrlAccess: true,\n }\n\n // Build the RFC2822 bytes ourselves via MailComposer so we can capture\n // them for the Sent-folder append (review H1, 2026-05-26).\n // nodemailer's `transporter.sendMail` info object does NOT contain `raw`\n // unless you configure a streamTransport, so naively reading\n // `info.raw` produces a 0-byte buffer and the Sent-folder append uploads\n // a corrupt message.\n let raw: Buffer = Buffer.alloc(0)\n let composedMessageId = message.messageId\n if (typeof MailComposer === 'function') {\n try {\n const composed = new MailComposer(mailOptions) as unknown as {\n compile: () => {\n build: (callback: (err: Error | null, output: Buffer) => void) => void\n messageId?: () => string | undefined\n }\n }\n const compiled = composed.compile()\n raw = await new Promise<Buffer>((resolve, reject) => {\n compiled.build((err, output) => {\n if (err) reject(err)\n else resolve(output)\n })\n })\n const messageIdFn = compiled.messageId\n if (typeof messageIdFn === 'function') {\n composedMessageId = messageIdFn.call(compiled) ?? composedMessageId\n }\n } catch (composeError) {\n // MailComposer build failed: the send below still delivers the mail, but we\n // cannot capture the RFC2822 bytes, so the caller skips the Sent-folder append.\n // Log so operators can diagnose missing Sent archival.\n raw = Buffer.alloc(0)\n logger.warn('failed to build RFC2822 bytes for Sent-folder append', { err: composeError })\n }\n }\n\n const info = (await transporter.sendMail(mailOptions)) as {\n messageId?: string\n envelope?: { messageId?: string }\n response?: string\n }\n const id = info.messageId ?? composedMessageId ?? info.envelope?.messageId\n if (!id) throw new Error('[internal] SMTP server did not return a Message-ID')\n return { messageId: id, raw, response: info.response }\n } finally {\n transporter.close()\n }\n }\n\n private async createTransporter(\n options: SmtpConnectionOptions,\n ): Promise<{\n transporter: NodemailerTransporter\n MailComposer: (new (mail: Record<string, unknown>) => unknown) | undefined\n }> {\n const mod = (await import('nodemailer')) as unknown as {\n default?: {\n createTransport: (opts: Record<string, unknown>) => NodemailerTransporter\n MailComposer?: new (mail: Record<string, unknown>) => unknown\n }\n createTransport?: (opts: Record<string, unknown>) => NodemailerTransporter\n MailComposer?: new (mail: Record<string, unknown>) => unknown\n }\n const createTransport = mod.createTransport ?? mod.default?.createTransport\n if (typeof createTransport !== 'function') {\n throw new Error('nodemailer.createTransport is unavailable')\n }\n const MailComposer = mod.MailComposer ?? mod.default?.MailComposer ?? await loadMailComposer()\n // Resolve + pin the SMTP host to a validated public IP at connect time\n // (DNS-rebinding-safe), keeping the hostname as the TLS servername for SNI +\n // certificate hostname verification.\n const pinned = await resolveSafeHostAddress(options.host)\n const transporter = createTransport({\n host: pinned.host,\n port: options.port,\n secure: options.transport === 'tls',\n requireTLS: options.transport === 'starttls',\n auth: { user: options.user, pass: options.pass },\n connectionTimeout: options.timeoutMs ?? 10_000,\n // Reject downgrade attacks: only allow cleartext when the operator\n // explicitly opts into `transport: 'none'`. Even then, refuse to skip\n // certificate verification on STARTTLS / TLS.\n tls:\n options.transport === 'none'\n ? undefined\n : { rejectUnauthorized: true, ...(pinned.servername ? { servername: pinned.servername } : {}) },\n })\n return { transporter, MailComposer }\n }\n}\n\ninterface NodemailerTransporter {\n verify(): Promise<true>\n sendMail(options: Record<string, unknown>): Promise<unknown>\n close(): void\n}\n\nlet cachedClient: SmtpClient | null = null\n\nexport function getSmtpClient(): SmtpClient {\n if (!cachedClient) cachedClient = new NodemailerClient()\n return cachedClient\n}\n\nexport function setSmtpClient(client: SmtpClient | null): void {\n cachedClient = client\n}\n\nexport function credentialsToSmtpConnection(credentials: ImapCredentials): SmtpConnectionOptions {\n assertTransportAllowed(credentials)\n return {\n host: credentials.smtpHost,\n port: Number(credentials.smtpPort),\n user: credentials.smtpUser,\n pass: credentials.smtpPassword,\n transport: credentials.smtpTls,\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,8BAA8B;AACvC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc;AA4D1C,eAAe,mBAA0D;AACvE,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,8BAA8B;AAGxD,UAAM,OAAO,IAAI,WAAW;AAC5B,WAAO,OAAO,SAAS,aAAa,OAAO;AAAA,EAC7C,SAAS,KAAK;AACZ,WAAO,KAAK,0CAA0C,EAAE,IAAI,CAAC;AAC7D,WAAO;AAAA,EACT;AACF;AAQO,SAAS,sBAAsB,OAAyB;AAC7D,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,EAAE,cAAc,UAAU,QAAQ,IAAI;AAC5C,QAAM,OAAO,GAAG,YAAY,EAAE,IAAI,WAAW,EAAE;AAC/C,MAAI,4BAA4B,KAAK,IAAI,EAAG,QAAO;AACnD,MAAI,iBAAiB,OAAO,iBAAiB,IAAK,QAAO;AACzD,MAAI,cAAc,KAAK,IAAI,EAAG,QAAO;AACrC,SAAO,6DAA6D,KAAK,IAAI;AAC/E;AAMO,SAAS,kBAAkB,MAAsB;AACtD,QAAM,SAAS,qBAAqB,KAAK,IAAI,IAAI,CAAC,KAAK;AACvD,SAAO,IAAI,WAAW,CAAC,IAAI,MAAM;AACnC;AAEA,MAAM,iBAAuC;AAAA,EAC3C,MAAM,OAAO,SAA+C;AAC1D,UAAM,EAAE,YAAY,IAAI,MAAM,KAAK,kBAAkB,OAAO;AAC5D,QAAI;AACF,YAAM,YAAY,OAAO;AAAA,IAC3B,UAAE;AAGA,kBAAY,MAAM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C7D,iBAAe;AACjB;AAEO,SAAS,4BAA4B,aAAqD;AAC/F,yBAAuB,WAAW;AAClC,SAAO;AAAA,IACL,MAAM,YAAY;AAAA,IAClB,MAAM,OAAO,YAAY,QAAQ;AAAA,IACjC,MAAM,YAAY;AAAA,IAClB,MAAM,YAAY;AAAA,IAClB,WAAW,YAAY;AAAA,EACzB;AACF;",
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.10.1-develop.8259.1.382cb7589a",
3
+ "version": "0.10.1-develop.8271.1.346e524319",
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.10.1-develop.8259.1.382cb7589a",
66
- "@open-mercato/queue": "0.10.1-develop.8259.1.382cb7589a",
67
- "@open-mercato/ui": "0.10.1-develop.8259.1.382cb7589a",
65
+ "@open-mercato/core": "0.10.1-develop.8271.1.346e524319",
66
+ "@open-mercato/queue": "0.10.1-develop.8271.1.346e524319",
67
+ "@open-mercato/ui": "0.10.1-develop.8271.1.346e524319",
68
68
  "@types/mailparser": "^3.4.5",
69
69
  "@types/nodemailer": "^8.0.1",
70
70
  "imapflow": "^1.7.6",
@@ -73,15 +73,15 @@
73
73
  },
74
74
  "peerDependencies": {
75
75
  "@mikro-orm/postgresql": "^7.0.14",
76
- "@open-mercato/ai-assistant": "0.10.1-develop.8259.1.382cb7589a",
77
- "@open-mercato/shared": "0.10.1-develop.8259.1.382cb7589a",
76
+ "@open-mercato/ai-assistant": "0.10.1-develop.8271.1.346e524319",
77
+ "@open-mercato/shared": "0.10.1-develop.8271.1.346e524319",
78
78
  "react": "^19.0.0",
79
79
  "react-dom": "^19.0.0",
80
80
  "react-is": ">=18.0.0"
81
81
  },
82
82
  "devDependencies": {
83
- "@open-mercato/ai-assistant": "0.10.1-develop.8259.1.382cb7589a",
84
- "@open-mercato/shared": "0.10.1-develop.8259.1.382cb7589a",
83
+ "@open-mercato/ai-assistant": "0.10.1-develop.8271.1.346e524319",
84
+ "@open-mercato/shared": "0.10.1-develop.8271.1.346e524319",
85
85
  "@types/jest": "^30.0.0",
86
86
  "@types/react": "^19.2.18",
87
87
  "@types/react-dom": "^19.2.5",
@@ -0,0 +1,135 @@
1
+ import { setImapClient, type ImapClient } from '../imap-client'
2
+ import { isSmtpMessageTooLarge, setSmtpClient, type SmtpClient, type SmtpMessage } from '../smtp-client'
3
+ import { getImapChannelAdapter } from '../adapter'
4
+
5
+ const credentials = {
6
+ imapHost: 'imap.example.com',
7
+ imapPort: 993,
8
+ imapTls: 'tls',
9
+ imapUser: 'alice@example.com',
10
+ imapPassword: 'secret',
11
+ smtpHost: 'smtp.example.com',
12
+ smtpPort: 465,
13
+ smtpTls: 'tls',
14
+ smtpUser: 'alice@example.com',
15
+ smtpPassword: 'secret',
16
+ fromAddress: 'alice@example.com',
17
+ }
18
+
19
+ const metadata = { subject: 'Order 42', to: ['bob@example.com'] }
20
+ const scope = { tenantId: 't', organizationId: 'o' }
21
+
22
+ function installClients(send: SmtpClient['send']) {
23
+ const imap: ImapClient = {
24
+ connectAndValidate: async () => ({ capabilities: [] }),
25
+ selectInbox: async () => ({}),
26
+ fetchUidRange: async () => [],
27
+ appendSent: async () => undefined,
28
+ }
29
+ setSmtpClient({ verify: async () => undefined, send })
30
+ setImapClient(imap)
31
+ }
32
+
33
+ afterEach(() => {
34
+ setImapClient(null)
35
+ setSmtpClient(null)
36
+ })
37
+
38
+ describe('ImapChannelAdapter.sendMessage — attachments', () => {
39
+ it('advertises file sharing', () => {
40
+ expect(getImapChannelAdapter().capabilities.fileSharing).toBe(true)
41
+ })
42
+
43
+ it('hands the attachment bytes to SMTP, from hub bytes or a data: URL', async () => {
44
+ const messages: SmtpMessage[] = []
45
+ installClients(async (_options, message) => {
46
+ messages.push(message)
47
+ return { messageId: '<out@example.com>', raw: Buffer.from('RAW'), response: '250 OK' }
48
+ })
49
+
50
+ const result = await getImapChannelAdapter().sendMessage({
51
+ content: {
52
+ text: 'See attached',
53
+ bodyFormat: 'text',
54
+ attachments: [
55
+ { url: '', fileName: 'order.pdf', mimeType: 'application/pdf', content: Buffer.from('%PDF-1.7') },
56
+ { url: 'data:text/csv;base64,YSxi', fileName: 'lines.csv', mimeType: 'text/csv', inline: false },
57
+ ],
58
+ },
59
+ credentials,
60
+ scope,
61
+ metadata,
62
+ })
63
+
64
+ expect(result.status).toBe('sent')
65
+ expect(messages[0].attachments).toEqual([
66
+ { filename: 'order.pdf', content: Buffer.from('%PDF-1.7'), contentType: 'application/pdf', inline: undefined },
67
+ { filename: 'lines.csv', content: Buffer.from('a,b'), contentType: 'text/csv', inline: false },
68
+ ])
69
+ })
70
+
71
+ it('refuses a remote attachment URL without sending', async () => {
72
+ const send = jest.fn()
73
+ installClients(send)
74
+
75
+ const result = await getImapChannelAdapter().sendMessage({
76
+ content: {
77
+ text: 'See attached',
78
+ bodyFormat: 'text',
79
+ attachments: [{ url: 'https://files.example.net/a.pdf', fileName: 'a.pdf', mimeType: 'application/pdf' }],
80
+ },
81
+ credentials,
82
+ scope,
83
+ metadata,
84
+ })
85
+
86
+ expect(result.status).toBe('failed')
87
+ expect(send).not.toHaveBeenCalled()
88
+ })
89
+
90
+ it('reports a server size rejection as message_too_large', async () => {
91
+ installClients(async () => {
92
+ throw Object.assign(new Error('Message failed: 552 5.3.4 Message size exceeds fixed limit'), {
93
+ code: 'EMESSAGE',
94
+ responseCode: 552,
95
+ response: '552 5.3.4 Message size exceeds fixed limit',
96
+ })
97
+ })
98
+
99
+ const result = await getImapChannelAdapter().sendMessage({
100
+ content: { text: 'big', bodyFormat: 'text' },
101
+ credentials,
102
+ scope,
103
+ metadata,
104
+ })
105
+
106
+ expect(result).toMatchObject({ status: 'failed' })
107
+ expect(result.error).toContain('message_too_large')
108
+ })
109
+
110
+ it('still throws other SMTP failures so the hub classifies them', async () => {
111
+ installClients(async () => {
112
+ throw Object.assign(new Error('Connection timeout'), { code: 'ETIMEDOUT' })
113
+ })
114
+
115
+ await expect(
116
+ getImapChannelAdapter().sendMessage({ content: { text: 'x', bodyFormat: 'text' }, credentials, scope, metadata }),
117
+ ).rejects.toThrow('Connection timeout')
118
+ })
119
+ })
120
+
121
+ describe('isSmtpMessageTooLarge', () => {
122
+ it.each([
123
+ [{ responseCode: 552, response: '552 5.3.4 Message size exceeds fixed limit' }, true],
124
+ [{ responseCode: 554, response: '554 5.2.3 Message too big' }, true],
125
+ [{ code: 'EMESSAGE', message: 'Message size larger than allowed 10485760' }, true],
126
+ [{ responseCode: 552, response: '552 Message size exceeds maximum permitted' }, true],
127
+ [{ responseCode: 552, response: '552 5.2.2 Mailbox full' }, false],
128
+ [{ responseCode: 552, response: '552 5.2.2 Mailbox size limit exceeded' }, false],
129
+ [{ responseCode: 552, response: '552 Requested mail action aborted: mailbox size limit exceeded' }, false],
130
+ [{ responseCode: 550, response: '550 5.1.1 User unknown' }, false],
131
+ [new Error('socket hang up'), false],
132
+ ])('classifies %j as %s', (error, expected) => {
133
+ expect(isSmtpMessageTooLarge(error)).toBe(expected)
134
+ })
135
+ })
@@ -50,6 +50,21 @@ describe('NodemailerClient.send — RFC2822 capture for the Sent-folder append',
50
50
  expect(close).toHaveBeenCalledTimes(1)
51
51
  })
52
52
 
53
+ it('sends attachments as bytes with file and URL access disabled', async () => {
54
+ const result = await getSmtpClient().send(connection, {
55
+ from: 'sender@example.com',
56
+ to: ['recipient@example.com'],
57
+ subject: 'With attachment',
58
+ text: 'body',
59
+ attachments: [{ filename: 'order.pdf', content: Buffer.from('%PDF-1.7'), contentType: 'application/pdf' }],
60
+ })
61
+
62
+ const options = sendMail.mock.calls[0][0] as Record<string, unknown>
63
+ expect(options.disableFileAccess).toBe(true)
64
+ expect(options.disableUrlAccess).toBe(true)
65
+ expect(result.raw.toString('utf8')).toContain('filename=order.pdf')
66
+ })
67
+
53
68
  it('prefers the composed Message-ID when the caller supplies one', async () => {
54
69
  const result = await getSmtpClient().send(connection, {
55
70
  from: 'sender@example.com',
@@ -27,12 +27,20 @@ import {
27
27
  import {
28
28
  credentialsToSmtpConnection,
29
29
  getSmtpClient,
30
+ isSmtpMessageTooLarge,
31
+ type SmtpMessage,
32
+ type SmtpSendResult,
30
33
  } from './smtp-client'
31
34
  import { convertOutboundForEmail } from './convert-outbound'
32
35
  import { normalizeInboundImapMessage } from './normalize-inbound'
33
36
  import { validateImapCredentials } from './validate-credentials'
34
37
  import { emailResolveContact } from '@open-mercato/core/modules/communication_channels/lib/email-contact'
35
- import { decodeCursor, encodeCursor } from '@open-mercato/core/modules/communication_channels/lib/email-mime'
38
+ import {
39
+ decodeCursor,
40
+ encodeCursor,
41
+ sanitizeHeaderValue,
42
+ } from '@open-mercato/core/modules/communication_channels/lib/email-mime'
43
+ import { resolveOutboundAttachmentBytes } from '@open-mercato/core/modules/communication_channels/lib/outbound-attachments'
36
44
  import { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'
37
45
  import { createLogger } from '@open-mercato/shared/lib/logger'
38
46
 
@@ -59,22 +67,6 @@ class ImapChannelAdapter implements ChannelAdapter {
59
67
  async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {
60
68
  const credentials = parseCredentialsOrThrow(input.credentials)
61
69
 
62
- // Reject attachments at the boundary BEFORE building the MIME body. The hub
63
- // passes attachments as URL pointers; until the IMAP/SMTP adapter wires a
64
- // fetcher (with size + content-type validation), inlining them is unsafe —
65
- // a 0-byte attachment looks "delivered" but conveys nothing. Checking here
66
- // (rather than after conversion) avoids wasted MIME-build work and surfaces
67
- // the clearer "attachments unsupported" error even when recipients are also
68
- // missing. Documented in review M2 (2026-05-26) and tracked as a follow-up.
69
- if (Array.isArray(input.content.attachments) && input.content.attachments.length > 0) {
70
- return {
71
- externalMessageId: '',
72
- status: 'failed',
73
- error:
74
- '[internal] IMAP/SMTP adapter does not yet support attachments. Send the message without attachments or use a provider that supports them (Gmail).',
75
- }
76
- }
77
-
78
70
  let native: ChannelNativeContent
79
71
  try {
80
72
  native = await convertOutboundForEmail({
@@ -93,19 +85,47 @@ class ImapChannelAdapter implements ChannelAdapter {
93
85
  return { externalMessageId: '', status: 'failed', error: '[internal] Email send requires at least one recipient' }
94
86
  }
95
87
 
88
+ // Attachments arrive as bytes the hub read from the attachments module (or
89
+ // as `data:` URLs); a remote URL is refused rather than fetched.
90
+ let attachments: SmtpMessage['attachments']
91
+ try {
92
+ attachments = native.content.attachments?.map((attachment) => ({
93
+ filename: sanitizeHeaderValue(attachment.fileName) || 'attachment',
94
+ content: asBuffer(resolveOutboundAttachmentBytes(attachment)),
95
+ contentType: attachment.mimeType,
96
+ inline: attachment.inline,
97
+ }))
98
+ } catch (error) {
99
+ const message = error instanceof Error ? error.message : '[internal] Outbound attachment is not readable'
100
+ return { externalMessageId: '', status: 'failed', error: message }
101
+ }
102
+
96
103
  const smtp = getSmtpClient()
97
- const result = await smtp.send(credentialsToSmtpConnection(credentials), {
98
- from: credentials.fromAddress,
99
- to,
100
- cc: Array.isArray(meta.cc) ? (meta.cc as string[]) : undefined,
101
- bcc: Array.isArray(meta.bcc) ? (meta.bcc as string[]) : undefined,
102
- subject: typeof meta.subject === 'string' ? (meta.subject as string) : undefined,
103
- text: native.content.text,
104
- html: native.content.html,
105
- inReplyTo: typeof meta.inReplyTo === 'string' ? (meta.inReplyTo as string) : undefined,
106
- references: Array.isArray(meta.references) ? (meta.references as string[]) : undefined,
107
- messageId: typeof meta.messageId === 'string' ? (meta.messageId as string) : undefined,
108
- })
104
+ let result: SmtpSendResult
105
+ try {
106
+ result = await smtp.send(credentialsToSmtpConnection(credentials), {
107
+ from: credentials.fromAddress,
108
+ to,
109
+ cc: Array.isArray(meta.cc) ? (meta.cc as string[]) : undefined,
110
+ bcc: Array.isArray(meta.bcc) ? (meta.bcc as string[]) : undefined,
111
+ subject: typeof meta.subject === 'string' ? (meta.subject as string) : undefined,
112
+ text: native.content.text,
113
+ html: native.content.html,
114
+ inReplyTo: typeof meta.inReplyTo === 'string' ? (meta.inReplyTo as string) : undefined,
115
+ references: Array.isArray(meta.references) ? (meta.references as string[]) : undefined,
116
+ messageId: typeof meta.messageId === 'string' ? (meta.messageId as string) : undefined,
117
+ attachments,
118
+ })
119
+ } catch (error) {
120
+ if (isSmtpMessageTooLarge(error)) {
121
+ return {
122
+ externalMessageId: '',
123
+ status: 'failed',
124
+ error: '[internal] The mail server rejected the message as too large (message_too_large)',
125
+ }
126
+ }
127
+ throw error
128
+ }
109
129
 
110
130
  // Best-effort append to Sent — many servers auto-store via "Submission" but not all do.
111
131
  const imap = getImapClient()
@@ -385,6 +405,10 @@ function parseCredentialsOrThrow(value: unknown): ImapCredentials {
385
405
  return parsed.data
386
406
  }
387
407
 
408
+ function asBuffer(bytes: Uint8Array): Buffer {
409
+ return Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
410
+ }
411
+
388
412
  function pickRawMimeBuffer(raw: InboundMessage): Buffer {
389
413
  const candidate = raw.raw as { rawBody?: unknown; mime?: unknown }
390
414
  const value = candidate?.rawBody ?? candidate?.mime ?? raw.raw
@@ -7,10 +7,10 @@ import { baseEmailCapabilities } from '@open-mercato/core/modules/communication_
7
7
  * attachments. No reactions, no edit/delete (only the IMAP `\Seen` flag, which
8
8
  * the user controls locally and is not reliably surfaced).
9
9
  *
10
- * `fileSharing: false` (R2-M4 / F11, 2026-05-26): the adapter's `sendMessage`
11
- * fails-fast on attachments (it doesn't yet fetch + inline attachment URLs into
12
- * MIME bodies). Re-enable when URL-fetch + size-validation lands.
10
+ * `fileSharing: true`: `sendMessage` hands nodemailer the attachment bytes the
11
+ * hub reads from the attachments module; a remote attachment URL is refused.
13
12
  */
14
13
  export const imapCapabilities: ChannelCapabilities = {
15
14
  ...baseEmailCapabilities,
15
+ fileSharing: true,
16
16
  }
@@ -77,6 +77,22 @@ async function loadMailComposer(): Promise<MailComposerCtor | undefined> {
77
77
  }
78
78
  }
79
79
 
80
+ /**
81
+ * Whether an SMTP send failed because the message is too large: a local
82
+ * `SIZE` pre-check, or a server answer of 552 / 554 with a size status
83
+ * (RFC 1870 `5.3.4`, `5.2.3`) or wording. A full recipient mailbox (`5.2.2`)
84
+ * is not a message size problem, even when its text mentions a size.
85
+ */
86
+ export function isSmtpMessageTooLarge(error: unknown): boolean {
87
+ if (!error || typeof error !== 'object') return false
88
+ const { responseCode, response, message } = error as { responseCode?: number; response?: string; message?: string }
89
+ const text = `${response ?? ''} ${message ?? ''}`
90
+ if (/size larger than allowed/i.test(text)) return true
91
+ if (responseCode !== 552 && responseCode !== 554) return false
92
+ if (/\b5\.2\.2\b/.test(text)) return false
93
+ return /5\.3\.4|5\.2\.3|too (large|big)|message size|size exceeds/i.test(text)
94
+ }
95
+
80
96
  // send() composes the message twice (MailComposer for the Sent-folder bytes, then
81
97
  // transporter.sendMail), and each composition would generate its own Message-ID.
82
98
  // Pinning one up front keeps the Sent copy, the delivered message and the
@@ -120,6 +136,10 @@ class NodemailerClient implements SmtpClient {
120
136
  contentDisposition: a.inline ? 'inline' : 'attachment',
121
137
  })),
122
138
  headers: message.headers,
139
+ // Attachments are always bytes; never let a value make nodemailer read
140
+ // the local disk or fetch a URL.
141
+ disableFileAccess: true,
142
+ disableUrlAccess: true,
123
143
  }
124
144
 
125
145
  // Build the RFC2822 bytes ourselves via MailComposer so we can capture