mailprobe.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Exercises ctx.mail through the DEPLOYED runner against a real mail provider.
  2. //
  3. // Credentials are NEVER in this source: userSecret/passwordSecret name project
  4. // secrets that the host resolves, so nothing here or in an echoed options
  5. // object can leak them.
  6. //
  7. // timeoutMs is raised to the HTTP ceiling because the default wall budget is
  8. // 2 s and a TLS IMAP session plus a LOGIN does not fit in that.
  9. export const on = {
  10. id: 'mailprobe',
  11. type: 'http',
  12. route: '/mail/:op',
  13. method: ['GET', 'POST'],
  14. timeoutMs: 15000,
  15. };
  16. const IMAP = {
  17. host: 'mail.onmail.hu',
  18. port: 993,
  19. tls: true,
  20. user: 'nbot@fsociety.hu',
  21. passwordSecret: 'MAIL_IMAP_PASSWORD',
  22. };
  23. // 2525 with STARTTLS. NOT 587: DigitalOcean blocks outbound 25, 465 and 587
  24. // from this droplet (confirmed as the host's policy, since gmail and sendgrid
  25. // are blocked on 587 too), while 2525 is open. tls and startTls are mutually
  26. // exclusive, so tls must be false here; plaintext is still refused off
  27. // loopback, which startTls satisfies.
  28. const SMTP = {
  29. host: 'mail.onmail.hu',
  30. port: 2525,
  31. tls: false,
  32. startTls: true,
  33. user: 'nbot@fsociety.hu',
  34. passwordSecret: 'MAIL_SMTP_PASSWORD',
  35. };
  36. export default async function (ctx) {
  37. const op = (ctx.params && ctx.params.op) || 'mailboxes';
  38. const started = Date.now();
  39. try {
  40. if (op === 'mailboxes') {
  41. const boxes = await ctx.mail.mailboxes(IMAP);
  42. return {
  43. op, ok: true, ms: Date.now() - started,
  44. count: boxes.length,
  45. // nameEncoding proves the modified-UTF-7 decode ran.
  46. boxes: boxes.map(b => ({ name: b.name, nameEncoding: b.nameEncoding, delimiter: b.delimiter })),
  47. };
  48. }
  49. if (op === 'read') {
  50. const r = await ctx.mail.read({ ...IMAP, mailbox: 'INBOX', criteria: 'ALL', limit: 3 });
  51. return {
  52. op, ok: true, ms: Date.now() - started,
  53. matched: r.matched,
  54. returned: r.messages.length,
  55. messages: r.messages.map(m => ({
  56. uid: m.uid, flags: m.flags, size: m.size,
  57. internal_date: m.internal_date,
  58. headerEncoding: m.headerEncoding, textEncoding: m.textEncoding,
  59. body_sections: m.body_sections,
  60. // A SLICE only: the point is that bytes arrived, not to echo mail.
  61. header_head: (m.header || '').slice(0, 120),
  62. text_head: (m.text || '').slice(0, 80),
  63. })),
  64. };
  65. }
  66. if (op === 'small') {
  67. // The documented remedy for mail_too_large: ask for less. A plain
  68. // read of this mailbox exceeds the 4 MiB per-run cap, so bound it by
  69. // message size rather than by count - limit alone cannot help, since
  70. // one big message is enough to blow the cap.
  71. const r = await ctx.mail.read({
  72. ...IMAP, criteria: { smallerThanBytes: 60000 }, limit: 3,
  73. });
  74. return {
  75. op, ok: true, ms: Date.now() - started,
  76. matched: r.matched, returned: r.messages.length,
  77. messages: r.messages.map(m => ({
  78. uid: m.uid, flags: m.flags, size: m.size,
  79. headerEncoding: m.headerEncoding, textEncoding: m.textEncoding,
  80. body_sections: m.body_sections,
  81. subject: ((m.header || '').match(/^Subject:\s*(.*)$/mi) || [])[1] || null,
  82. text_head: (m.text || '').slice(0, 60),
  83. })),
  84. };
  85. }
  86. if (op === 'unseen') {
  87. // A structured criterion, which is the only form accepted.
  88. const r = await ctx.mail.read({ ...IMAP, criteria: { unseen: true }, limit: 5 });
  89. return { op, ok: true, ms: Date.now() - started, matched: r.matched, uids: r.messages.map(m => m.uid) };
  90. }
  91. if (op === 'accents') {
  92. // MUST be refused by field name rather than sent. A pass here is a
  93. // silently wrong answer, not a feature.
  94. const r = await ctx.mail.read({ ...IMAP, criteria: { subject: 'árvíztűrő' }, limit: 1 });
  95. return { op, ok: true, unexpected: true, matched: r.matched };
  96. }
  97. if (op === 'send') {
  98. const stamp = String(Date.now());
  99. const r = await ctx.mail.send({
  100. ...SMTP,
  101. from: 'Kővágó Örs <nbot@fsociety.hu>',
  102. to: 'test001@fsociety.hu',
  103. subject: 'ctx.mail prod proba ' + stamp + ' - árvíztűrő tükörfúrógép',
  104. text: 'Ez a level a telepitett runnerbol ment. stamp=' + stamp +
  105. '\n.\nEgy maganyos pont a fenti sorban.\n',
  106. html: '<p>Ez a levél a <b>telepített runnerből</b> ment.</p>',
  107. attachments: [{ filename: 'árvíztűrő.txt', contentType: 'text/plain', base64: 'w6FydsOtenT9csWR' }],
  108. });
  109. return { op, ok: true, ms: Date.now() - started, accepted: r.accepted };
  110. }
  111. if (op === 'roundtrip') {
  112. // The strongest end-to-end check available: send to the mailbox we can
  113. // READ, then fetch it back and assert on the bytes. Sent to nbot@ rather
  114. // than test001@ precisely because test001@ routes to a human's box we
  115. // cannot open.
  116. const stamp = String(Date.now());
  117. const subject = 'svapi roundtrip ' + stamp + ' - árvíztűrő tükörfúrógép';
  118. const sent = await ctx.mail.send({
  119. ...SMTP,
  120. from: 'Kővágó Örs <nbot@fsociety.hu>',
  121. to: 'nbot@fsociety.hu',
  122. subject,
  123. // A lone '.' on its own line: dot-stuffing is curl's job, and if we
  124. // also stuffed it the body would be corrupt; if neither did, the
  125. // message would be TRUNCATED here.
  126. text: 'stamp=' + stamp + '\n.\nA fenti sorban egy magányos pont áll.\n',
  127. html: '<p>stamp=' + stamp + ' <b>árvíztűrő</b></p>',
  128. attachments: [{ filename: 'árvíztűrő.txt', contentType: 'text/plain', base64: 'w6FydsOtenT9csWR' }],
  129. });
  130. // Give the server a moment to file it, then find it by an ASCII-safe
  131. // criterion - the accented subject CANNOT be searched for, by design.
  132. let found = null;
  133. for (let attempt = 0; attempt < 6 && !found; attempt++) {
  134. const r = await ctx.mail.read({
  135. ...IMAP, criteria: { subject: 'svapi roundtrip ' + stamp }, limit: 1,
  136. });
  137. if (r.messages.length > 0) found = r.messages[0];
  138. }
  139. if (!found) {
  140. return { op, ok: false, sent: sent.accepted, stamp, error: 'sent but not found on read-back' };
  141. }
  142. const header = found.header || '';
  143. const text = found.text || '';
  144. return {
  145. op, ok: true, ms: Date.now() - started, stamp,
  146. sent: sent.accepted,
  147. uid: found.uid,
  148. flags: found.flags,
  149. checks: {
  150. // The subject must arrive as RFC 2047 encoded words, not raw bytes.
  151. subject_is_encoded_word: /Subject:.*=\?UTF-8\?/i.test(header),
  152. subject_raw: (header.match(/^Subject:\s*(.*)$/mi) || [])[1] || null,
  153. // The lone dot survived and was not doubled.
  154. lone_dot_intact: /\n\.\r?\n|\r\n\.\r\n/.test(text),
  155. double_stuffed: text.indexOf('\n..') !== -1,
  156. // RFC 2231 for the accented filename.
  157. rfc2231_filename: /filename\*=|filename\*0\*=/i.test(text),
  158. quoted_printable: /Content-Transfer-Encoding:\s*quoted-printable/i.test(text),
  159. multipart_alternative: /multipart\/alternative/i.test(text),
  160. multipart_mixed: /multipart\/mixed/i.test(text),
  161. // Quoted-printable encodes '=' as '=3D', so the literal 'stamp='
  162. // is NOT in the transferred body - looking for it was a naive check.
  163. stamp_in_body_qp: text.indexOf('stamp=3D' + stamp) !== -1,
  164. // multipart/mixed is declared in the HEADER (it is the top-level
  165. // Content-Type); only the inner alternative boundary shows in TEXT.
  166. mixed_in_header: /multipart\/mixed/i.test(header),
  167. },
  168. headerEncoding: found.headerEncoding,
  169. // The exact bytes around the Subject, escaped, so a fold is visible.
  170. subject_region: (function () {
  171. const i = header.search(/^Subject:/mi);
  172. if (i < 0) return null;
  173. return header.slice(i, i + 120).replace(/\r/g, '<CR>').replace(/\n/g, '<LF>');
  174. })(),
  175. };
  176. }
  177. return { op, ok: false, error: 'unknown op; use mailboxes|read|small|unseen|accents|send' };
  178. } catch (e) {
  179. // The shape a consumer branches on: slug, status and retryable.
  180. // NOT a key called `status`: a returned object carrying status, headers or
  181. // body is read as a response ENVELOPE, and an envelope may hold nothing
  182. // else - so a diagnostic field named `status` turns into a 500
  183. // invalid_return and hides the very error it was meant to report.
  184. return {
  185. op, ok: false, ms: Date.now() - started,
  186. code: e.code || null,
  187. httpStatus: e.status || null,
  188. retryable: (e.details && e.details.retryable) ?? null,
  189. message: String(e.message || e).slice(0, 400),
  190. };
  191. }
  192. }