Cache mailbox metadata briefly and coalesce duplicate mail-host checks
This commit is contained in:
parent
3dee0ee6b3
commit
428ff2fc8a
3 changed files with 81 additions and 3 deletions
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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('<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DuneRealms email signature</title></head><body style="margin:0;padding:12px;background:#0d211b">'+signature.html+'</body></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.until<now)attempts.delete(key);let attempt=attempts.get(user.id);if(!attempt||attempt.until<now){attempt={count:0,until:now+900000};attempts.set(user.id,attempt);}if(++attempt.count>5)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.'});
|
||||
};}
|
||||
|
|
|
|||
34
website/node/mail-metadata-cache.mjs
Normal file
34
website/node/mail-metadata-cache.mjs
Normal file
|
|
@ -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);
|
||||
};
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff