mail-access.test.js 31 KB

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