mail-access.test.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 exposes MIME body structures and individual parts for Roundcube', async () => {
  114. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-mime-test-')), 'mail-access-secret');
  115. const { mailbox } = createMailboxFixture('mime.example', 'mime-user');
  116. createInboundMessage(mailbox, {
  117. sender: 'alice@example.net',
  118. recipients: ['admin@mime.example'],
  119. subject: 'MIME message',
  120. messageId: '<mime-message@example.net>',
  121. rawMessage: [
  122. 'From: Alice <alice@example.net>',
  123. 'To: admin@mime.example',
  124. 'Subject: MIME message',
  125. 'MIME-Version: 1.0',
  126. 'Content-Type: multipart/alternative; boundary="mailhub-boundary"',
  127. '',
  128. '--mailhub-boundary',
  129. 'Content-Type: text/plain; charset=UTF-8',
  130. 'Content-Transfer-Encoding: quoted-printable',
  131. '',
  132. 'Plain message body.',
  133. '--mailhub-boundary',
  134. 'Content-Type: text/html; charset=UTF-8',
  135. '',
  136. '<p>HTML message body.</p>',
  137. '--mailhub-boundary--',
  138. ''
  139. ].join('\r\n'),
  140. textBody: 'Plain message body.',
  141. htmlBody: '<p>HTML message body.</p>'
  142. });
  143. const [server] = startMailboxAccessServers({
  144. hostname: 'mail.mime.example',
  145. imapEnabled: true,
  146. imapListeners: [{ port: 0, protocol: 'imap' }],
  147. pop3Enabled: false,
  148. pop3Listeners: [],
  149. allowInsecureAuth: true
  150. });
  151. await waitForListening(server);
  152. let client;
  153. try {
  154. client = await connectClient(server.address().port);
  155. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  156. assert.match(await client.command('A1 LOGIN "admin@mime.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  157. await client.command('A2 SELECT INBOX', /A2 OK/);
  158. const structure = await client.command('A3 UID FETCH 1 (UID BODYSTRUCTURE)', /A3 OK/);
  159. assert.match(structure, /BODYSTRUCTURE \(\("TEXT" "PLAIN" \("CHARSET" "UTF-8"\).*\) \("TEXT" "HTML" \("CHARSET" "UTF-8"\).*\) "ALTERNATIVE" \("BOUNDARY" "mailhub-boundary"\)\)/);
  160. const textPart = await client.command('A4 UID FETCH 1 (BODY.PEEK[1])', /A4 OK/);
  161. assert.match(textPart, /BODY\[1\] \{\d+\}\r\nPlain message body\./);
  162. assert.doesNotMatch(textPart, /Content-Type: text\/plain/);
  163. const htmlPart = await client.command('A5 UID FETCH 1 (BODY.PEEK[2])', /A5 OK/);
  164. assert.match(htmlPart, /BODY\[2\] \{\d+\}\r\n<p>HTML message body\.<\/p>/);
  165. const mimeHeaders = await client.command('A6 UID FETCH 1 (BODY.PEEK[1.MIME])', /A6 OK/);
  166. assert.match(mimeHeaders, /BODY\[1\.MIME\] \{\d+\}\r\nContent-Type: text\/plain; charset=UTF-8/);
  167. await client.command('A7 LOGOUT', /A7 OK/);
  168. client.close();
  169. } finally {
  170. client?.close();
  171. await closeServer(server);
  172. }
  173. });
  174. test('IMAP exposes standard folders expected by mainstream clients', async () => {
  175. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-folders-test-')), 'mail-access-secret');
  176. createMailboxFixture('folders.example', 'folders-user');
  177. const [server] = startMailboxAccessServers({
  178. hostname: 'mail.folders.example',
  179. imapEnabled: true,
  180. imapListeners: [{ port: 0, protocol: 'imap' }],
  181. pop3Enabled: false,
  182. pop3Listeners: [],
  183. allowInsecureAuth: true
  184. });
  185. await waitForListening(server);
  186. let client;
  187. try {
  188. client = await connectClient(server.address().port);
  189. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  190. assert.match(await client.command('A1 LOGIN "admin@folders.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  191. const listed = await client.command('A2 LIST "" "*"', /A2 OK/);
  192. assert.match(listed, /\* LIST .* "INBOX"/);
  193. assert.match(listed, /\* LIST .*\\Sent.* "Sent"/);
  194. assert.match(listed, /\* LIST .*\\Drafts.* "Drafts"/);
  195. assert.match(listed, /\* LIST .*\\Trash.* "Trash"/);
  196. assert.match(listed, /\* LIST .*\\Junk.* "Junk"/);
  197. assert.match(listed, /\* LIST .*\\Archive.* "Archive"/);
  198. const selected = await client.command('A3 SELECT Sent', /A3 OK/);
  199. assert.match(selected, /\* 0 EXISTS/);
  200. await client.command('A4 LOGOUT', /A4 OK/);
  201. client.close();
  202. } finally {
  203. client?.close();
  204. await closeServer(server);
  205. }
  206. });
  207. test('IMAP uses Modified UTF-7 on the wire while storing Unicode folder names', async () => {
  208. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-utf7-test-')), 'mail-access-secret');
  209. const { user, mailbox } = createMailboxFixture('utf7.example', 'utf7-user');
  210. createInboundFolder(mailbox, '中文 & 项目');
  211. const [server] = startMailboxAccessServers({
  212. hostname: 'mail.utf7.example',
  213. imapEnabled: true,
  214. imapListeners: [{ port: 0, protocol: 'imap' }],
  215. pop3Enabled: false,
  216. pop3Listeners: [],
  217. allowInsecureAuth: true
  218. });
  219. await waitForListening(server);
  220. let client;
  221. try {
  222. client = await connectClient(server.address().port);
  223. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  224. await client.command('A1 LOGIN "admin@utf7.example" "mailbox-pass-123"', /A1 OK/);
  225. const listed = await client.command('A2 LIST "" "*"', /A2 OK/);
  226. assert.match(listed, /"&Ti1lhw- &- &mHl27g-"/);
  227. assert.doesNotMatch(listed, /中文|项目/);
  228. const subscribed = await client.command('A2L LSUB "" "*"', /A2L OK/);
  229. assert.match(subscribed, /"&Ti1lhw- &- &mHl27g-"/);
  230. const selected = await client.command('A3 SELECT "&Ti1lhw- &- &mHl27g-"', /A3 OK/);
  231. assert.match(selected, /\* 0 EXISTS/);
  232. const status = await client.command('A4 STATUS "&Ti1lhw- &- &mHl27g-" \(MESSAGES UNSEEN\)', /A4 OK/);
  233. assert.match(status, /\* STATUS "&Ti1lhw- &- &mHl27g-" \(MESSAGES 0 UNSEEN 0/);
  234. await client.command('A5 CREATE "&ZeVnLIqe-"', /A5 OK/);
  235. assert.equal(inboundFolderExists(mailbox, '日本語'), true);
  236. const rawMessage = [
  237. 'From: Bob <bob@example.net>',
  238. 'To: admin@utf7.example',
  239. 'Subject: UTF-7 folder append',
  240. '',
  241. 'Imported into a Unicode folder.'
  242. ].join('\r\n');
  243. await client.append(
  244. `A6 APPEND "&ZeVnLIqe-" {${Buffer.byteLength(rawMessage, 'utf8')}}`,
  245. rawMessage,
  246. /A6 OK/
  247. );
  248. assert.equal(listInboundMessages(user.id, { folder: '日本語' }).length, 1);
  249. await client.command('A7 LOGOUT', /A7 OK/);
  250. client.close();
  251. } finally {
  252. client?.close();
  253. await closeServer(server);
  254. }
  255. });
  256. test('IMAP APPEND stores sent messages in the Sent folder', async () => {
  257. initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-imap-append-test-')), 'mail-access-secret');
  258. const { user } = createMailboxFixture('append.example', 'append-user');
  259. const [server] = startMailboxAccessServers({
  260. hostname: 'mail.append.example',
  261. imapEnabled: true,
  262. imapListeners: [{ port: 0, protocol: 'imap' }],
  263. pop3Enabled: false,
  264. pop3Listeners: [],
  265. allowInsecureAuth: true
  266. });
  267. await waitForListening(server);
  268. let client;
  269. try {
  270. const sentMessage = [
  271. 'From: Admin <admin@append.example>',
  272. 'To: Bob <bob@example.net>',
  273. 'Subject: =?UTF-8?Q?=E6=A0=B8=E4=BA=91?=',
  274. ' =?UTF-8?Q?=E8=AE=A1=E7=AE=97?=',
  275. 'Message-ID: <sent-copy@append.example>',
  276. 'MIME-Version: 1.0',
  277. 'Content-Type: multipart/alternative; boundary="sent-boundary"',
  278. '',
  279. '--sent-boundary',
  280. 'Content-Type: text/plain; charset=UTF-8',
  281. 'Content-Transfer-Encoding: base64',
  282. '',
  283. Buffer.from('工单正文', 'utf8').toString('base64'),
  284. '--sent-boundary',
  285. 'Content-Type: text/html; charset=UTF-8',
  286. 'Content-Transfer-Encoding: quoted-printable',
  287. '',
  288. '<p>Sent HTML body.</p>',
  289. '--sent-boundary--',
  290. ''
  291. ].join('\r\n');
  292. client = await connectClient(server.address().port);
  293. await client.readUntil(/\* OK .* IMAP ready\r\n/);
  294. assert.match(await client.command('A1 LOGIN "admin@append.example" "mailbox-pass-123"', /A1 OK/), /LOGIN completed/);
  295. await client.append(`A2 APPEND Sent (\\Seen) {${Buffer.byteLength(sentMessage, 'utf8')}}`, sentMessage, /A2 OK/);
  296. const selectedSent = await client.command('A3 SELECT Sent', /A3 OK/);
  297. assert.match(selectedSent, /\* 1 EXISTS/);
  298. const fetchedSent = await client.command('A4 UID FETCH 1:* (UID FLAGS BODY.PEEK[])', /A4 OK/);
  299. assert.match(fetchedSent, /FLAGS \(\\Seen\)/);
  300. assert.match(fetchedSent, /Subject: =\?UTF-8\?Q\?/);
  301. assert.match(fetchedSent, /--sent-boundary/);
  302. const [storedSummary] = listInboundMessages(user.id, { folder: 'Sent' });
  303. const storedMessage = getInboundMessage(user.id, storedSummary.id);
  304. assert.equal(storedMessage.subject, '核云计算');
  305. assert.equal(storedMessage.textBody, '工单正文');
  306. assert.match(storedMessage.htmlBody, /Sent HTML body/);
  307. assert.equal(storedMessage.preview, '工单正文');
  308. assert.match(storedMessage.rawMessage, /--sent-boundary/);
  309. const latin1Message = Buffer.concat([
  310. Buffer.from([
  311. 'From: Admin <admin@append.example>',
  312. 'To: Bob <bob@example.net>',
  313. 'Subject: Latin1 copy',
  314. 'Content-Type: text/plain; charset=ISO-8859-1',
  315. 'Content-Transfer-Encoding: 8bit',
  316. '',
  317. 'caf'
  318. ].join('\r\n'), 'ascii'),
  319. Buffer.from([0xe9])
  320. ]);
  321. await client.append(`A5 APPEND Sent {${latin1Message.length}}`, latin1Message, /A5 OK/);
  322. const latin1Summary = listInboundMessages(user.id, { folder: 'Sent' })
  323. .find((message) => message.subject === 'Latin1 copy');
  324. assert.equal(getInboundMessage(user.id, latin1Summary.id).textBody, 'café');
  325. await client.command('A6 SELECT Sent', /A6 OK/);
  326. const latin1Fetch = await client.commandBytes('A7 UID FETCH 1:* (UID BODY.PEEK[])', /A7 OK/);
  327. assert.equal(latin1Fetch.includes(latin1Message), true);
  328. const selectedInbox = await client.command('A8 SELECT INBOX', /A8 OK/);
  329. assert.match(selectedInbox, /\* 0 EXISTS/);
  330. await client.command('A9 LOGOUT', /A9 OK/);
  331. client.close();
  332. } finally {
  333. client?.close();
  334. await closeServer(server);
  335. }
  336. });
  337. test('POP3 clients can retrieve and delete messages on quit', async () => {
  338. const database = initDatabase(mkdtempSync(path.join(tmpdir(), 'mailhub-pop3-test-')), 'mail-access-secret');
  339. const { user, mailbox } = createMailboxFixture('pop3.example', 'pop3-user');
  340. const firstRawMessage = [
  341. 'From: Bob <bob@example.net>',
  342. 'To: admin@pop3.example',
  343. 'Subject: POP3 hello',
  344. 'Message-ID: <pop3-hello@example.net>',
  345. '',
  346. 'Hello through POP3.'
  347. ].join('\r\n');
  348. const firstMessage = createInboundMessage(mailbox, {
  349. sender: 'bob@example.net',
  350. recipients: ['admin@pop3.example'],
  351. subject: 'POP3 hello',
  352. messageId: '<pop3-hello@example.net>',
  353. rawMessage: firstRawMessage,
  354. textBody: 'Hello through POP3.'
  355. });
  356. const latin1RawMessage = Buffer.concat([
  357. Buffer.from([
  358. 'From: Alice <alice@example.net>',
  359. 'To: admin@pop3.example',
  360. 'Subject: Latin1 POP3',
  361. 'Content-Type: text/plain; charset=ISO-8859-1',
  362. 'Content-Transfer-Encoding: 8bit',
  363. '',
  364. 'caf'
  365. ].join('\n'), 'ascii'),
  366. Buffer.from([0xe9])
  367. ]);
  368. createInboundMessage(mailbox, {
  369. sender: 'alice@example.net',
  370. recipients: ['admin@pop3.example'],
  371. subject: 'Latin1 POP3',
  372. rawMessage: latin1RawMessage.toString('latin1'),
  373. rawMessageBytes: latin1RawMessage,
  374. textBody: 'café'
  375. });
  376. const firstPop3Message = Buffer.from(`${firstRawMessage}\r\n`, 'utf8');
  377. const latin1Pop3Message = Buffer.concat([
  378. Buffer.from(latin1RawMessage.toString('latin1').replace(/\n/g, '\r\n'), 'latin1'),
  379. Buffer.from('\r\n')
  380. ]);
  381. const totalOctets = firstPop3Message.length + latin1Pop3Message.length;
  382. const [server] = startMailboxAccessServers({
  383. hostname: 'mail.pop3.example',
  384. imapEnabled: false,
  385. imapListeners: [],
  386. pop3Enabled: true,
  387. pop3Listeners: [{ port: 0, protocol: 'pop3' }],
  388. allowInsecureAuth: true
  389. });
  390. await waitForListening(server);
  391. try {
  392. const client = await connectClient(server.address().port);
  393. await client.readUntil(/\+OK .* POP3 ready\r\n/);
  394. assert.match(await client.command('USER admin@pop3.example', /\+OK/), /User accepted/);
  395. assert.match(await client.command('PASS mailbox-pass-123', /\+OK/), /ready/);
  396. assert.match(await client.command('STAT', /\+OK \d+ \d+/), new RegExp(`\\+OK 2 ${totalOctets}`));
  397. const listed = await client.command('LIST', /\r\n\.\r\n/);
  398. assert.match(listed, new RegExp(`1 ${firstPop3Message.length}\\r\\n`));
  399. assert.match(listed, new RegExp(`2 ${latin1Pop3Message.length}\\r\\n`));
  400. assert.match(await client.command('UIDL 1', /\+OK 1 mh-1/), /\+OK 1 mh-1/);
  401. database
  402. .prepare('UPDATE inbound_messages SET raw_message_bytes = ? WHERE id = ?')
  403. .run(Buffer.from(firstRawMessage.replace('Hello through POP3.', 'Hallo through POP3.'), 'utf8'), firstMessage.id);
  404. const retrieved = await client.command('RETR 1', /\r\n\.\r\n/);
  405. assert.match(retrieved, /Subject: POP3 hello/);
  406. assert.match(retrieved, /Hallo through POP3\./);
  407. assert.doesNotMatch(retrieved, /Hello through POP3\./);
  408. const latin1Retrieved = await client.commandBytes('RETR 2', /\r\n\.\r\n/);
  409. assert.deepEqual(latin1Retrieved, Buffer.concat([
  410. Buffer.from(`+OK ${latin1Pop3Message.length} octets\r\n`),
  411. latin1Pop3Message,
  412. Buffer.from('.\r\n')
  413. ]));
  414. assert.match(await client.command('DELE 1', /\+OK/), /deleted/);
  415. assert.match(await client.command('DELE 2', /\+OK/), /deleted/);
  416. await client.command('QUIT', /\+OK Bye/);
  417. client.close();
  418. assert.equal(listInboundMessages(user.id).length, 0);
  419. } finally {
  420. await closeServer(server);
  421. }
  422. });
  423. test('POP3 AUTH PLAIN requires TLS when insecure authentication is disabled', async () => {
  424. const [server] = startMailboxAccessServers({
  425. hostname: 'mail.secure-pop3.example',
  426. imapEnabled: false,
  427. imapListeners: [],
  428. pop3Enabled: true,
  429. pop3Listeners: [{ port: 0, protocol: 'pop3' }],
  430. allowInsecureAuth: false
  431. });
  432. await waitForListening(server);
  433. let client;
  434. try {
  435. client = await connectClient(server.address().port);
  436. await client.readUntil(/\+OK .* POP3 ready\r\n/);
  437. const credentials = Buffer.from('\u0000user@example.com\u0000password').toString('base64');
  438. assert.equal(
  439. await client.command(`AUTH PLAIN ${credentials}`, /\+OK|\-ERR/),
  440. '-ERR Encryption required for authentication\r\n'
  441. );
  442. } finally {
  443. client?.close();
  444. await closeServer(server);
  445. }
  446. });
  447. function createMailboxFixture(domainName, username) {
  448. const user = createUser({ username, email: `${username}@example.com`, password: 'password123' });
  449. createDomain(user.id, {
  450. domain: domainName,
  451. selector: 'mh',
  452. verificationToken: 'verify',
  453. dkimPublic: 'public',
  454. dkimPrivate: 'private',
  455. senderHost: `mail.${domainName}`,
  456. sendingIp: '192.0.2.30',
  457. spfExtra: '',
  458. dmarcPolicy: 'none',
  459. dmarcRua: ''
  460. });
  461. const mailbox = createInboundMailbox(user.id, {
  462. address: `admin@${domainName}`,
  463. password: 'mailbox-pass-123'
  464. });
  465. return { user, mailbox };
  466. }
  467. function connectClient(port) {
  468. return new Promise((resolve, reject) => {
  469. const socket = net.createConnection({ host: '127.0.0.1', port });
  470. socket.setTimeout(5000);
  471. let buffer = '';
  472. let rawBuffer = Buffer.alloc(0);
  473. const waiters = [];
  474. socket.on('data', (chunk) => {
  475. const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
  476. rawBuffer = Buffer.concat([rawBuffer, bytes]);
  477. buffer += bytes.toString('utf8');
  478. for (const waiter of [...waiters]) {
  479. if (waiter.pattern.test(buffer)) {
  480. waiters.splice(waiters.indexOf(waiter), 1);
  481. const output = buffer;
  482. const rawOutput = rawBuffer;
  483. buffer = '';
  484. rawBuffer = Buffer.alloc(0);
  485. waiter.resolve(waiter.raw ? rawOutput : output);
  486. }
  487. }
  488. });
  489. socket.once('connect', () => resolve({
  490. command(command, pattern) {
  491. socket.write(`${command}\r\n`);
  492. return this.readUntil(pattern);
  493. },
  494. commandBytes(command, pattern) {
  495. socket.write(`${command}\r\n`);
  496. return this.readUntil(pattern, true);
  497. },
  498. async append(command, literal, pattern) {
  499. socket.write(`${command}\r\n`);
  500. await this.readUntil(/^\+ /m);
  501. socket.write(literal);
  502. socket.write('\r\n');
  503. return this.readUntil(pattern);
  504. },
  505. readUntil(pattern, raw = false) {
  506. if (pattern.test(buffer)) {
  507. const output = buffer;
  508. const rawOutput = rawBuffer;
  509. buffer = '';
  510. rawBuffer = Buffer.alloc(0);
  511. return Promise.resolve(raw ? rawOutput : output);
  512. }
  513. return new Promise((waitResolve, waitReject) => {
  514. const waiter = {
  515. pattern,
  516. raw,
  517. resolve(output) {
  518. clearTimeout(waiter.timer);
  519. waitResolve(output);
  520. },
  521. reject(error) {
  522. clearTimeout(waiter.timer);
  523. waitReject(error);
  524. },
  525. timer: null
  526. };
  527. waiter.timer = setTimeout(() => {
  528. waiters.splice(waiters.indexOf(waiter), 1);
  529. waitReject(new Error(`Timed out waiting for ${pattern}; buffered response: ${buffer}`));
  530. }, 5000);
  531. waiters.push(waiter);
  532. });
  533. },
  534. close() {
  535. socket.destroy();
  536. }
  537. }));
  538. socket.once('error', reject);
  539. socket.once('timeout', () => reject(new Error('Mail access client timed out')));
  540. });
  541. }
  542. function waitForListening(server) {
  543. if (server.listening) return Promise.resolve();
  544. return new Promise((resolve) => server.once('listening', resolve));
  545. }
  546. function closeServer(server) {
  547. return new Promise((resolve, reject) => {
  548. server.close((error) => error ? reject(error) : resolve());
  549. });
  550. }