Files
linkspin/mailer.js
T

60 lines
3.0 KiB
JavaScript

// Outbound mail via SendGrid v3 (domain-authenticated the site host).
// Key sources: SENDGRID_KEY env, else DATA_DIR/sendgrid.key in the volume.
// No key = email sign-in stays feature-flagged off in production.
const { SITE_HOST, SITE_URL } = require('./host');
const fs = require('fs');
const path = require('path');
const https = require('https');
let DATA_DIR = null;
const FROM = { email: 'no-reply@' + SITE_HOST, name: 'LinkSpin' };
function init(opts) { DATA_DIR = opts.dataDir; }
function key() {
if (process.env.SENDGRID_KEY) return process.env.SENDGRID_KEY.trim();
try { return fs.readFileSync(path.join(DATA_DIR, 'sendgrid.key'), 'utf8').trim(); } catch (e) { return ''; }
}
// A deployment must opt IN to sending mail. Default-deny, on purpose: on 2026-09-18 this
// test area mailed 95 real people because a seeded member list and a live key were both
// present and every send site dutifully checked hasKey() and got a yes.
const OUTBOUND = process.env.OUTBOUND === 'on';
function hasKey() { return OUTBOUND && !!key(); }
// Pre-launch mail gate (Marty, 2026-10-17: "no reminder emails or any kind of emails should be going out right now other
// than to let whitelisted testers log in"). LS_MAIL_MODE=codes-only (the default) lets ONLY sign-in codes through; every
// other send is dropped and logged. Set LS_MAIL_MODE=all at launch to open the rest.
const MAIL_MODE = String(process.env.LS_MAIL_MODE || 'codes-only').trim();
let held = 0;
function send(to, subject, text, opts) {
if (!OUTBOUND) return Promise.reject(new Error('outbound mail is off on this deployment (set OUTBOUND=on to allow it)'));
if (MAIL_MODE !== 'all' && !(opts && opts.code)) { held++; console.log('mail held (codes-only, #' + held + '): ' + String(subject).slice(0, 80)); return Promise.resolve(false); }
return new Promise((resolve, reject) => {
const body = JSON.stringify({
personalizations: [{ to: [{ email: to }] }],
from: FROM,
subject,
content: [{ type: 'text/plain', value: text }]
});
const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST',
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body) }, timeout: 15000 },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => res.statusCode < 300 ? resolve(true) : reject(new Error('sendgrid ' + res.statusCode + ': ' + d.slice(0, 200))));
});
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('sendgrid timeout')));
req.end(body);
});
}
function sendCode(to, code) {
return send(to, code + ' is your LinkSpin sign-in code',
'Your sign-in code is: ' + code + '\n\n'
+ 'It works for 15 minutes. If you did not request it, ignore this email.\n\n'
+ 'LinkSpin\nAdvertise and earn instantly. Locked in code, not promises.\n' + SITE_URL, { code: true });
}
module.exports = { init, hasKey, send, sendCode };