From ad17017250a3437902f303a74592b59959855a82 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 16 Oct 2026 18:10:53 -0500 Subject: [PATCH] Help desk email intake: SendGrid Inbound Parse -> /api/inbound/email (secret key) creates tickets or threads replies; robots, bounces, auto-replies and our own mail dropped; ticket mail carries reply+@ reply-to and Auto-Submitted Co-Authored-By: Claude Opus 5.5 --- inbound.js | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ mailer.js | 2 ++ server.js | 11 +++++++++ tickets.js | 8 +++++-- 4 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 inbound.js diff --git a/inbound.js b/inbound.js new file mode 100644 index 0000000..204b8df --- /dev/null +++ b/inbound.js @@ -0,0 +1,67 @@ +// 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+@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* !/^\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(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/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; + const platform = rcpts.some(r => /@linkspin\.app$/.test(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 }; diff --git a/mailer.js b/mailer.js index f4afb1e..312ede4 100644 --- a/mailer.js +++ b/mailer.js @@ -44,6 +44,8 @@ async function send(to, subject, text, html, opts) { // html optional (2026-10-0 content }; if (unsub) msg.headers = { 'List-Unsubscribe': '<' + unsub + '>', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' }; + if (opts && opts.replyTo) msg.reply_to = { email: String(opts.replyTo) }; // help desk: replies thread back into the ticket + if (opts && opts.headers) msg.headers = Object.assign(msg.headers || {}, opts.headers); const body = JSON.stringify(msg); const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST', headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', diff --git a/server.js b/server.js index 1549b42..885bdd3 100644 --- a/server.js +++ b/server.js @@ -59,6 +59,7 @@ const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked S const refill = require('./refill'); const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20) const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) +const inbound = require('./inbound'); // help desk email intake: SendGrid Inbound Parse -> tickets (2026-10-16) const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16) const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16) const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) @@ -533,6 +534,7 @@ async function boot() { coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain }); tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram }); + inbound.init({ tickets }); supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' }); badge.init({ publicDir: PUBLIC_DIR }); gamestats.init({ dataDir: DATA_DIR }); @@ -2112,6 +2114,15 @@ const server = http.createServer(async (req, res) => { } // -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off + if (p === '/api/inbound/email' && req.method === 'POST') { // SendGrid Inbound Parse: secret key in the URL, always 200 once it matches + const k = inbound.key(); + if (!k || u.searchParams.get('k') !== k) { req.resume(); return json(res, 403, { error: 'forbidden' }); } + const chunks = []; let n = 0, tooBig = false; + await new Promise(done => { req.on('data', c => { n += c.length; if (n > 12e6) tooBig = true; else chunks.push(c); }); req.on('end', done); req.on('error', done); }); + if (tooBig) { console.log('inbound email: too big, dropped'); return json(res, 200, { ok: true }); } + try { console.log('inbound email:', await inbound.handle(Buffer.concat(chunks), req.headers['content-type'])); } catch (e) { console.error('inbound email', e.message); } + return json(res, 200, { ok: true }); + } if (p === '/api/telegram/support' && req.method === 'POST') { // the support bot's webhook: secret header checked inside, always 200 let b = {}; try { b = await readBody(req); } catch (e) {} try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); } diff --git a/tickets.js b/tickets.js index 7faf2a2..da3b8c8 100644 --- a/tickets.js +++ b/tickets.js @@ -204,12 +204,16 @@ function htmlMail(intro, blocks, link, linkLabel, brand) { + '

' + escH(linkLabel) + '

' + '

' + escH(b.name) + ' support. ' + escH(b.footer) + '

'; } +// email intake (2026-10-16): the requester's replies come back through SendGrid Inbound Parse. The reply-to carries the ticket +// ref (reply+iap-1042@help.instantadpay.com, reply+ls-1003@linkspin.app); Auto-Submitted keeps other robots from answering. +const replyTo = t => 'reply+' + String(t.ref).toLowerCase() + (t.platform === 'linkspin' ? '@linkspin.app' : '@help.instantadpay.com'); +const mailOpts = t => ({ transactional: true, replyTo: replyTo(t), headers: { 'Auto-Submitted': 'auto-replied' } }); function confirmRequester(t, m) { if (!deps.mailer || !deps.mailer.hasKey()) return; const link = linkFor(t), b = brandOf(t); const text = 'Hi' + (t.name ? ' ' + t.name : '') + ',\n\nWe got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.\n\n' + 'Subject: ' + t.subject + '\n\n' + m.body + '\n\nView the ticket or add more detail here (no sign-in needed):\n' + link + '\n\n' + b.name + ' support'; - deps.mailer.send(t.email, '[' + t.ref + '] ' + t.subject, text, htmlMail('We got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.', [m.body], link, 'View your ticket', b), { transactional: true }) + deps.mailer.send(t.email, '[' + t.ref + '] ' + t.subject, text, htmlMail('We got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.', [m.body], link, 'View your ticket', b), mailOpts(t)) .catch(e => console.error('support confirm mail', e.message)); } function notifyRequester(t, m) { @@ -220,7 +224,7 @@ function notifyRequester(t, m) { if (deps.mailer && deps.mailer.hasKey()) { const text = 'Hi' + (cur.name ? ' ' + cur.name : '') + ',\n\nMarty replied to your support ticket ' + cur.ref + ':\n\n' + bodies.join('\n\n---\n\n') + '\n\nRead the whole thread and reply here:\n' + link + (cur.platform === 'linkspin' ? '\n\nOr open Help in your LinkSpin Control Room: ' + b.help(cur.ref) : '') + '\n\n' + b.name + ' support'; - deps.mailer.send(cur.email, '[' + cur.ref + '] ' + cur.subject, text, htmlMail('Marty replied to your support ticket ' + cur.ref + ':', bodies, link, 'Read and reply', b), { transactional: true }) + deps.mailer.send(cur.email, '[' + cur.ref + '] ' + cur.subject, text, htmlMail('Marty replied to your support ticket ' + cur.ref + ':', bodies, link, 'Read and reply', b), mailOpts(cur)) .catch(e => console.error('support reply mail', e.message)); } // members also get it in their on-site inbox, as a notice: it never pops the sign-in modal. InstantAdPay tickets only: