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
This commit is contained in:
Kerod-Fresenbet-Gebremedhin2660 2026-11-09 10:59:42 +03:00
parent d67fdb33af
commit 96283aed62
6 changed files with 392 additions and 74 deletions

View File

@ -10,8 +10,26 @@ Deploy it to any static host (Vercel, Netlify, nginx) with the repo root as the
## Waitlist
The form takes a phone number (SMS, the default) or an email, then asks for a name. Signups go to a Google Sheet through `tools/waitlist-apps-script.gs`, which also emails a notification for each one. Until `ENDPOINT` in `index.html` is set, signups are only saved in the visitor's browser.
The form takes a phone number (SMS, the default) or an email, then asks for a name. The live `ENDPOINT` posts to `tools/waitlist-apps-script.gs`, which saves to a private Google Sheet owned by `kiburtw1@gmail.com` and sends an internal notification to `info@gishenpharmacy.org`. The page only confirms success after a server-side save; there is no browser-only success fallback.
Individuals and institutions are stored in separate tabs. Duplicate contacts do not create extra waitlist rows or repeat already-sent notifications. Notification failures and Google email quota exhaustion leave rows marked `pending`; an hourly trigger retries them. User-entered values are protected against spreadsheet formula injection.
Keep the Sheet private. The anonymous web app runs as the owner and exposes only a signup count on GET, not contact details. Owner access, links, deployment notes and remaining human tasks are in [TASKS.md](TASKS.md). Saving script changes is not enough: update its existing web-app deployment to a new version, preserving the `/exec` URL. Run `setupWaitlist` once when provisioning a new project; it creates the tabs and hourly retry trigger.
Run backend regression checks: `node --test tools/waitlist.test.mjs`.
This collects a waitlist; it does not send welcome emails, SMS or launch campaigns automatically.
## Invisible spam protection
Both forms obtain a fresh Cloudflare Turnstile token on final submission. The widget is configured in **Invisible** mode for `gishenpharmacy.org`, so visitors do not see a checkbox or puzzle. No email or phone ownership verification is performed.
Apps Script validates every token with Cloudflare before writing to Sheets or sending notifications. It requires a successful verification, the exact `gishenpharmacy.org` hostname and the matching `waitlist` or `b2b` action. A script-lock-protected hash ledger also prevents token reuse even if the provider repeats a successful response; hashes expire after ten minutes and are pruned on subsequent accepted requests. Raw tokens are never stored. Missing, expired/reused, invalid and wrong-site tokens are rejected. Verification outages fail closed, with a retry/contact message; there is no unprotected submission fallback.
Only the public sitekey belongs in `index.html`. The secret is stored as `TURNSTILE_SECRET_KEY` in Apps Script **Project Settings → Script properties**. Never put it in HTML, source control or logs. If replacing the widget, update both its public sitekey and that private property, then test both forms. Saving server code is not enough: update the existing web-app deployment to a new version.
`privacy.html` discloses this use and links Cloudflare's Turnstile Privacy Addendum, as required for invisible mode. Keep it deployed and linked from the footer. This bot check is not a substitute for rate limiting and does not prove ownership of a submitted contact address.
## B2B onboarding
Institutions sign up through the form in the B2B section (institution, type, contact person, phone, optional email and usual orders). It posts to the same Apps Script endpoint with `type: 'b2b'`, which adds a row to an "Institutions" tab and emails `NOTIFY`. Until `ENDPOINT` is set, the form opens a pre-filled email to `b2b@gishenpharmacy.org` instead. Institutions can also call `+251 930 099 850`. Setting up the inbox is tracked in [TASKS.md](TASKS.md).
Institutions sign up through the form in the B2B section (institution, type, contact person, phone, optional email and usual orders). It posts to the same Apps Script endpoint with `type: 'b2b'`, which adds a row to an "Institutions" tab and emails `NOTIFY`. Without an endpoint the B2B form falls back to opening a pre-filled email. Direct mail to `b2b@gishenpharmacy.org` is also copied to `info@`, retaining both mailboxes. Institutions can call `+251 930 099 850`; the team must confirm that this number is staffed and ensure the promised one-working-day response.

View File

