Files
instantadpay/inbound.js
T

71 lines
5.1 KiB
JavaScript

// Email intake for the help desk (2026-10-16): SendGrid Inbound Parse posts every message sent to the support hosts
// (support@help.instantadpay.com, reply+<ref>@help.instantadpay.com, anything @linkspin.app) here as multipart/form-data.
// We turn it into a new ticket or a reply on an existing one (tickets.ingestEmail), after dropping robots: bounces,
// auto-replies, bulk mail and our own messages, so two autoresponders can never ping-pong. The URL carries a secret key
// (env SUPPORT_INBOUND_KEY); SendGrid retries anything that is not 2xx, so the route always answers 200 once the key passes.
'use strict';
let tickets = null;
function init(d) { tickets = d.tickets; }
const key = () => String(process.env.SUPPORT_INBOUND_KEY || '').trim();
// a small multipart reader: text fields only, files skipped (attachments are not kept yet)
function parseMultipart(buf, contentType) {
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || ''); if (!m) return {};
const boundary = Buffer.from('--' + (m[1] || m[2]).trim());
const out = {}; let pos = buf.indexOf(boundary);
while (pos >= 0) {
const next = buf.indexOf(boundary, pos + boundary.length); if (next < 0) break;
const part = buf.slice(pos + boundary.length + 2, next - 2); // skip CRLF after the boundary and before the next
const sep = part.indexOf('\r\n\r\n');
if (sep > 0) {
const head = part.slice(0, sep).toString('utf8');
const nm = /name="([^"]+)"/i.exec(head);
if (nm && !/filename=/i.test(head)) out[nm[1]] = part.slice(sep + 4).toString('utf8');
}
pos = next;
}
return out;
}
const header = (raw, name) => { const m = new RegExp('^' + name + ':\\s*([^\\r\\n]*(?:\\r?\\n[ \\t][^\\r\\n]*)*)', 'im').exec(raw || ''); return m ? m[1].replace(/\r?\n[ \t]+/g, ' ').trim() : ''; };
const addrOf = s => { const m = /<([^>]+)>/.exec(s || ''); return String(m ? m[1] : s || '').trim().toLowerCase(); };
const nameOf = s => { const m = /^\s*"?([^"<]*?)"?\s*</.exec(s || ''); return m ? m[1].trim() : ''; };
const ROBOT_FROM = /(mailer-daemon|postmaster|no-?reply|do-?not-?reply|bounce|notifications?@)/i;
// keep what the person wrote, not the quoted history under it
function stripQuoted(text) {
let t = String(text || '').replace(/\r\n/g, '\n');
const cuts = [/^On .{3,200}wrote:\s*$/m, /^-{2,}\s*Original Message\s*-{2,}/im, /^From:\s.+\n(?:Sent|Date):\s/m, /^_{10,}\s*$/m];
for (const re of cuts) { const m = re.exec(t); if (m) t = t.slice(0, m.index); }
return t.split('\n').filter(l => !/^\s*>/.test(l)).join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
const htmlToText = h => String(h || '').replace(/<(br|\/p|\/div)[^>]*>/gi, '\n').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
const perSender = new Map(); // sender -> [timestamps], at most 20 messages an hour become tickets or replies
function flood(addr) { const now = Date.now(); const a = (perSender.get(addr) || []).filter(t => now - t < 3600000); a.push(now); perSender.set(addr, a); return a.length > 20; }
// returns a short outcome string for the log
async function handle(buf, contentType) {
const f = parseMultipart(buf, contentType);
const raw = f.headers || '';
const from = addrOf(f.from); if (!from || !/@/.test(from)) return 'no sender';
let rcpts = []; try { rcpts = (JSON.parse(f.envelope || '{}').to || []).map(addrOf); } catch (e) {}
if (!rcpts.length) rcpts = String(f.to || '').split(',').map(addrOf);
const auto = header(raw, 'Auto-Submitted'), prec = header(raw, 'Precedence');
if ((auto && !/^no$/i.test(auto)) || /bulk|junk|list/i.test(prec) || header(raw, 'X-Autoreply') || header(raw, 'X-Autorespond') || ROBOT_FROM.test(from)) return 'robot dropped: ' + from;
if (/@(instantadpay\.com|help\.instantadpay\.com|linkspin\.app)$/.test(from)) return 'own address dropped';
if (flood(from)) return 'flood dropped: ' + from;
// support@instantadpay.com is forwarded by NameSilo to iap-support@linkspin.app (its forwarder will not deliver to our own
// help. subdomain), so that one address means an InstantAdPay ticket even though it arrives on the LinkSpin host
const iapAlias = r => /^iap-support@linkspin\.app$/.test(r);
const platform = rcpts.some(r => /@linkspin\.app$/.test(r) && !iapAlias(r)) ? 'linkspin' : 'iap';
let subject = String(f.subject || '').replace(/\s+/g, ' ').trim();
const plus = rcpts.map(r => /^reply\+((?:iap|ls)-\d{4,9})@/.exec(r)).find(Boolean); // the reply-to we put on ticket mail
if (plus) { const ref = plus[1].toUpperCase(); if (!subject.toUpperCase().includes(ref)) subject = '[' + ref + '] ' + subject; }
const body = stripQuoted(f.text || htmlToText(f.html)) || '(empty message)';
const r = await tickets.ingestEmail({ from, name: nameOf(f.from), subject, text: body, platform, confirm: true,
messageId: header(raw, 'Message-ID'), inReplyTo: header(raw, 'In-Reply-To'), references: header(raw, 'References') });
if (r && r.error) return 'refused: ' + r.error;
return (r.created ? 'new ticket ' : 'reply on ') + (r.ticket && r.ticket.ref) + ' from ' + from;
}
module.exports = { init, key, handle, stripQuoted, parseMultipart };