54 lines
11 KiB
JavaScript
54 lines
11 KiB
JavaScript
import {mailBrandingFor} from './mail-branding.mjs';
|
||
import {identity} from './auth.mjs';
|
||
import {scrypt as rawScrypt,timingSafeEqual,randomUUID} from 'node:crypto';
|
||
import {promisify} from 'node:util';
|
||
const scrypt=promisify(rawScrypt),reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'no-store'}});
|
||
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||
export async function mailSignatureFor(db,user,address){return mailSignature(user,address,await mailBrandingFor(db,user));}
|
||
export function mailSignature(user,address,{rankLabel='DuneRealms Community Team',seals=[]}={}){
|
||
const name=user.id==='f3ffda37-01e4-41ea-b89d-fbeda82e453e'&&address.toLowerCase()==='unimatrix@dunerealms.com'?'Unimatrix':user.display_name||user.username;
|
||
const rows=[];for(let i=0;i<seals.length;i+=7)rows.push('<tr>'+seals.slice(i,i+7).map(item=>'<td bgcolor="#142e26" style="background-color:#142e26;padding:4px 7px 4px 0"><img src="'+escape(item.url)+'" width="48" height="48" alt="'+escape(item.label)+'" style="display:block;width:48px;height:48px;border:0"></td>').join('')+'</tr>');
|
||
const html='<table role="presentation" bgcolor="#142e26" cellpadding="0" cellspacing="0" style="width:100%;max-width:560px;background:#142e26;border:1px solid #c3a159;border-radius:8px;color:#eee6d2;font:14px/1.6 Arial,sans-serif"><tr><td bgcolor="#142e26" style="padding:20px;background-color:#142e26;color:#eee6d2"><a href="https://www.dunerealms.com/"><img src="https://www.dunerealms.com/assets/dunerealms-season-logo-v2.png" width="220" alt="DuneRealms" style="display:block;width:220px;max-width:100%;height:auto;border:0"></a><p style="margin:16px 0 4px;color:#eee6d2">With regards,<br><strong style="color:#e2c379">'+escape(name)+'</strong></p><p style="margin:4px 0;font-size:10px;letter-spacing:2px;color:#c3a159">DUNEREALMS COMMUNITY TEAM</p><p style="margin:4px 0;color:#d7cfad;font-size:12px">'+escape(rankLabel)+'</p><a href="mailto:'+escape(address)+'" style="color:#e2c379">'+escape(address)+'</a>'+(rows.length?'<table role="presentation" bgcolor="#142e26" cellpadding="0" cellspacing="0" style="background-color:#142e26;margin-top:12px">'+rows.join('')+'</table>':'')+'<p style="border-top:1px solid #796b42;padding-top:12px;margin:14px 0 0;font-size:12px;color:#d4d9c9">For support, <a href="https://support.dunerealms.com/" style="color:#e2c379">visit our support site and submit a ticket</a>.</p></td></tr></table>';
|
||
return {html,text:'With regards,\n'+name+'\nDUNEREALMS COMMUNITY TEAM\n'+address+'\nhttps://www.dunerealms.com/\nFor support, visit https://support.dunerealms.com/ and submit a ticket.'};
|
||
}
|
||
export function mailTemplate(user,address,branding={},mode='new'){
|
||
const signature=mailSignature(user,address,branding);
|
||
const html='<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DuneRealms message template</title></head><body bgcolor="#0d211b" text="#eee6d2" style="margin:0;padding:0;background-color:#0d211b;color:#eee6d2"><table role="presentation" width="100%" bgcolor="#0d211b" cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#0d211b;color:#eee6d2"><tr><td align="center" bgcolor="#0d211b" style="padding:24px;background-color:#0d211b;color:#eee6d2"><table role="presentation" width="640" bgcolor="#142e26" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:640px;background-color:#142e26;border:1px solid #c3a159;border-radius:8px;color:#eee6d2;font:15px/1.7 Arial,sans-serif"><tr><td bgcolor="#142e26" style="padding:24px;background-color:#142e26;color:#eee6d2"><a href="https://www.dunerealms.com/"><img src="https://www.dunerealms.com/assets/dunerealms-season-logo-v2.png" width="220" alt="DuneRealms" style="display:block;width:220px;max-width:100%;height:auto;border:0"></a><p style="margin:18px 0 22px;color:#c3a159;font:11px/1.5 Arial,sans-serif;letter-spacing:2px">DUNEREALMS · THE CARAVAN DISPATCH</p><table role="presentation" width="100%" bgcolor="#1b382d" cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#1b382d;border:1px solid #59704f;color:#eee6d2"><tr><td bgcolor="#1b382d" style="padding:18px;background-color:#1b382d;color:#eee6d2;font:15px/1.7 Arial,sans-serif"><p style="margin:0;color:#eee6d2">Write your message here.</p></td></tr></table><table role="presentation" width="100%" bgcolor="#142e26" cellpadding="0" cellspacing="0" border="0" style="background-color:#142e26"><tr><td bgcolor="#142e26" style="padding-top:22px;background-color:#142e26;color:#eee6d2">'+signature.html+'</td></tr></table></td></tr></table></td></tr></table></body></html>';
|
||
return {html:mode==='reply'?html.replace('Write your message here.','Write your reply here.'):html,text:'DUNEREALMS · THE CARAVAN DISPATCH\n\n'+(mode==='reply'?'Write your reply here.':'Write your message here.')+'\n\n'+signature.text};
|
||
}
|
||
export function smartReplyTemplate(user,address,branding={}){
|
||
const template=mailTemplate(user,address,branding,'reply');
|
||
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=>{
|
||
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);
|
||
const user=await identity(request,db);if(!user)return Response.json({message:'Sign in first'},{status:401,headers:{'Cache-Control':'no-store'}});
|
||
const row=await db.prepare('SELECT mailbox_address,verified_at FROM site_mail_identities WHERE user_id=? AND active=1').bind(user.id).first();
|
||
if(!row||Number(row.verified_at)<=0)return reply({linked:false},path==='/api/mail/me'?200:403);
|
||
if(['/api/mail/signature','/api/mail/template'].includes(path)){
|
||
try{const state=await broker({action:'status',userId:user.id});if(!state.active||state.address!==row.mailbox_address)return reply({message:'An active verified mailbox is required.'},403);}catch{return reply({message:'Signature download is temporarily unavailable.'},503);}
|
||
const mode=new URL(request.url).searchParams.get('mode')==='reply'?'reply':'new'; const branding=await brandingFor(db,user),template=path==='/api/mail/template',signature=template?(mode==='reply'&&new URL(request.url).searchParams.get('format')==='smarttemplates'?smartReplyTemplate(user,row.mailbox_address,branding):mailTemplate(user,row.mailbox_address,branding,mode)):mailSignature(user,row.mailbox_address,branding),url=new URL(request.url);if(url.searchParams.get('format')==='json')return reply(signature);
|
||
if(template&&url.searchParams.get('preview')!=='1'&&!['html','smarttemplates'].includes(url.searchParams.get('format'))){
|
||
const boundary='dunerealms-'+randomUUID(),encode=text=>Buffer.from(text,'utf8').toString('base64').match(/.{1,76}/g).join('\r\n');
|
||
const eml=['From: '+row.mailbox_address,'To:','Subject:','X-Unsent: 1','MIME-Version: 1.0','Content-Type: multipart/alternative; boundary="'+boundary+'"','','--'+boundary,'Content-Type: text/plain; charset=utf-8','Content-Transfer-Encoding: base64','',encode(signature.text),'--'+boundary,'Content-Type: text/html; charset=utf-8','Content-Transfer-Encoding: base64','',encode(signature.html),'--'+boundary+'--',''].join('\r\n');
|
||
return new Response(eml,{headers:{'Content-Type':'message/rfc822','Content-Disposition':'attachment; filename="dunerealms-email-template.eml"','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||
}
|
||
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(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);}
|
||
const current=body.currentPassword,password=body.useSamePassword===true?current:body.newPassword;
|
||
if(typeof current!=='string'||current.length>256||typeof password!=='string'||password.length<12||password.length>256||/[\r\n\0]/.test(password))return reply({message:'Use a mailbox password of 12–256 characters.'},400);
|
||
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);}
|
||
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.'});
|
||
};}
|

Staff