@ -4,8 +4,35 @@
The coming-soon page asks people to email or call Gishen. Before we share the link:
- [ ] Create the mailboxes the page links to: `b2b@gishenpharmacy.org` (B2B onboarding CTA) and `info@gishenpharmacy.org` (footer contact). If only one inbox is set up, make the other an alias that forwards to it.
- [ ] Forward all contact and inquiry mail (B2B onboarding, general contact, waitlist notifications) to that inbox, and make sure someone on the Gishen team reads it daily. The page promises a reply within one working day.
- [x] Create `b2b@gishenpharmacy.org` and `info@gishenpharmacy.org`. Mail DNS, SPF, DKIM, DMARC and mail-client TLS are configured; Kerod verified end-to-end mail delivery.
- [x] Route inquiries to `info@gishenpharmacy.org`: B2B mail is copied there while retaining the B2B mailbox; both web forms send their internal notifications there.
- [ ] Assign someone on the Gishen team to read `info@` daily and respond within one working day, as promised on the page.
- [ ] Confirm `+251 930 099 850` is answered for B2B onboarding calls, or send us the right number to put on the page.
- [ ] Deploy `tools/waitlist-apps-script.gs` (steps are at the top of the file). Set `NOTIFY` to the inbox above, then paste the `/exec` URL into `ENDPOINT` in `index.html`. Until then, signups only save in the visitor's browser.
- [ ] Send a test email to `b2b@gishenpharmacy.org` and do one test waitlist signup to confirm both reach the inbox.
- [x] Deploy `tools/waitlist-apps-script.gs`, owned by `kiburtw1@gmail.com`, with `NOTIFY=info@gishenpharmacy.org`. The live `/exec` URL is configured in `index.html` and deployed to the VPS.
- [x] Verify the email, phone-only and B2B forms on the live page. All three saved successfully and their notification messages arrived in `info@`. Kerod also confirmed end-to-end mailbox delivery.
## Operations
- Private Sheet: [Gishen launch waitlist & B2B inquiries](https://docs.google.com/spreadsheets/d/14zuxfxr1XVNcc7Ld6b2aZcoVfNdKBR6n8GKWwqoVK_k/edit#gid=38651670). Sharing was verified as "Private to only me" under `kiburtw1@gmail.com`. Grant individual team members access as needed; never make the contact list public.
- Apps Script: [Gishen website — Waitlist & B2B](https://script.google.com/home/projects/1h9MhmjgO67uSBHP3juTBz1WBSknQ10lc3049wtaRCNzQidiVxcAXlKob/edit).
- The `Waitlist` tab stores individuals; `Institutions` stores B2B inquiries. `notificationStatus` records whether the internal email was sent. Pending notifications retry hourly.
- Notifications are sent by the owning Google account, with replies directed to `info@`. Google email quotas apply; a delayed notification does not discard a saved signup.
- This is signup collection only. Subscriber launch emails and SMS campaigns are not automatically sent. Plan the launch communication separately, honoring the page's promise of one launch message.
- Updating Apps Script code requires updating the existing deployment to a new version; saving the editor alone does not update `/exec`.
- Run backend regression checks with `node --test tools/waitlist.test.mjs`.
- Three clearly labelled `TEST — Gishen ... setup 2026-11-09` records remain as verification examples: two in `Waitlist` and one in `Institutions`. Exclude/delete these test records before using the lists for real outreach. Their notifications were received in `info@`.
- The previous live page is recoverable at `/var/backups/gishen-waitlist-20261109-Jjqo59/index.html` on the production VPS.
## Silent CAPTCHA configuration
- [x] Deployed Apps Script **Version 3** to the existing `/exec` URL on 2026-11-09, with invisible Turnstile verification and the independent replay guard.
- [x] Verified in Safari: both forms succeed without visible challenges; missing/invalid tokens, wrong-form tokens and replayed valid tokens are rejected. Existing labelled test contacts were reused, and the signup count did not change during these checks.
- [x] All 13 backend regression tests pass, including failure-closed behavior, duplicate protection and replay rejection even if the provider repeats success.
- Cloudflare account: the Yaltopia-Gishen profile's existing account. Widget: `Gishen .org waitlist — invisible`, restricted to `gishenpharmacy.org`; invisible mode, no pre-clearance.
- Public sitekey: `0x4AAAAAAF5kBCYJ6Vhl5ok7`. The matching secret is stored only in Apps Script's `TURNSTILE_SECRET_KEY` Script property, not in this repository.
- Both final form submissions require a fresh token. The server checks hostname and the appropriate `waitlist`/`b2b` action before storing or emailing. Invalid/missing/replayed tokens must fail without changing the lists.
- Token reuse is also blocked by a script-lock-protected hash ledger, independent of the provider response. It stores only SHA-256 hashes for a ten-minute replay window; expired hash entries are pruned on subsequent accepted requests. Do not delete active replay properties to bypass a failed challenge.
- No email/phone ownership check is enabled. If verification cannot finish, visitors can retry or contact Gishen directly; there is no unprotected form bypass.
- Deploy `privacy.html` alongside the page; its footer link and Cloudflare Privacy Addendum disclosure are required for invisible mode.
- Pre-captcha landing-page backup: `/var/backups/gishen-turnstile-20261109.XmlNVe/index.html` on the production server. Reverting HTML alone is not sufficient: the protected backend still requires a token. Coordinate a complete rollback of the Apps Script deployment if needed; Version 1 is the earlier unprotected backend.

View File

@ -546,14 +546,50 @@
<div class="legal">
<span>© <span id="year">2026</span> Gishen Pharmacy · <span class="eth">ግሸን መድሃኒት ቤት</span> · All rights reserved</span>
<span>Powered by <a href="https://yaltopiatech.com" rel="noopener" target="_blank">Yaltopia Tech</a></span>
<span><a href="/privacy.html">Privacy &amp; bot protection</a></span>
</div>
</div>
</footer>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" async defer></script>
<script>
// Google Apps Script web app URL (…/exec) from tools/waitlist-apps-script.gs. Each signup becomes a row in the sheet.
// While it's empty, signups are kept only in this browser's localStorage, so don't share the page until it's set.
const ENDPOINT = '';
// Only a confirmed server-side save counts as a successful signup.
const ENDPOINT = 'https://script.google.com/macros/s/AKfycbz6C1LsMLbrCuqlE58FBU27bv9guALVNbIOVLA24exb1jPAgDLZ0rQeYJKo8CHEbRMR/exec';
const TURNSTILE_SITE_KEY = '0x4AAAAAAF5kBCYJ6Vhl5ok7';
// Invisible, one-use challenge on final submission; no checkbox or contact OTP.
async function botToken(action) {
const start = Date.now();
while (!window.turnstile) {
if (Date.now() - start > 10000) throw new Error('captcha');
await new Promise((resolve) => setTimeout(resolve, 100));
}
return new Promise((resolve, reject) => {
const container = document.createElement('div');
document.body.append(container);
let widget, timer, finished = false;
const finish = (error, token) => {
if (finished) return;
finished = true; clearTimeout(timer);
try { if (widget !== undefined) window.turnstile.remove(widget); } catch {}
container.remove();
if (error) reject(new Error('captcha')); else resolve(token);
};
timer = setTimeout(() => finish(true), 30000);
try {
widget = window.turnstile.render(container, {
sitekey: TURNSTILE_SITE_KEY, action, execution: 'execute',
'response-field': false, retry: 'never', 'refresh-expired': 'manual',
callback: (token) => finish(!token, token),
'error-callback': () => { finish(true); return true; },
'expired-callback': () => finish(true), 'timeout-callback': () => finish(true),
});
window.turnstile.execute(widget);
} catch { finish(true); }
});
}
const botError = 'The security check could not finish. Please retry, or contact info@gishenpharmacy.org.';
const $ = (id) => document.getElementById(id);
$('year').textContent = new Date().getFullYear();
@ -649,21 +685,20 @@
btn.disabled = true;
try {
if (ENDPOINT) {
const turnstileToken = await botToken('waitlist');
// text/plain keeps this a "simple" request: Apps Script can't answer a CORS preflight.
const res = await fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ ...r.data, page: location.href, company: $('company').value }) });
const res = await fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ ...r.data, page: location.href, company: $('company').value, turnstileToken }) });
const out = await res.json().catch(() => ({}));
if (!res.ok || !out.ok) throw new Error(out.error || res.status);
waiting = Number.isFinite(out.count) ? out.count : waiting + (out.duplicate ? 0 : 1);
} else {
let list = []; try { list = JSON.parse(localStorage.getItem('waitlist') || '[]'); } catch {}
if (!list.some((x) => (r.data.email && x.email === r.data.email) || (r.data.phone && x.phone === r.data.phone))) list.push(r.data);
try { localStorage.setItem('waitlist', JSON.stringify(list)); } catch {}
console.warn('Waitlist ENDPOINT not set: signup saved in this browser only.', r.data);
throw new Error('Waitlist is not configured');
}
const first = r.data.name.split(' ')[0];
waiting += 1; showWaiting(true);
showWaiting(true);
form.parentElement.innerHTML = `<div class="done" role="status"><div class="tick"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg></div><div><h3>You're on the list, ${first.replace(/[<>&"]/g, '')}.</h3><p>We'll ${channel === 'sms' ? 'text' : 'email'} you the day Gishen opens online.</p></div></div>`;
} catch {
err.textContent = 'Something went wrong. Please try again, or call us on +251 930 099 850.';
} catch (error) {
err.textContent = error.message === 'captcha' ? botError : 'Something went wrong. Please try again, or call us on +251 930 099 850.';
btn.disabled = false;
}
});
@ -686,12 +721,13 @@
}
bBtn.disabled = true;
try {
const res = await fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify(data) });
const turnstileToken = await botToken('b2b');
const res = await fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ ...data, turnstileToken }) });
const out = await res.json().catch(() => ({}));
if (!res.ok || !out.ok) throw new Error(out.error || res.status);
bform.innerHTML = `<div class="done" role="status"><div class="tick"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg></div><div><h3>Thanks, ${data.institution.replace(/[<>&"]/g, '')} is signed up.</h3><p>Our B2B team will call you within one working day.</p></div></div>`;
} catch {
bErr.textContent = 'Something went wrong. Please try again, or call us on +251 930 099 850.';
} catch (error) {
bErr.textContent = error.message === 'captcha' ? botError : 'Something went wrong. Please try again, or call us on +251 930 099 850.';
bBtn.disabled = false;
}
});

