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'); });