mail-access.test.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. import assert from 'node:assert/strict';
  2. import { mkdtempSync } from 'node:fs';
  3. import net from 'node:net';
  4. import { tmpdir } from 'node:os';
  5. import path from 'node:path';
  6. import { test } from 'node:test';
  7. import {
  8. createDomain,
  9. createInboundFolder,
  10. createInboundMailbox,
  11. createInboundMessage,
  12. createImportedInboundMessage,
  13. createUser,
  14. getInboundMessage,
  15. inboundFolderExists,
  16. initDatabase,
  17. listInboundMessages
  18. } from '../src/db.js';
  19. import { startMailboxAccessServers } from '../src/mail-access.js';
  20. test('IMAP SELECT keeps message bodies lazy and FETCH hydrates one message', async () => {
  21. const database = initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-test-')), 'mail-access-secret');
  22. const { user, mailbox } = createMailboxFixture('imap.example', 'imap-user');
  23. const storedMessage = createInboundMessage(mailbox, {
  24. sender: 'alice@example.net',
  25. recipients: ['admin@imap.example'],
  26. subject: 'IMAP hello',
  27. messageId: '<imap-hello@example.net>',
  28. rawMessage: [
  29. 'From: Alice <alice@example.net>',
  30. 'To: admin@imap.example',
  31. 'Subject: IMAP hello',
  32. 'Message-ID: <imap-hello@example.net>',
  33. '',
  34. 'Hello through IMAP.'
  35. ].join('\r\n'),
  36. textBody: 'Hello through IMAP.'
  37. });
  38. const [server] = startMailboxAccessServers({
  39. hostname: 'mail.imap.example',
  40. imapEnabled: true,
  41. imapListeners: [{ port: 0, protocol: 'imap' }],
  42. pop3Enabled: false,
  43. pop3Listeners: [],
  44. allowInsecureAuth: true
  45. });
  46. await waitForListening(server);
  47. try {
  48. const port = server.address().port;
  49. const client = await connectClient(port);
  50. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  51. assert.match(await client.command('A1 LOGIN "admin@imap.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  52. const selected = await client.command('A2 SELECT INBOX', /A2 OK/);
  53. assert.match(selected, /\* 1 EXISTS/);
  54. database
  55. .prepare('UPDATE inbound_messages SET raw_message_bytes = ? WHERE id = ?')
  56. .run(Buffer.from(storedMessage.rawMessage.replace('Hello through IMAP.', 'Hallo through IMAP.'), 'utf8'), storedMessage.id);
  57. const fetched = await client.command('A3 UID FETCH 1:* (UID FLAGS RFC822.SIZE BODY.PEEK[])', /A3 OK/);
  58. assert.match(fetched, /\* 1 FETCH/);
  59. assert.match(fetched, /UID 1/);
  60. assert.match(fetched, /Subject: IMAP hello/);
  61. assert.match(fetched, /Hallo through IMAP\./);
  62. assert.doesNotMatch(fetched, /Hello through IMAP\./);
  63. await client.command('A4 LOGOUT', /A4 OK/);
  64. client.close();
  65. assert.equal(listInboundMessages(user.id).length, 1);
  66. } finally {
  67. await closeServer(server);
  68. }
  69. });
  70. test('IMAP exposes imported Maildir flags and Dovecot keywords', async () => {
  71. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-flags-test-')), 'mail-access-secret');
  72. const { mailbox } = createMailboxFixture('flags.example', 'flags-user');
  73. createImportedInboundMessage(mailbox, {
  74. importSource: 'vesta:flags',
  75. sourceKey: 'message-1',
  76. sender: 'sender@example.net',
  77. recipients: ['admin@flags.example'],
  78. subject: 'Imported flags',
  79. messageId: '<flags@example.net>',
  80. rawMessageBytes: Buffer.from('From: sender@example.net\r\nTo: admin@flags.example\r\nSubject: Imported flags\r\n\r\nBody', 'utf8'),
  81. flags: ['\\Answered', '\\Flagged', '\\Draft', '\\Seen'],
  82. keywords: ['$Label1', 'custom-keyword'],
  83. receivedAt: '2024-01-02T03:04:05.000Z'
  84. });
  85. const [server] = startMailboxAccessServers({
  86. hostname: 'mail.flags.example',
  87. imapEnabled: true,
  88. imapListeners: [{ port: 0, protocol: 'imap' }],
  89. pop3Enabled: false,
  90. pop3Listeners: [],
  91. allowInsecureAuth: true
  92. });
  93. await waitForListening(server);
  94. let client;
  95. try {
  96. client = await connectClient(server.address().port);
  97. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  98. await client.command('A1 LOGIN "admin@flags.example" "mailbox-pass-123"', /A1 OK/);
  99. const selected = await client.command('A2 SELECT INBOX', /A2 OK/);
  100. assert.match(selected, /\* FLAGS \([^\r\n]*\\Answered/);
  101. assert.match(selected, /\* FLAGS \([^\r\n]*\$Label1/);
  102. assert.match(selected, /\* FLAGS \([^\r\n]*custom-keyword/);
  103. const fetched = await client.command('A3 UID FETCH 1:* (UID FLAGS)', /A3 OK/);
  104. for (const flag of ['\\Answered', '\\Flagged', '\\Draft', '\\Seen', '$Label1', 'custom-keyword']) {
  105. assert.ok(fetched.includes(flag));
  106. }
  107. await client.command('A4 LOGOUT', /A4 OK/);
  108. } finally {
  109. client?.close();
  110. await closeServer(server);
  111. }
  112. });
  113. test('IMAP SEARCH filters seen state and rejects invalid contexts or criteria', async () => {
  114. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-search-test-')), 'mail-access-secret');
  115. const { mailbox: offsetMailbox } = createMailboxFixture('search-offset.example', 'search-offset-user');
  116. createInboundMessage(offsetMailbox, {
  117. sender: 'offset@example.net',
  118. recipients: ['admin@search-offset.example'],
  119. subject: 'UID offset',
  120. messageId: '<offset@search-offset.example>',
  121. rawMessage: 'From: offset@example.net\r\nTo: admin@search-offset.example\r\nSubject: UID offset\r\n\r\nOffset body.',
  122. textBody: 'Offset body.'
  123. });
  124. const { mailbox } = createMailboxFixture('search.example', 'search-user');
  125. const { message: seenMessage } = createImportedInboundMessage(mailbox, {
  126. importSource: 'imap-search-test',
  127. sourceKey: 'seen-message',
  128. sender: 'seen@example.net',
  129. recipients: ['admin@search.example'],
  130. subject: 'Already seen',
  131. messageId: '<seen@search.example>',
  132. rawMessageBytes: Buffer.from('From: seen@example.net\r\nTo: admin@search.example\r\nSubject: Already seen\r\n\r\nSeen body.', 'utf8'),
  133. flags: ['\\Seen'],
  134. receivedAt: '2026-07-15T01:00:00.000Z'
  135. });
  136. const unseenMessage = createInboundMessage(mailbox, {
  137. sender: 'unseen@example.net',
  138. recipients: ['admin@search.example'],
  139. subject: 'Still unread',
  140. messageId: '<unseen@search.example>',
  141. rawMessage: 'From: unseen@example.net\r\nTo: admin@search.example\r\nSubject: Still unread\r\n\r\nUnread body.',
  142. textBody: 'Unread body.'
  143. });
  144. const [server] = startMailboxAccessServers({
  145. hostname: 'mail.search.example',
  146. imapEnabled: true,
  147. imapListeners: [{ port: 0, protocol: 'imap' }],
  148. pop3Enabled: false,
  149. pop3Listeners: [],
  150. allowInsecureAuth: true
  151. });
  152. await waitForListening(server);
  153. let client;
  154. try {
  155. client = await connectClient(server.address().port);
  156. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  157. await client.command('A1 LOGIN "admin@search.example" "mailbox-pass-123"', /A1 OK/);
  158. const searchBeforeSelect = await client.command('A2 SEARCH ALL', /A2 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  159. const uidSearchBeforeSelect = await client.command('A3 UID SEARCH ALL', /A3 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  160. await client.command('A4 SELECT INBOX', /A4 OK/);
  161. const all = await client.command('A5 SEARCH ALL', /A5 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  162. const unseen = await client.command('A6 SEARCH UNSEEN', /A6 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  163. const seen = await client.command('A7 SEARCH SEEN', /A7 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  164. const allUnseen = await client.command('A8 SEARCH ALL UNSEEN', /A8 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  165. const uidUnseen = await client.command('A9 UID SEARCH UNSEEN', /A9 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  166. const uidCharsetUnseen = await client.command('A10 UID SEARCH CHARSET UTF-8 UNSEEN', /A10 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  167. const sequenceNumber = await client.command('A10A SEARCH 2', /A10A (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  168. const sequenceRangeUnseen = await client.command('A10B SEARCH 1:* UNSEEN', /A10B (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  169. const uidSequenceNumber = await client.command('A10C UID SEARCH 2', /A10C (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  170. const uidSequenceOutOfRange = await client.command('A10D UID SEARCH 16', /A10D (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  171. const uidRangeUnseen = await client.command('A10E UID SEARCH 1:2 UNSEEN', /A10E (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  172. const uidList = await client.command('A10F UID SEARCH 1,2', /A10F (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  173. const uidCriterion = await client.command(`A10G UID SEARCH UID ${unseenMessage.id}`, /A10G (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  174. const sequenceUidCriterion = await client.command(`A10H SEARCH UID ${unseenMessage.id}`, /A10H (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  175. const stored = await client.command(
  176. `A11 UID STORE ${unseenMessage.id} +FLAGS.SILENT (\\Seen)`,
  177. /A11 (?:OK|NO|BAD)[^\r\n]*\r\n$/
  178. );
  179. const unseenAfterStore = await client.command('A12 SEARCH UNSEEN', /A12 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  180. const seenAfterStore = await client.command('A13 SEARCH SEEN', /A13 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  181. const returnCriteria = await client.command('A14 SEARCH RETURN (ALL) ALL', /A14 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  182. const unknownCriteria = await client.command('A15 SEARCH FROBNICATE', /A15 (?:OK|NO|BAD)[^\r\n]*\r\n$/);
  183. await client.command('A16 LOGOUT', /A16 OK/);
  184. assert.match(searchBeforeSelect, /^A2 (?:NO|BAD) /m);
  185. assert.doesNotMatch(searchBeforeSelect, /^\* SEARCH/m);
  186. assert.match(uidSearchBeforeSelect, /^A3 (?:NO|BAD) /m);
  187. assert.doesNotMatch(uidSearchBeforeSelect, /^\* SEARCH/m);
  188. assertImapSearchResult(all, [1, 2]);
  189. assertImapSearchResult(unseen, [2]);
  190. assertImapSearchResult(seen, [1]);
  191. assertImapSearchResult(allUnseen, [2]);
  192. assertImapSearchResult(uidUnseen, [unseenMessage.id]);
  193. assertImapSearchResult(uidCharsetUnseen, [unseenMessage.id]);
  194. assertImapSearchResult(sequenceNumber, [2]);
  195. assertImapSearchResult(sequenceRangeUnseen, [2]);
  196. assertImapSearchResult(uidSequenceNumber, [unseenMessage.id]);
  197. assertImapSearchResult(uidSequenceOutOfRange, []);
  198. assertImapSearchResult(uidRangeUnseen, [unseenMessage.id]);
  199. assertImapSearchResult(uidList, [seenMessage.id, unseenMessage.id]);
  200. assertImapSearchResult(uidCriterion, [unseenMessage.id]);
  201. assertImapSearchResult(sequenceUidCriterion, [2]);
  202. assert.match(stored, /^A11 OK STORE completed\r?$/m);
  203. assert.doesNotMatch(stored, /^\* \d+ FETCH/m);
  204. assertImapSearchResult(unseenAfterStore, []);
  205. assertImapSearchResult(seenAfterStore, [1, 2]);
  206. assert.match(returnCriteria, /^A14 BAD /m);
  207. assert.doesNotMatch(returnCriteria, /^\* SEARCH/m);
  208. assert.match(unknownCriteria, /^A15 BAD /m);
  209. assert.doesNotMatch(unknownCriteria, /^\* SEARCH/m);
  210. } finally {
  211. client?.close();
  212. await closeServer(server);
  213. }
  214. });
  215. test('IMAP exposes MIME body structures and individual parts for Roundcube', async () => {
  216. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-mime-test-')), 'mail-access-secret');
  217. const { mailbox } = createMailboxFixture('mime.example', 'mime-user');
  218. createInboundMessage(mailbox, {
  219. sender: 'alice@example.net',
  220. recipients: ['admin@mime.example'],
  221. subject: 'MIME message',
  222. messageId: '<mime-message@example.net>',
  223. rawMessage: [
  224. 'From: Alice <alice@example.net>',
  225. 'To: admin@mime.example',
  226. 'Subject: MIME message',
  227. 'MIME-Version: 1.0',
  228. 'Content-Type: multipart/alternative; boundary="mailhub-boundary"',
  229. '',
  230. '--mailhub-boundary',
  231. 'Content-Type: text/plain; charset=UTF-8',
  232. 'Content-Transfer-Encoding: quoted-printable',
  233. '',
  234. 'Plain message body.',
  235. '--mailhub-boundary',
  236. 'Content-Type: text/html; charset=UTF-8',
  237. '',
  238. '<p>HTML message body.</p>',
  239. '--mailhub-boundary--',
  240. ''
  241. ].join('\r\n'),
  242. textBody: 'Plain message body.',
  243. htmlBody: '<p>HTML message body.</p>'
  244. });
  245. const [server] = startMailboxAccessServers({
  246. hostname: 'mail.mime.example',
  247. imapEnabled: true,
  248. imapListeners: [{ port: 0, protocol: 'imap' }],
  249. pop3Enabled: false,
  250. pop3Listeners: [],
  251. allowInsecureAuth: true
  252. });
  253. await waitForListening(server);
  254. let client;
  255. try {
  256. client = await connectClient(server.address().port);
  257. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  258. assert.match(await client.command('A1 LOGIN "admin@mime.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  259. await client.command('A2 SELECT INBOX', /A2 OK/);
  260. const structure = await client.command('A3 UID FETCH 1 (UID BODYSTRUCTURE)', /A3 OK/);
  261. assert.match(structure, /BODYSTRUCTURE \(\("TEXT" "PLAIN" \("CHARSET" "UTF-8"\).*\) \("TEXT" "HTML" \("CHARSET" "UTF-8"\).*\) "ALTERNATIVE" \("BOUNDARY" "mailhub-boundary"\)\)/);
  262. const textPart = await client.command('A4 UID FETCH 1 (BODY.PEEK[1])', /A4 OK/);
  263. assert.match(textPart, /BODY\[1\] \{\d+\}\r\nPlain message body\./);
  264. assert.doesNotMatch(textPart, /Content-Type: text\/plain/);
  265. const htmlPart = await client.command('A5 UID FETCH 1 (BODY.PEEK[2])', /A5 OK/);
  266. assert.match(htmlPart, /BODY\[2\] \{\d+\}\r\n<p>HTML message body\.<\/p>/);
  267. const mimeHeaders = await client.command('A6 UID FETCH 1 (BODY.PEEK[1.MIME])', /A6 OK/);
  268. assert.match(mimeHeaders, /BODY\[1\.MIME\] \{\d+\}\r\nContent-Type: text\/plain; charset=UTF-8/);
  269. await client.command('A7 LOGOUT', /A7 OK/);
  270. client.close();
  271. } finally {
  272. client?.close();
  273. await closeServer(server);
  274. }
  275. });
  276. test('IMAP exposes LF-only Maildir headers and text sections to Roundcube', async () => {
  277. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-lf-test-')), 'mail-access-secret');
  278. const { mailbox } = createMailboxFixture('lf.example', 'lf-user');
  279. const rawMessageBytes = Buffer.from([
  280. 'From: Alice <alice@example.net>',
  281. 'To: admin@lf.example',
  282. 'Subject: LF-only imported',
  283. ' continuation',
  284. 'Message-ID: <lf-only@example.net>',
  285. 'Content-Type: text/plain; charset=UTF-8',
  286. 'X-Not-Selected: private metadata',
  287. '',
  288. 'LF-only body.',
  289. 'Second line.'
  290. ].join('\n'), 'utf8');
  291. createImportedInboundMessage(mailbox, {
  292. importSource: 'vesta:lf-only',
  293. sourceKey: 'lf-only-message',
  294. sender: 'alice@example.net',
  295. recipients: ['admin@lf.example'],
  296. subject: 'LF-only imported continuation',
  297. messageId: '<lf-only@example.net>',
  298. rawMessageBytes,
  299. receivedAt: '2026-07-14T06:19:40.000Z'
  300. });
  301. const [server] = startMailboxAccessServers({
  302. hostname: 'mail.lf.example',
  303. imapEnabled: true,
  304. imapListeners: [{ port: 0, protocol: 'imap' }],
  305. pop3Enabled: false,
  306. pop3Listeners: [],
  307. allowInsecureAuth: true
  308. });
  309. await waitForListening(server);
  310. let client;
  311. try {
  312. client = await connectClient(server.address().port);
  313. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  314. await client.command('A1 LOGIN "admin@lf.example" "mailbox-pass-123"', /A1 OK/);
  315. await client.command('A2 SELECT INBOX', /A2 OK/);
  316. const headerFieldsLabel = 'BODY[HEADER.FIELDS (DATE FROM TO CC REPLY-TO SUBJECT MESSAGE-ID REFERENCES CONTENT-TYPE X-PRIORITY X-MSMMAIL-PRIORITY IMPORTANCE)]';
  317. const headerFieldsResponse = await client.commandBytes(
  318. `A3 UID FETCH 1 (UID FLAGS RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE FROM TO CC REPLY-TO SUBJECT MESSAGE-ID REFERENCES CONTENT-TYPE X-PRIORITY X-MSMMAIL-PRIORITY IMPORTANCE)])`,
  319. /A3 OK FETCH completed\r\n$/
  320. );
  321. assert.deepEqual(extractFetchLiteral(headerFieldsResponse, headerFieldsLabel), Buffer.from([
  322. 'From: Alice <alice@example.net>',
  323. 'To: admin@lf.example',
  324. 'Subject: LF-only imported',
  325. ' continuation',
  326. 'Message-ID: <lf-only@example.net>',
  327. 'Content-Type: text/plain; charset=UTF-8',
  328. '',
  329. ''
  330. ].join('\r\n'), 'utf8'));
  331. const fullHeaderResponse = await client.commandBytes(
  332. 'A4 UID FETCH 1 (RFC822.HEADER)',
  333. /A4 OK FETCH completed\r\n$/
  334. );
  335. assert.deepEqual(extractFetchLiteral(fullHeaderResponse, 'RFC822.HEADER'), Buffer.from([
  336. 'From: Alice <alice@example.net>',
  337. 'To: admin@lf.example',
  338. 'Subject: LF-only imported',
  339. ' continuation',
  340. 'Message-ID: <lf-only@example.net>',
  341. 'Content-Type: text/plain; charset=UTF-8',
  342. 'X-Not-Selected: private metadata',
  343. '',
  344. ''
  345. ].join('\r\n'), 'utf8'));
  346. const expectedBody = Buffer.from('LF-only body.\nSecond line.', 'utf8');
  347. const rfc822TextResponse = await client.commandBytes(
  348. 'A5 UID FETCH 1 (RFC822.TEXT)',
  349. /A5 OK FETCH completed\r\n$/
  350. );
  351. assert.deepEqual(extractFetchLiteral(rfc822TextResponse, 'RFC822.TEXT'), expectedBody);
  352. const bodyTextResponse = await client.commandBytes(
  353. 'A6 UID FETCH 1 (BODY.PEEK[TEXT])',
  354. /A6 OK FETCH completed\r\n$/
  355. );
  356. assert.deepEqual(extractFetchLiteral(bodyTextResponse, 'BODY[TEXT]'), expectedBody);
  357. const fullMessageResponse = await client.commandBytes(
  358. 'A7 UID FETCH 1 (BODY.PEEK[])',
  359. /A7 OK FETCH completed\r\n$/
  360. );
  361. assert.deepEqual(extractFetchLiteral(fullMessageResponse, 'BODY[]'), rawMessageBytes);
  362. await client.command('A8 LOGOUT', /A8 OK/);
  363. } finally {
  364. client?.close();
  365. await closeServer(server);
  366. }
  367. });
  368. test('IMAP exposes standard folders expected by mainstream clients', async () => {
  369. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-folders-test-')), 'mail-access-secret');
  370. createMailboxFixture('folders.example', 'folders-user');
  371. const [server] = startMailboxAccessServers({
  372. hostname: 'mail.folders.example',
  373. imapEnabled: true,
  374. imapListeners: [{ port: 0, protocol: 'imap' }],
  375. pop3Enabled: false,
  376. pop3Listeners: [],
  377. allowInsecureAuth: true
  378. });
  379. await waitForListening(server);
  380. let client;
  381. try {
  382. client = await connectClient(server.address().port);
  383. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  384. assert.match(await client.command('A1 LOGIN "admin@folders.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  385. const listed = await client.command('A2 LIST "" "*"', /A2 OK/);
  386. assert.match(listed, /\* LIST .* "INBOX"/);
  387. assert.match(listed, /\* LIST .*\\Sent.* "Sent"/);
  388. assert.match(listed, /\* LIST .*\\Drafts.* "Drafts"/);
  389. assert.match(listed, /\* LIST .*\\Trash.* "Trash"/);
  390. assert.match(listed, /\* LIST .*\\Junk.* "Junk"/);
  391. assert.match(listed, /\* LIST .*\\Archive.* "Archive"/);
  392. const selected = await client.command('A3 SELECT Sent', /A3 OK/);
  393. assert.match(selected, /\* 0 EXISTS/);
  394. await client.command('A4 LOGOUT', /A4 OK/);
  395. client.close();
  396. } finally {
  397. client?.close();
  398. await closeServer(server);
  399. }
  400. });
  401. test('IMAP uses Modified UTF-7 on the wire while storing Unicode folder names', async () => {
  402. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-utf7-test-')), 'mail-access-secret');
  403. const { user, mailbox } = createMailboxFixture('utf7.example', 'utf7-user');
  404. createInboundFolder(mailbox, '中文 & 项目');
  405. const [server] = startMailboxAccessServers({
  406. hostname: 'mail.utf7.example',
  407. imapEnabled: true,
  408. imapListeners: [{ port: 0, protocol: 'imap' }],
  409. pop3Enabled: false,
  410. pop3Listeners: [],
  411. allowInsecureAuth: true
  412. });
  413. await waitForListening(server);
  414. let client;
  415. try {
  416. client = await connectClient(server.address().port);
  417. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  418. await client.command('A1 LOGIN "admin@utf7.example" "mailbox-pass-123"', /A1 OK/);
  419. const listed = await client.command('A2 LIST "" "*"', /A2 OK/);
  420. assert.match(listed, /"&Ti1lhw- &- &mHl27g-"/);
  421. assert.doesNotMatch(listed, /中文|项目/);
  422. const subscribed = await client.command('A2L LSUB "" "*"', /A2L OK/);
  423. assert.match(subscribed, /"&Ti1lhw- &- &mHl27g-"/);
  424. const selected = await client.command('A3 SELECT "&Ti1lhw- &- &mHl27g-"', /A3 OK/);
  425. assert.match(selected, /\* 0 EXISTS/);
  426. const status = await client.command('A4 STATUS "&Ti1lhw- &- &mHl27g-" \(MESSAGES UNSEEN\)', /A4 OK/);
  427. assert.match(status, /\* STATUS "&Ti1lhw- &- &mHl27g-" \(MESSAGES 0 UNSEEN 0/);
  428. await client.command('A5 CREATE "&ZeVnLIqe-"', /A5 OK/);
  429. assert.equal(inboundFolderExists(mailbox, '日本語'), true);
  430. const rawMessage = [
  431. 'From: Bob <bob@example.net>',
  432. 'To: admin@utf7.example',
  433. 'Subject: UTF-7 folder append',
  434. '',
  435. 'Imported into a Unicode folder.'
  436. ].join('\r\n');
  437. await client.append(
  438. `A6 APPEND "&ZeVnLIqe-" {${Buffer.byteLength(rawMessage, 'utf8')}}`,
  439. rawMessage,
  440. /A6 OK/
  441. );
  442. assert.equal(listInboundMessages(user.id, { folder: '日本語' }).length, 1);
  443. await client.command('A7 LOGOUT', /A7 OK/);
  444. client.close();
  445. } finally {
  446. client?.close();
  447. await closeServer(server);
  448. }
  449. });
  450. test('IMAP APPEND stores sent messages in the Sent folder', async () => {
  451. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-append-test-')), 'mail-access-secret');
  452. const { user } = createMailboxFixture('append.example', 'append-user');
  453. const [server] = startMailboxAccessServers({
  454. hostname: 'mail.append.example',
  455. imapEnabled: true,
  456. imapListeners: [{ port: 0, protocol: 'imap' }],
  457. pop3Enabled: false,
  458. pop3Listeners: [],
  459. allowInsecureAuth: true
  460. });
  461. await waitForListening(server);
  462. let client;
  463. try {
  464. const sentMessage = [
  465. 'From: Admin <admin@append.example>',
  466. 'To: Bob <bob@example.net>',
  467. 'Subject: =?UTF-8?Q?=E6=A0=B8=E4=BA=91?=',
  468. ' =?UTF-8?Q?=E8=AE=A1=E7=AE=97?=',
  469. 'Message-ID: <sent-copy@append.example>',
  470. 'MIME-Version: 1.0',
  471. 'Content-Type: multipart/alternative; boundary="sent-boundary"',
  472. '',
  473. '--sent-boundary',
  474. 'Content-Type: text/plain; charset=UTF-8',
  475. 'Content-Transfer-Encoding: base64',
  476. '',
  477. Buffer.from('工单正文', 'utf8').toString('base64'),
  478. '--sent-boundary',
  479. 'Content-Type: text/html; charset=UTF-8',
  480. 'Content-Transfer-Encoding: quoted-printable',
  481. '',
  482. '<p>Sent HTML body.</p>',
  483. '--sent-boundary--',
  484. ''
  485. ].join('\r\n');
  486. client = await connectClient(server.address().port);
  487. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  488. assert.match(await client.command('A1 LOGIN "admin@append.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  489. await client.append(`A2 APPEND Sent (\\Seen) {${Buffer.byteLength(sentMessage, 'utf8')}}`, sentMessage, /A2 OK/);
  490. const selectedSent = await client.command('A3 SELECT Sent', /A3 OK/);
  491. assert.match(selectedSent, /\* 1 EXISTS/);
  492. const fetchedSent = await client.command('A4 UID FETCH 1:* (UID FLAGS BODY.PEEK[])', /A4 OK/);
  493. assert.match(fetchedSent, /FLAGS \(\\Seen\)/);
  494. assert.match(fetchedSent, /Subject: =\?UTF-8\?Q\?/);
  495. assert.match(fetchedSent, /--sent-boundary/);
  496. const [storedSummary] = listInboundMessages(user.id, { folder: 'Sent' });
  497. const storedMessage = getInboundMessage(user.id, storedSummary.id);
  498. assert.equal(storedMessage.subject, '核云计算');
  499. assert.equal(storedMessage.textBody, '工单正文');
  500. assert.match(storedMessage.htmlBody, /Sent HTML body/);
  501. assert.equal(storedMessage.preview, '工单正文');
  502. assert.match(storedMessage.rawMessage, /--sent-boundary/);
  503. const latin1Message = Buffer.concat([
  504. Buffer.from([
  505. 'From: Admin <admin@append.example>',
  506. 'To: Bob <bob@example.net>',
  507. 'Subject: Latin1 copy',
  508. 'Content-Type: text/plain; charset=ISO-8859-1',
  509. 'Content-Transfer-Encoding: 8bit',
  510. '',
  511. 'caf'
  512. ].join('\r\n'), 'ascii'),
  513. Buffer.from([0xe9])
  514. ]);
  515. await client.append(`A5 APPEND Sent {${latin1Message.length}}`, latin1Message, /A5 OK/);
  516. const latin1Summary = listInboundMessages(user.id, { folder: 'Sent' })
  517. .find((message) => message.subject === 'Latin1 copy');
  518. assert.equal(getInboundMessage(user.id, latin1Summary.id).textBody, 'café');
  519. await client.command('A6 SELECT Sent', /A6 OK/);
  520. const latin1Fetch = await client.commandBytes('A7 UID FETCH 1:* (UID BODY.PEEK[])', /A7 OK/);
  521. assert.equal(latin1Fetch.includes(latin1Message), true);
  522. const selectedInbox = await client.command('A8 SELECT INBOX', /A8 OK/);
  523. assert.match(selectedInbox, /\* 0 EXISTS/);
  524. await client.command('A9 LOGOUT', /A9 OK/);
  525. client.close();
  526. } finally {
  527. client?.close();
  528. await closeServer(server);
  529. }
  530. });
  531. test('POP3 clients can retrieve and delete messages on quit', async () => {
  532. const database = initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-pop3-test-')), 'mail-access-secret');
  533. const { user, mailbox } = createMailboxFixture('pop3.example', 'pop3-user');
  534. const firstRawMessage = [
  535. 'From: Bob <bob@example.net>',
  536. 'To: admin@pop3.example',
  537. 'Subject: POP3 hello',
  538. 'Message-ID: <pop3-hello@example.net>',
  539. '',
  540. 'Hello through POP3.'
  541. ].join('\r\n');
  542. const firstMessage = createInboundMessage(mailbox, {
  543. sender: 'bob@example.net',
  544. recipients: ['admin@pop3.example'],
  545. subject: 'POP3 hello',
  546. messageId: '<pop3-hello@example.net>',
  547. rawMessage: firstRawMessage,
  548. textBody: 'Hello through POP3.'
  549. });
  550. const latin1RawMessage = Buffer.concat([
  551. Buffer.from([
  552. 'From: Alice <alice@example.net>',
  553. 'To: admin@pop3.example',
  554. 'Subject: Latin1 POP3',
  555. 'Content-Type: text/plain; charset=ISO-8859-1',
  556. 'Content-Transfer-Encoding: 8bit',
  557. '',
  558. 'caf'
  559. ].join('\n'), 'ascii'),
  560. Buffer.from([0xe9])
  561. ]);
  562. createInboundMessage(mailbox, {
  563. sender: 'alice@example.net',
  564. recipients: ['admin@pop3.example'],
  565. subject: 'Latin1 POP3',
  566. rawMessage: latin1RawMessage.toString('latin1'),
  567. rawMessageBytes: latin1RawMessage,
  568. textBody: 'café'
  569. });
  570. const firstPop3Message = Buffer.from(`${firstRawMessage}\r\n`, 'utf8');
  571. const latin1Pop3Message = Buffer.concat([
  572. Buffer.from(latin1RawMessage.toString('latin1').replace(/\n/g, '\r\n'), 'latin1'),
  573. Buffer.from('\r\n')
  574. ]);
  575. const totalOctets = firstPop3Message.length + latin1Pop3Message.length;
  576. const [server] = startMailboxAccessServers({
  577. hostname: 'mail.pop3.example',
  578. imapEnabled: false,
  579. imapListeners: [],
  580. pop3Enabled: true,
  581. pop3Listeners: [{ port: 0, protocol: 'pop3' }],
  582. allowInsecureAuth: true
  583. });
  584. await waitForListening(server);
  585. try {
  586. const client = await connectClient(server.address().port);
  587. await client.readUntil(/\+OK .* POP3 ready\r\n/);
  588. assert.match(await client.command('USER admin@pop3.example', /\+OK/), /User accepted/);
  589. assert.match(await client.command('PASS mailbox-pass-123', /\+OK/), /ready/);
  590. assert.match(await client.command('STAT', /\+OK \d+ \d+/), new RegExp(`\\+OK 2 ${totalOctets}`));
  591. const listed = await client.command('LIST', /\r\n\.\r\n/);
  592. assert.match(listed, new RegExp(`1 ${firstPop3Message.length}\\r\\n`));
  593. assert.match(listed, new RegExp(`2 ${latin1Pop3Message.length}\\r\\n`));
  594. assert.match(await client.command('UIDL 1', /\+OK 1 mh-1/), /\+OK 1 mh-1/);
  595. database
  596. .prepare('UPDATE inbound_messages SET raw_message_bytes = ? WHERE id = ?')
  597. .run(Buffer.from(firstRawMessage.replace('Hello through POP3.', 'Hallo through POP3.'), 'utf8'), firstMessage.id);
  598. const retrieved = await client.command('RETR 1', /\r\n\.\r\n/);
  599. assert.match(retrieved, /Subject: POP3 hello/);
  600. assert.match(retrieved, /Hallo through POP3\./);
  601. assert.doesNotMatch(retrieved, /Hello through POP3\./);
  602. const latin1Retrieved = await client.commandBytes('RETR 2', /\r\n\.\r\n/);
  603. assert.deepEqual(latin1Retrieved, Buffer.concat([
  604. Buffer.from(`+OK ${latin1Pop3Message.length} octets\r\n`),
  605. latin1Pop3Message,
  606. Buffer.from('.\r\n')
  607. ]));
  608. assert.match(await client.command('DELE 1', /\+OK/), /deleted/);
  609. assert.match(await client.command('DELE 2', /\+OK/), /deleted/);
  610. await client.command('QUIT', /\+OK Bye/);
  611. client.close();
  612. assert.equal(listInboundMessages(user.id).length, 0);
  613. } finally {
  614. await closeServer(server);
  615. }
  616. });
  617. test('POP3 AUTH PLAIN requires TLS when insecure authentication is disabled', async () => {
  618. const [server] = startMailboxAccessServers({
  619. hostname: 'mail.secure-pop3.example',
  620. imapEnabled: false,
  621. imapListeners: [],
  622. pop3Enabled: true,
  623. pop3Listeners: [{ port: 0, protocol: 'pop3' }],
  624. allowInsecureAuth: false
  625. });
  626. await waitForListening(server);
  627. let client;
  628. try {
  629. client = await connectClient(server.address().port);
  630. await client.readUntil(/\+OK .* POP3 ready\r\n/);
  631. const credentials = Buffer.from('\u0000user@example.com\u0000password').toString('base64');
  632. assert.equal(
  633. await client.command(`AUTH PLAIN ${credentials}`, /\+OK|\-ERR/),
  634. '-ERR Encryption required for authentication\r\n'
  635. );
  636. } finally {
  637. client?.close();
  638. await closeServer(server);
  639. }
  640. });
  641. function createMailboxFixture(domainName, username) {
  642. const user = createUser({ username, email: `${username}@example.com`, password: 'password123' });
  643. createDomain(user.id, {
  644. domain: domainName,
  645. selector: 'mh',
  646. verificationToken: 'verify',
  647. dkimPublic: 'public',
  648. dkimPrivate: 'private',
  649. senderHost: `mail.${domainName}`,
  650. sendingIp: '192.0.2.30',
  651. spfExtra: '',
  652. dmarcPolicy: 'none',
  653. dmarcRua: ''
  654. });
  655. const mailbox = createInboundMailbox(user.id, {
  656. address: `admin@${domainName}`,
  657. password: 'mailbox-pass-123'
  658. });
  659. return { user, mailbox };
  660. }
  661. function connectClient(port) {
  662. return new Promise((resolve, reject) => {
  663. const socket = net.createConnection({ host: '127.0.0.1', port });
  664. socket.setTimeout(5000);
  665. let buffer = '';
  666. let rawBuffer = Buffer.alloc(0);
  667. const waiters = [];
  668. socket.on('data', (chunk) => {
  669. const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
  670. rawBuffer = Buffer.concat([rawBuffer, bytes]);
  671. buffer += bytes.toString('utf8');
  672. for (const waiter of [...waiters]) {
  673. if (waiter.pattern.test(buffer)) {
  674. waiters.splice(waiters.indexOf(waiter), 1);
  675. const output = buffer;
  676. const rawOutput = rawBuffer;
  677. buffer = '';
  678. rawBuffer = Buffer.alloc(0);
  679. waiter.resolve(waiter.raw ? rawOutput : output);
  680. }
  681. }
  682. });
  683. socket.once('connect', () => resolve({
  684. command(command, pattern) {
  685. socket.write(`${command}\r\n`);
  686. return this.readUntil(pattern);
  687. },
  688. commandBytes(command, pattern) {
  689. socket.write(`${command}\r\n`);
  690. return this.readUntil(pattern, true);
  691. },
  692. async append(command, literal, pattern) {
  693. socket.write(`${command}\r\n`);
  694. await this.readUntil(/^\+ /m);
  695. socket.write(literal);
  696. socket.write('\r\n');
  697. return this.readUntil(pattern);
  698. },
  699. readUntil(pattern, raw = false) {
  700. if (pattern.test(buffer)) {
  701. const output = buffer;
  702. const rawOutput = rawBuffer;
  703. buffer = '';
  704. rawBuffer = Buffer.alloc(0);
  705. return Promise.resolve(raw ? rawOutput : output);
  706. }
  707. return new Promise((waitResolve, waitReject) => {
  708. const waiter = {
  709. pattern,
  710. raw,
  711. resolve(output) {
  712. clearTimeout(waiter.timer);
  713. waitResolve(output);
  714. },
  715. reject(error) {
  716. clearTimeout(waiter.timer);
  717. waitReject(error);
  718. },
  719. timer: null
  720. };
  721. waiter.timer = setTimeout(() => {
  722. waiters.splice(waiters.indexOf(waiter), 1);
  723. waitReject(new Error(`Timed out waiting for ${pattern}; buffered response: ${buffer}`));
  724. }, 5000);
  725. waiters.push(waiter);
  726. });
  727. },
  728. close() {
  729. socket.destroy();
  730. }
  731. }));
  732. socket.once('error', reject);
  733. socket.once('timeout', () => reject(new Error('Mail access client timed out')));
  734. });
  735. }
  736. function extractFetchLiteral(response, label) {
  737. const bytes = Buffer.isBuffer(response) ? response : Buffer.from(response || '');
  738. const marker = Buffer.from(`${label} {`, 'ascii');
  739. const markerIndex = bytes.indexOf(marker);
  740. assert.notEqual(markerIndex, -1, `Missing ${label} literal marker`);
  741. const sizeStart = markerIndex + marker.length;
  742. const sizeEndMarker = Buffer.from('}\r\n', 'ascii');
  743. const sizeEnd = bytes.indexOf(sizeEndMarker, sizeStart);
  744. assert.notEqual(sizeEnd, -1, `Missing ${label} literal size terminator`);
  745. const size = Number(bytes.subarray(sizeStart, sizeEnd).toString('ascii'));
  746. assert.equal(Number.isInteger(size) && size >= 0, true, `Invalid ${label} literal size`);
  747. const literalStart = sizeEnd + sizeEndMarker.length;
  748. const literalEnd = literalStart + size;
  749. assert.ok(literalEnd <= bytes.length, `Truncated ${label} literal`);
  750. assert.deepEqual(bytes.subarray(literalEnd, literalEnd + 5), Buffer.from('\r\n)\r\n', 'ascii'));
  751. return bytes.subarray(literalStart, literalEnd);
  752. }
  753. function assertImapSearchResult(response, expected) {
  754. assert.match(response, /^\S+ OK SEARCH completed\r?$/m);
  755. const match = response.match(/^\* SEARCH(?: ([0-9 ]+))?\r?$/m);
  756. assert.ok(match, `Missing SEARCH response in: ${response}`);
  757. const actual = String(match[1] || '')
  758. .split(/\s+/)
  759. .filter(Boolean)
  760. .map(Number);
  761. assert.deepEqual(actual, expected);
  762. }
  763. function waitForListening(server) {
  764. if (server.listening) return Promise.resolve();
  765. return new Promise((resolve) => server.once('listening', resolve));
  766. }
  767. function closeServer(server) {
  768. return new Promise((resolve, reject) => {
  769. server.close((error) => error ? reject(error) : resolve());
  770. });
  771. }