22
privacy.html Normal file
View File

@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Waitlist privacy | Gishen Pharmacy</title>
<meta name="description" content="How Gishen handles coming-soon waitlist details and protects its forms from automated spam." />
<style>body{margin:0;background:#f6f7f2;color:#141414;font:17px/1.7 system-ui,sans-serif}main{max-width:720px;margin:auto;padding:48px 24px}a{color:#315f29}h1,h2{line-height:1.2}h2{margin-top:32px;font-size:22px}</style>
</head>
<body><main>
<a href="/">← Back to Gishen</a>
<h1>Waitlist privacy &amp; bot protection</h1>
<p>Updated 9 November 2026. This notice covers the coming-soon forms at gishenpharmacy.org.</p>
<h2>Details you submit</h2>
<p>The waitlist collects your name and your chosen email address or phone number so Gishen can contact you when the online store opens. The institution form also collects the institution name, type, contact person and optional usual-order details to handle your B2B inquiry. Do not submit prescriptions or patient health records through these forms.</p>
<h2>Storage and notifications</h2>
<p>Submissions are stored in a private Google Sheet and sent as internal notifications to the Gishen team at info@gishenpharmacy.org. Google provides the spreadsheet and submission-processing services. To ask about your details or request removal, email <a href="mailto:info@gishenpharmacy.org">info@gishenpharmacy.org</a>.</p>
<h2>Silent spam protection</h2>
<p>These forms use Cloudflare Turnstile in invisible mode to distinguish genuine visitors from automated submissions. Cloudflare processes browser and device signals for this security check. Turnstile is subject to the <a href="https://www.cloudflare.com/turnstile-privacy-policy/" rel="noopener" target="_blank">Cloudflare Turnstile Privacy Addendum</a>. No email code or phone code is required.</p>
<p>If the security check cannot finish, your submission will not be accepted. You can retry or contact the team by email or telephone instead.</p>
</main></body>
</html>

View File

@ -1,69 +1,158 @@
// Gishen waitlist backend: a Google Sheet + this Apps Script.
// Setup: create a Sheet → Extensions → Apps Script → paste this file → Deploy → New deployment →
// Web app, Execute as "Me", Access "Anyone" → copy the /exec URL into ENDPOINT in index.html.
// NOTIFY: every signup is also emailed here. Set it to the inbox Kerod sets up (see TASKS.md).
// 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 HEADERS = ['createdAt', 'name', 'phone', 'email', 'channel', 'locale', 'page'];
function sheet_() {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
if (sh.getLastRow() === 0) sh.appendRow(HEADERS);
return sh;
}
const json_ = (o) => ContentService.createTextOutput(JSON.stringify(o)).setMimeType(ContentService.MimeType.JSON);
// GET → { count } for the "N people are already waiting" pill.
function doGet() {
return json_({ count: Math.max(sheet_().getLastRow() - 1, 0) });
}
const B2B_HEADERS = ['createdAt', 'institution', 'type', 'contact', 'phone', 'email', 'orders', 'page', 'status'];
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'];
// Institution sign-ups live on their own tab, so the waitlist count (first tab) stays right.
function b2b_(d) {
const org = String(d.institution || '').trim().slice(0, 160);
const name = String(d.name || '').trim().slice(0, 120);
const phone = /^\+\d{8,15}$/.test(d.phone || '') ? d.phone : '';
const email = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.email || '') ? String(d.email).toLowerCase().slice(0, 200) : '';
if (org.length < 2 || name.length < 2 || !phone) return json_({ ok: false, error: 'invalid' });
const kind = B2B_TYPES.includes(d.kind) ? d.kind : 'Other';
const orders = String(d.orders || '').slice(0, 500);
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getSheetByName('Institutions') || ss.insertSheet('Institutions');
if (sh.getLastRow() === 0) sh.appendRow(B2B_HEADERS);
sh.appendRow([new Date(), org, kind, name, "'" + phone, email, orders, String(d.page || '').slice(0, 200), 'new']);
if (NOTIFY) MailApp.sendEmail(NOTIFY, 'New institution sign-up: ' + org, [org + ' (' + kind + ')', name, phone, email, orders].filter(String).join('\n'));
return json_({ ok: true });
// 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; }
}
function doPost(e) {
try {
const d = JSON.parse(e.postData.contents || '{}');
if (d.company) return json_({ ok: true }); // honeypot: bots fill the hidden field
if (d.type === 'b2b') return b2b_(d);
const name = String(d.name || '').trim().slice(0, 120);
const phone = /^\+\d{8,15}$/.test(d.phone || '') ? d.phone : '';
const email = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.email || '') ? String(d.email).toLowerCase().slice(0, 200) : '';
if (name.length < 2 || (!phone && !email)) return json_({ ok: false, error: 'invalid' });
// 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 {
const sh = sheet_();
const rows = sh.getLastRow() > 1 ? sh.getRange(2, 3, sh.getLastRow() - 1, 2).getValues() : [];
// Prefix with ' so Sheets keeps +251… as text, not a number.
const dup = rows.some(([p, m]) => (phone && String(p).replace(/^'/, '') === phone) || (email && m === email));
if (!dup) {
sh.appendRow([new Date(), name, phone ? "'" + phone : '', email, d.channel === 'email' ? 'email' : 'sms', String(d.locale || '').slice(0, 20), String(d.page || '').slice(0, 200)]);
if (NOTIFY) MailApp.sendEmail(NOTIFY, 'New Gishen waitlist signup: ' + name, [name, phone, email].filter(String).join('\n'));
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();
}
} finally {
lock.releaseLock();
}
return json_({ ok: true });
// 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' });
}
}

126
tools/waitlist.test.mjs Normal file
View File

@ -0,0 +1,126 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
function backend() {
const sheets = new Map(), mails = [], triggers = [];
let quota = 100, failMail = false;
let sequence = 0, secret = 'unit-test-secret', verifyStatus = 200, verifyOverride;
const usedTokens = new Set(), verifications = [];
const properties = new Map();
const propertyStore = {getProperty:key=>key==='TURNSTILE_SECRET_KEY'?secret:(properties.get(key)??null),
getProperties:()=>Object.fromEntries(properties),setProperty:(key,value)=>properties.set(key,value),deleteProperty:key=>properties.delete(key)};
function sheet(name) {
const rows = [];
const sh = { rows, appendRow: row => rows.push([...row]), getLastRow: () => rows.length,
setFrozenRows() {}, getRange(r,c,n=1,m=1) { return {
getValue: () => rows[r-1]?.[c-1],
getValues: () => Array.from({length:n}, (_,i)=>Array.from({length:m}, (_,j)=>rows[r+i-1]?.[c+j-1]??'')),
setValues(values) { values.forEach((v,i)=>v.forEach((cell,j)=>{rows[r+i-1]??=[];rows[r+i-1][c+j-1]=cell;})); },
setFontWeight() {},
}; } };
sheets.set(name, sh); return sh;
}
const spreadsheet = { getSheetByName:n=>sheets.get(n), insertSheet:sheet };
const context = vm.createContext({ console:{log(){},error(){}},
SpreadsheetApp:{openById:()=>spreadsheet},
ContentService:{MimeType:{JSON:'json'},createTextOutput:s=>({setMimeType:()=>JSON.parse(s)})},
LockService:{getScriptLock:()=>({tryLock:()=>true,waitLock(){},releaseLock(){}})},
ScriptApp:{getProjectTriggers:()=>triggers,newTrigger:handler=>({timeBased:()=>({everyHours:()=>({create:()=>triggers.push({getHandlerFunction:()=>handler})})})})},
MailApp:{getRemainingDailyQuota:()=>quota,sendEmail:message=>{if(failMail)throw Error('temporary');mails.push(message);quota--; }},
PropertiesService:{getScriptProperties:()=>propertyStore},
Utilities:{DigestAlgorithm:{SHA_256:'sha256'},Charset:{UTF_8:'utf8'},computeDigest:(algorithm,text)=>[...createHash(algorithm).update(text).digest()]},
UrlFetchApp:{fetch:(url,options)=>{
const data=JSON.parse(options.payload); verifications.push({url,options});
const valid=/^(valid|b2b)-/.test(data.response)&&!usedTokens.has(data.response);
usedTokens.add(data.response);
const result=verifyOverride??{success:valid,hostname:'gishenpharmacy.org',action:data.response.startsWith('b2b-')?'b2b':'waitlist'};
return {getResponseCode:()=>verifyStatus,getContentText:()=>JSON.stringify(result)};
}},
});
vm.runInContext(readFileSync(new URL('./waitlist-apps-script.gs',import.meta.url),'utf8'),context);
context.setupWaitlist();
return {context,sheets,mails,triggers,verifications,properties,post:data=>context.doPost({postData:{contents:JSON.stringify({turnstileToken:(data.type==='b2b'?'b2b-':'valid-')+(++sequence),...data})}}),
quota:value=>quota=value,fail:value=>failMail=value,secret:value=>secret=value,
verification:(result,status=200)=>{verifyOverride=result;verifyStatus=status;}};
}
const signup={name:'Setup test',email:'setup@example.com',channel:'email'};
test('saves signup and notifies the approved inbox; duplicate is idempotent',()=>{
const b=backend(); assert.equal(b.post(signup).ok,true); assert.equal(b.post(signup).duplicate,true);
assert.equal(b.sheets.get('Waitlist').rows.length,2); assert.equal(b.mails.length,1);
assert.equal(b.mails[0].to,'info@gishenpharmacy.org'); assert.equal(b.context.doGet().count,1);
});
test('saves SMS signup and escapes spreadsheet formulas',()=>{
const b=backend(); assert.equal(b.post({name:'=IMPORTXML("x")',phone:'+251911234567'}).ok,true);
const row=b.sheets.get('Waitlist').rows[1]; assert.equal(row[1][0],"'"); assert.equal(row[2],"'+251911234567");
});
test('institution signups are separate and deduplicated',()=>{
const b=backend(), data={type:'b2b',institution:'Test clinic',kind:'Clinic',name:'Contact',phone:'+251911234567'};
assert.equal(b.post(data).ok,true); assert.equal(b.post(data).duplicate,true);
assert.equal(b.sheets.get('Institutions').rows.length,2); assert.equal(b.context.doGet().count,0);
});
test('invalid data and honeypot never save or send',()=>{
const b=backend(); assert.equal(b.post({name:'x'}).ok,false); assert.equal(b.post({...signup,company:'bot'}).ok,true);
assert.equal(b.context.doGet().count,0); assert.equal(b.mails.length,0);
assert.equal(b.context.doPost({postData:{contents:'bad json'}}).ok,false);
});
test('mail failure keeps signup saved; hourly retry recovers',()=>{
const b=backend(); b.fail(true); assert.equal(b.post(signup).ok,true);
assert.equal(b.sheets.get('Waitlist').rows[1][7],'pending'); b.fail(false); b.context.retryNotifications();
assert.equal(b.sheets.get('Waitlist').rows[1][7],'sent'); assert.equal(b.mails.length,1);
});
test('exhausted email quota does not lose signup; setup trigger is idempotent',()=>{
const b=backend(); b.quota(0); assert.equal(b.post(signup).ok,true); assert.equal(b.mails.length,0);
b.context.setupWaitlist(); assert.equal(b.triggers.length,1); b.quota(1); b.context.retryNotifications(); assert.equal(b.mails.length,1);
});
test('missing, malformed and oversized bot tokens cannot save or send',()=>{
const b=backend();
for(const turnstileToken of [undefined,'',{},'x'.repeat(2049)])assert.equal(b.post({...signup,turnstileToken}).error,'captcha');
assert.equal(b.context.doGet().count,0);assert.equal(b.mails.length,0);assert.equal(b.verifications.length,0);
});
test('invalid and reused tokens cannot save or send',()=>{
const b=backend();assert.equal(b.post({...signup,turnstileToken:'invalid'}).error,'captcha');
assert.equal(b.post({...signup,turnstileToken:'valid-once'}).ok,true);
assert.equal(b.post({...signup,email:'second@example.com',turnstileToken:'valid-once'}).error,'captcha');
assert.equal(b.context.doGet().count,1);assert.equal(b.mails.length,1);
});
test('verification enforces exact site hostname and form action',()=>{
const b=backend();
for(const result of [{success:true,hostname:'attacker.example',action:'waitlist'},
{success:true,hostname:'gishenpharmacy.org',action:'b2b'},
{success:'true',hostname:'gishenpharmacy.org',action:'waitlist'}]){
b.verification(result);assert.equal(b.post(signup).error,'captcha');
}
assert.equal(b.context.doGet().count,0);assert.equal(b.mails.length,0);
});
test('missing secret and upstream failures fail closed',()=>{
const b=backend();b.secret('');assert.equal(b.post(signup).error,'captcha');
b.secret('unit-test-secret');b.verification({success:true,hostname:'gishenpharmacy.org',action:'waitlist'},503);
assert.equal(b.post(signup).error,'captcha');assert.equal(b.context.doGet().count,0);assert.equal(b.mails.length,0);
});
test('both forms use siteverify before storage; no untrusted redirect is followed',()=>{
const b=backend();assert.equal(b.post(signup).ok,true);
assert.equal(b.post({type:'b2b',institution:'Test clinic',name:'Contact',phone:'+251911234567'}).ok,true);
assert.equal(b.verifications.length,2);
for(const call of b.verifications){
assert.equal(call.url,'https://challenges.cloudflare.com/turnstile/v0/siteverify');
assert.equal(call.options.followRedirects,false);
assert.equal(JSON.parse(call.options.payload).secret,'unit-test-secret');
}
});
test('durable server guard rejects replay even if provider repeats success',()=>{
const b=backend();b.verification({success:true,hostname:'gishenpharmacy.org',action:'waitlist'});
const turnstileToken='valid-replayed-provider-success';
assert.equal(b.post({...signup,turnstileToken}).ok,true);
assert.equal(b.post({...signup,email:'second@example.com',turnstileToken}).error,'captcha');
assert.equal(b.context.doGet().count,1);assert.equal(b.mails.length,1);
assert.equal([...b.properties.keys()].every(key=>/^TURNSTILE_USED_[a-f0-9]{64}$/.test(key)),true);
assert.equal(JSON.stringify([...b.properties]).includes(turnstileToken),false);
});
test('expired replay hashes are pruned without altering configuration',()=>{
const b=backend();b.properties.set('TURNSTILE_USED_expired','1');b.properties.set('OTHER_CONFIG','keep');
assert.equal(b.post(signup).ok,true);assert.equal(b.properties.has('TURNSTILE_USED_expired'),false);
assert.equal(b.properties.get('OTHER_CONFIG'),'keep');
});