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+<ref>@ reply-to and Auto-Submitted
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+67
@@ -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+<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(/ /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 };
|
||||||
@@ -44,6 +44,8 @@ async function send(to, subject, text, html, opts) { // html optional (2026-10-0
|
|||||||
content
|
content
|
||||||
};
|
};
|
||||||
if (unsub) msg.headers = { 'List-Unsubscribe': '<' + unsub + '>', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' };
|
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 body = JSON.stringify(msg);
|
||||||
const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST',
|
const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST',
|
||||||
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
|
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked S
|
|||||||
const refill = require('./refill');
|
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 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 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 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 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)
|
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 });
|
coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig });
|
||||||
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
|
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
|
||||||
tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram });
|
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' });
|
supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' });
|
||||||
badge.init({ publicDir: PUBLIC_DIR });
|
badge.init({ publicDir: PUBLIC_DIR });
|
||||||
gamestats.init({ dataDir: DATA_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
|
// -- 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
|
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) {}
|
let b = {}; try { b = await readBody(req); } catch (e) {}
|
||||||
try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); }
|
try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); }
|
||||||
|
|||||||
+6
-2
@@ -204,12 +204,16 @@ function htmlMail(intro, blocks, link, linkLabel, brand) {
|
|||||||
+ '<p><a href="' + link + '" style="display:inline-block;background:#043b2f;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none">' + escH(linkLabel) + '</a></p>'
|
+ '<p><a href="' + link + '" style="display:inline-block;background:#043b2f;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none">' + escH(linkLabel) + '</a></p>'
|
||||||
+ '<p style="font-size:12px;color:#777">' + escH(b.name) + ' support. ' + escH(b.footer) + '</p></div>';
|
+ '<p style="font-size:12px;color:#777">' + escH(b.name) + ' support. ' + escH(b.footer) + '</p></div>';
|
||||||
}
|
}
|
||||||
|
// 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) {
|
function confirmRequester(t, m) {
|
||||||
if (!deps.mailer || !deps.mailer.hasKey()) return;
|
if (!deps.mailer || !deps.mailer.hasKey()) return;
|
||||||
const link = linkFor(t), b = brandOf(t);
|
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'
|
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';
|
+ '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));
|
.catch(e => console.error('support confirm mail', e.message));
|
||||||
}
|
}
|
||||||
function notifyRequester(t, m) {
|
function notifyRequester(t, m) {
|
||||||
@@ -220,7 +224,7 @@ function notifyRequester(t, m) {
|
|||||||
if (deps.mailer && deps.mailer.hasKey()) {
|
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')
|
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';
|
+ '\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));
|
.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:
|
// members also get it in their on-site inbox, as a notice: it never pops the sign-in modal. InstantAdPay tickets only:
|
||||||
|
|||||||
Reference in New Issue
Block a user