diff --git a/website/node/internal-mail.mjs b/website/node/internal-mail.mjs index 74cd71ca..37812d16 100644 --- a/website/node/internal-mail.mjs +++ b/website/node/internal-mail.mjs @@ -1,3 +1,4 @@ +import {cacheMailMetadata} from './mail-metadata-cache.mjs'; import {reconcileRoyalCompanyMail} from './company-royal-mail.mjs'; import {ownCompanyMailbox,ensureCompanyMailbox,reconcileCompanyMail,defaultCompanyMailbox} from './internal-mail-companies.mjs'; import {runJarvisApplicationNotifications} from './jarvis-notifications.mjs'; @@ -72,6 +73,7 @@ const routes={ '/api/internal-mail/messages/tags':['internal_tags',['folder','uid','uidValidity','tags']] }; export function createInternalMail(db,{origin='https://cp.dunerealms.com',broker=internalMailBroker,getIdentity=identity,eligible=internalMailEligible,staffAccess=canUseStaffMail,settings=process.env,governmentAccess=(db,user)=>politicalMailContext(db,user,settings),now=Date.now}={}){ + broker=cacheMailMetadata(broker,{clock:now}); const attempts=new Map(); return async request=>{ const path=new URL(request.url).pathname; diff --git a/website/node/mail-identity.mjs b/website/node/mail-identity.mjs index b6ae7053..2dfe2503 100644 --- a/website/node/mail-identity.mjs +++ b/website/node/mail-identity.mjs @@ -1,3 +1,4 @@ +import {cacheMailMetadata} from './mail-metadata-cache.mjs'; import {mailBrandingFor} from './mail-branding.mjs'; import {identity} from './auth.mjs'; import {scrypt as rawScrypt,timingSafeEqual,randomUUID} from 'node:crypto'; @@ -21,7 +22,7 @@ export function smartReplyTemplate(user,address,branding={}){ return {html:template.html.replace('Write your reply here.','%cursor%'),text:template.text.replace('Write your reply here.','%cursor%')}; } export async function initializeMailIdentities(db){await db.prepare('CREATE TABLE IF NOT EXISTS site_mail_identities (user_id VARCHAR(36) PRIMARY KEY,mailbox_address VARCHAR(254) NOT NULL,verified_at BIGINT NOT NULL,link_method VARCHAR(32) NOT NULL,active INTEGER NOT NULL DEFAULT 1)').run();} -export function createMailIdentityRoute(db,{origin='https://cp.dunerealms.com',brandingFor=mailBrandingFor,broker=async body=>(await import('./mail-broker.mjs')).callMailBroker(body)}={}){const attempts=new Map();return async request=>{ +export function createMailIdentityRoute(db,{origin='https://cp.dunerealms.com',brandingFor=mailBrandingFor,broker=async body=>(await import('./mail-broker.mjs')).callMailBroker(body)}={}){const cachedBroker=cacheMailMetadata(broker),attempts=new Map();return async request=>{ const path=new URL(request.url).pathname; if(!['/api/mail/me','/api/mail/password','/api/mail/signature','/api/mail/template'].includes(path))return reply({message:'Not found'},404); if(request.method!==(path==='/api/mail/password'?'POST':'GET'))return reply({message:'Method not allowed'},405); @@ -39,7 +40,7 @@ export function createMailIdentityRoute(db,{origin='https://cp.dunerealms.com',b if(template)return new Response(signature.html,{headers:{'Content-Type':'text/html; charset=utf-8','Content-Disposition':(url.searchParams.get('preview')==='1'?'inline':'attachment')+'; filename="dunerealms-email-template.html"','Cache-Control':'private, no-store','Content-Security-Policy':"default-src 'none'; img-src https://www.dunerealms.com; style-src 'unsafe-inline'; frame-ancestors 'self'; sandbox"}}); return new Response('DuneRealms email signature'+signature.html+'',{headers:{'Content-Type':'text/html; charset=utf-8','Content-Disposition':(url.searchParams.get('preview')==='1'?'inline':'attachment')+'; filename="dunerealms-signature.html"','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':"default-src 'none'; img-src https://www.dunerealms.com; style-src 'unsafe-inline'; frame-ancestors 'self'; sandbox"}}); } - if(path==='/api/mail/me'){let setup={};try{const state=await broker({action:'status',userId:user.id});if(!state.active||state.address!==row.mailbox_address)return reply({linked:false});setup={needsPasswordSetup:!!state.needsPasswordSetup,setupAvailable:true};}catch{setup={setupAvailable:false};}return reply({linked:true,address:row.mailbox_address,webmailUrl:'https://www.lgbbenelux.org/webmail/',...setup});} + if(path==='/api/mail/me'){let setup={};try{const state=await cachedBroker({action:'status',userId:user.id});if(!state.active||state.address!==row.mailbox_address)return reply({linked:false});setup={needsPasswordSetup:!!state.needsPasswordSetup,setupAvailable:true};}catch{setup={setupAvailable:false};}return reply({linked:true,address:row.mailbox_address,webmailUrl:'https://www.lgbbenelux.org/webmail/',...setup});} if(request.headers.get('Origin')!==origin)return reply({message:'Request origin rejected'},403); const now=Date.now();for(const[key,value]of attempts)if(value.until5)return reply({message:'Too many attempts. Try again in 15 minutes.'},429); let body;try{body=await request.json();}catch{return reply({message:'Invalid request'},400);} @@ -48,7 +49,7 @@ export function createMailIdentityRoute(db,{origin='https://cp.dunerealms.com',b const account=await db.prepare('SELECT password_salt,password_hash FROM site_accounts WHERE id=?').bind(user.id).first(); const expected=Buffer.from(account?.password_hash||'','hex'),actual=await scrypt(current,account?.password_salt||'00000000000000000000000000000000',64); if(expected.length!==actual.length||!timingSafeEqual(actual,expected))return reply({message:'Incorrect website password.'},403); - try{const result=await broker({action:'set_password',userId:user.id,password});if(!result.active)throw Error('Mailbox unavailable');}catch{return reply({message:'Mailbox password setup is temporarily unavailable. Your website password has not changed.'},503);} + try{const result=await cachedBroker({action:'set_password',userId:user.id,password});if(!result.active)throw Error('Mailbox unavailable');}catch{return reply({message:'Mailbox password setup is temporarily unavailable. Your website password has not changed.'},503);} await db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'mail-password-set','Self-service mailbox password updated',Date.now()).run(); return reply({ok:true,message:'Mailbox password saved. Your website password is unchanged.'}); };} diff --git a/website/node/mail-metadata-cache.mjs b/website/node/mail-metadata-cache.mjs new file mode 100644 index 00000000..e207aabe --- /dev/null +++ b/website/node/mail-metadata-cache.mjs @@ -0,0 +1,34 @@ +// Process-local metadata only. Message contents and credentials are never cached. +const metadataActions=new Set(['status','ensure','internal_status','internal_ensure']); +const readActions=new Set(['internal_list','internal_get','internal_attachment','internal_password_reveal']); +function containsSecret(value){ + if(!value||typeof value!=='object')return false; + return Object.entries(value).some(([key,item])=> + /password|secret|token|credential/i.test(key)&&typeof item==='string'&&item.length>0||containsSecret(item)); +} +export function cacheMailMetadata(broker,{clock=Date.now,ttlMs=15000,maxEntries=256}={}){ + const entries=new Map(); + const invalidate=userId=>{for(const [key,entry]of entries)if(entry.userId===userId)entries.delete(key);}; + return async payload=>{ + if(!metadataActions.has(payload.action)){ + if(!readActions.has(payload.action))invalidate(payload.userId); + return broker(payload); + } + // Include every argument: mailbox owner, kind, resource and address must match. + const key=JSON.stringify(Object.keys(payload).sort().map(name=>[name,payload[name]])); + const existing=entries.get(key); + if(existing&&(existing.pending||existing.until>clock()))return structuredClone(await existing.promise); + if(existing)entries.delete(key); + for(const [k,e]of entries)if(!e.pending&&e.until<=clock())entries.delete(k); + while(entries.size>=maxEntries)entries.delete(entries.keys().next().value); + const entry={userId:payload.userId,pending:true,until:0}; + entries.set(key,entry); + entry.promise=Promise.resolve().then(()=>broker(payload)).then(value=>{ + if(value?.error||value?.ok===false||value?.active===false||value?.configured===false||containsSecret(value)){ + if(entries.get(key)===entry)entries.delete(key); + }else{entry.pending=false;entry.until=clock()+ttlMs;} + return structuredClone(value); + },error=>{if(entries.get(key)===entry)entries.delete(key);throw error;}); + return structuredClone(await entry.promise); + }; +} diff --git a/website/tests/mail-metadata-cache.test.mjs b/website/tests/mail-metadata-cache.test.mjs new file mode 100644 index 00000000..db8cb35d --- /dev/null +++ b/website/tests/mail-metadata-cache.test.mjs @@ -0,0 +1,41 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {cacheMailMetadata} from '../node/mail-metadata-cache.mjs'; +const status={action:'internal_status',userId:'person-a'}; +test('metadata is reused for fifteen seconds, with independent return values',async()=>{ + let now=0,calls=0;const cached=cacheMailMetadata(async()=>({ok:true,active:true,capabilities:{read:++calls}}),{clock:()=>now}); + const first=await cached(status);first.capabilities.read=999;now=14999; + assert.equal((await cached(status)).capabilities.read,1);assert.equal(calls,1); + now=15000;assert.equal((await cached(status)).capabilities.read,2); +}); +test('simultaneous identical checks share one upstream operation',async()=>{ + let calls=0,release;const cached=cacheMailMetadata(async()=>{calls++;await new Promise(r=>release=r);return {active:true};}); + const requests=Array.from({length:8},()=>cached(status));await new Promise(r=>setImmediate(r));assert.equal(calls,1);release();await Promise.all(requests); +}); +test('users, mailbox resources and provisioning parameters stay isolated',async()=>{ + let calls=0;const cached=cacheMailMetadata(async()=>({active:true,sequence:++calls})); + for(const payload of [status,{...status,userId:'person-b'},{...status,action:'internal_ensure',mailboxKind:'clan',resourceId:'clan-a'},{...status,action:'internal_ensure',mailboxKind:'clan',resourceId:'clan-b'}])await cached(payload); + assert.equal(calls,4);await cached({...status});assert.equal(calls,4); +}); +for(const result of [{active:false},{configured:false},{ok:false},{error:'unavailable'},{active:true,password:'secret'},{active:true,nested:{credential:'secret'}}])test(`unsafe or unavailable result is not retained: ${JSON.stringify(Object.keys(result))}`,async()=>{ + let calls=0;const cached=cacheMailMetadata(async()=>{calls++;return result;});await cached(status);await cached(status);assert.equal(calls,2); +}); +test('errors are not cached and a later request can recover',async()=>{ + let calls=0;const cached=cacheMailMetadata(async()=>{if(++calls===1)throw Error('offline');return {active:true};}); + await assert.rejects(cached(status),/offline/);await cached(status);assert.equal(calls,2); +}); +test('messages, password reveal and sends are always fresh; writes invalidate metadata',async()=>{ + const calls=[];const cached=cacheMailMetadata(async p=>{calls.push(p.action);return {active:true};}); + await cached(status);await cached(status); + for(const action of ['internal_list','internal_get','internal_password_reveal']){await cached({...status,action});await cached({...status,action});} + await cached(status);assert.equal(calls.filter(a=>a==='internal_status').length,1); + await cached({...status,action:'set_password',password:'not-a-real-password'});await cached(status); + assert.equal(calls.filter(a=>a==='internal_status').length,2);assert.equal(calls.filter(a=>a==='internal_list').length,2); +}); +test('a late status reply cannot repopulate metadata invalidated by a write',async()=>{ + let release,calls=0;const cached=cacheMailMetadata(async p=>{if(p.action==='internal_status'){calls++;if(calls===1)await new Promise(r=>release=r);}return {active:true};}); + const pending=cached(status);await new Promise(r=>setImmediate(r));await cached({...status,action:'internal_password'});release();await pending;await cached(status);assert.equal(calls,2); +}); +test('cache size is bounded and oldest entries are evicted',async()=>{ + let calls=0;const cached=cacheMailMetadata(async()=>({active:true,sequence:++calls}),{maxEntries:2}); + for(const userId of ['a','b','c','a'])await cached({...status,userId});assert.equal(calls,4); +});