Gishen-ComingSoon/tools/waitlist-apps-script.gs
Kerod-Fresenbet-Gebremedhin2660 96283aed62 feat(waitlist): connect Google Sheets and add invisible spam protection
- Save waitlist and B2B submissions and notify the info inbox
- Add duplicate protection and hourly notification retries
- Require server-verified invisible Turnstile challenges
- Reject reused tokens with a lock-protected hash ledger
- Remove browser-only signup success fallback
- Add privacy notice, regression tests, and setup documentation
2026-11-09 10:59:42 +03:00

159 lines
8.6 KiB
JavaScript

// Owner: kiburtw1@gmail.com. Keep the spreadsheet private.
// Run setupWaitlist once, then deploy as Web app: Execute as Me, Access Anyone.
// Put the deployed /exec URL in ENDPOINT in index.html (never use /dev).
// Notifications are internal; this does not send subscriber campaigns or SMS.
// Set TURNSTILE_SECRET_KEY in Project Settings > Script properties, never in source.
const SPREADSHEET_ID = '14zuxfxr1XVNcc7Ld6b2aZcoVfNdKBR6n8GKWwqoVK_k';
const NOTIFY = 'info@gishenpharmacy.org';
const PAGE = 'https://gishenpharmacy.org/';
const HEADERS = ['createdAt', 'name', 'phone', 'email', 'channel', 'locale', 'page', 'notificationStatus', 'notifiedAt'];
const B2B_HEADERS = ['createdAt', 'institution', 'type', 'contact', 'phone', 'email', 'orders', 'page', 'status', 'notificationStatus', 'notifiedAt'];
const B2B_TYPES = ['Hospital', 'Clinic', 'Company', 'NGO', 'Pharmacy', 'Other'];
// Fail closed: no unverified request may write a row or consume the email quota.
function verifyBotToken_(token, action) {
if (typeof token !== 'string' || !token || token.length > 2048) return false;
const secret = PropertiesService.getScriptProperties().getProperty('TURNSTILE_SECRET_KEY');
if (!secret) return false;
try {
const response = UrlFetchApp.fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'post', contentType: 'application/json',
payload: JSON.stringify({ secret: secret, response: token }),
muteHttpExceptions: true, followRedirects: false,
});
if (response.getResponseCode() !== 200) return false;
const result = JSON.parse(response.getContentText());
return result.success === true && result.hostname === 'gishenpharmacy.org' && result.action === action;
} catch (err) { return false; }
}
// Called only while holding the script lock. Store hashes, never raw tokens.
// This also blocks replay if Siteverify repeats a successful response.
function consumeBotToken_(token) {
const properties = PropertiesService.getScriptProperties();
const hash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, token, Utilities.Charset.UTF_8)
.map(byte => (byte & 255).toString(16).padStart(2, '0')).join('');
const key = 'TURNSTILE_USED_' + hash;
const now = Date.now();
if (Number(properties.getProperty(key) || 0) > now) return false;
// Keep only the replay window; do not touch secret/config properties.
for (const [name, expiry] of Object.entries(properties.getProperties())) {
if (name.startsWith('TURNSTILE_USED_') && (!Number.isFinite(Number(expiry)) || Number(expiry) <= now)) {
properties.deleteProperty(name);
}
}
properties.setProperty(key, String(now + 10 * 60 * 1000));
return true;
}
function spreadsheet_() { return SpreadsheetApp.openById(SPREADSHEET_ID); }
function json_(data) { return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(ContentService.MimeType.JSON); }
function clean_(value, limit) { return String(value || '').trim().slice(0, limit); }
// User-controlled cells must stay text, never become spreadsheet formulas.
function text_(value) { return /^[=+\-@\t\r]/.test(value) ? "'" + value : value; }
function raw_(value) { return String(value || '').replace(/^'/, ''); }
function phone_(value) { return /^\+\d{8,15}$/.test(value || '') ? String(value) : ''; }
function email_(value) {
const email = clean_(value, 200).toLowerCase();
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) ? email : '';
}
function sheet_(name, headers) {
const ss = spreadsheet_();
const sheet = ss.getSheetByName(name) || ss.insertSheet(name);
if (sheet.getLastRow() === 0) {
sheet.appendRow(headers);
sheet.setFrozenRows(1);
sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold');
}
return sheet;
}
function setupWaitlist() {
sheet_('Waitlist', HEADERS);
sheet_('Institutions', B2B_HEADERS);
if (!ScriptApp.getProjectTriggers().some(t => t.getHandlerFunction() === 'retryNotifications')) {
ScriptApp.newTrigger('retryNotifications').timeBased().everyHours(1).create();
}
console.log('Waitlist ready. Notifications go to ' + NOTIFY + '. Remaining daily email quota: ' + MailApp.getRemainingDailyQuota());
}
// Public endpoint exposes only a count, never names or contact details.
function doGet() {
return json_({ count: Math.max(sheet_('Waitlist', HEADERS).getLastRow() - 1, 0) });
}
function notify_(sheet, row, b2b) {
const statusCol = b2b ? 10 : 8;
if (sheet.getRange(row, statusCol).getValue() === 'sent') return;
if (MailApp.getRemainingDailyQuota() < 1) return; // Keep pending for the hourly retry.
const data = sheet.getRange(row, 1, 1, statusCol - 1).getValues()[0].map(raw_);
const subject = b2b ? 'New Gishen institution signup: ' + data[1] : 'New Gishen waitlist signup: ' + data[1];
const body = b2b
? ['Institution: ' + data[1], 'Type: ' + data[2], 'Contact: ' + data[3], 'Phone: ' + data[4], 'Email: ' + data[5], 'Usual orders: ' + data[6]]
: ['Name: ' + data[1], 'Phone: ' + data[2], 'Email: ' + data[3], 'Preferred channel: ' + data[4]];
body.push('', 'Review the private list: https://docs.google.com/spreadsheets/d/' + SPREADSHEET_ID + '/edit');
try {
MailApp.sendEmail({ to: NOTIFY, subject: subject.replace(/[\r\n]/g, ' '), body: body.join('\n'), name: 'Gishen website', replyTo: NOTIFY });
sheet.getRange(row, statusCol, 1, 2).setValues([['sent', new Date()]]);
} catch (err) {
// A notification failure must not discard an already-saved signup.
console.error('Notification pending; the hourly retry will try again.');
}
}
function retryNotifications() {
const lock = LockService.getScriptLock();
if (!lock.tryLock(1000)) return;
try {
let remaining = Math.min(MailApp.getRemainingDailyQuota(), 20);
for (const config of [['Waitlist', HEADERS, false, 8], ['Institutions', B2B_HEADERS, true, 10]]) {
const sheet = sheet_(config[0], config[1]);
if (sheet.getLastRow() < 2) continue;
const statuses = sheet.getRange(2, config[3], sheet.getLastRow() - 1, 1).getValues();
for (let i = 0; i < statuses.length && remaining > 0; i++) {
if (statuses[i][0] !== 'sent') { notify_(sheet, i + 2, config[2]); remaining--; }
}
}
} finally { lock.releaseLock(); }
}
function doPost(event) {
try {
if (!event || !event.postData || event.postData.contents.length > 12000) return json_({ ok: false, error: 'invalid' });
const data = JSON.parse(event.postData.contents || '{}');
if (!data || typeof data !== 'object' || Array.isArray(data)) return json_({ ok: false, error: 'invalid' });
if (data.company) return json_({ ok: true }); // Hidden honeypot, no storage or email.
const b2b = data.type === 'b2b';
if (data.type && !b2b) return json_({ ok: false, error: 'invalid' });
const name = clean_(data.name, 120), phone = phone_(data.phone), email = email_(data.email);
const org = clean_(data.institution, 160);
if (name.length < 2 || (b2b ? org.length < 2 || !phone || (data.email && !email) : !phone && !email)) return json_({ ok: false, error: 'invalid' });
if (!verifyBotToken_(data.turnstileToken, b2b ? 'b2b' : 'waitlist')) return json_({ ok: false, error: 'captcha' });
const lock = LockService.getScriptLock();
lock.waitLock(10000);
try {
if (!consumeBotToken_(data.turnstileToken)) return json_({ ok: false, error: 'captcha' });
const sheet = sheet_(b2b ? 'Institutions' : 'Waitlist', b2b ? B2B_HEADERS : HEADERS);
const rows = sheet.getLastRow() > 1 ? sheet.getRange(2, 1, sheet.getLastRow() - 1, b2b ? 6 : 4).getValues() : [];
const existing = rows.findIndex(row => b2b
? raw_(row[1]).toLowerCase() === org.toLowerCase() && raw_(row[4]) === phone
: (phone && raw_(row[2]) === phone) || (email && raw_(row[3]).toLowerCase() === email));
let row;
if (existing >= 0) row = existing + 2;
else {
const values = b2b
? [new Date(), text_(org), B2B_TYPES.includes(data.kind) ? data.kind : 'Other', text_(name), text_(phone), text_(email), text_(clean_(data.orders, 500)), PAGE, 'new', 'pending', '']
: [new Date(), text_(name), text_(phone), text_(email), data.channel === 'email' ? 'email' : 'sms', text_(clean_(data.locale, 20)), PAGE, 'pending', ''];
sheet.appendRow(values);
row = sheet.getLastRow();
}
// Saving is the success condition; mail failures remain visible and retryable.
try { notify_(sheet, row, b2b); } catch (err) { console.error('Notification pending.'); }
return json_({ ok: true, duplicate: existing >= 0, count: Math.max(sheet_('Waitlist', HEADERS).getLastRow() - 1, 0) });
} finally { lock.releaseLock(); }
} catch (err) {
console.error('Unable to save signup.');
return json_({ ok: false, error: 'server' });
}
}