34 lines
1.9 KiB
JavaScript
34 lines
1.9 KiB
JavaScript
// 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);
|
|
};
|
|
}
|

Staff