web/website/control-panel/public/cp-v2/cp-v2-security.mjs

54 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
import {createUserAPI} from './cp-v2-user-api.mjs';
export function passwordPayload(currentPassword,newPassword,confirmed){
if(confirmed!==true||typeof currentPassword!=='string'||!currentPassword||currentPassword.length>256||typeof newPassword!=='string'||newPassword.length<12||newPassword.length>256)throw Error('Confirm the change and enter your current password and a new password of 12–256 characters.');
return {currentPassword,newPassword};
}
export function contactPayload(action,{email='',code='',confirmed=false}={}){
if(!['request','confirm','remove','sync'].includes(action))throw Error('Unknown notification setting.');
if(['request','remove'].includes(action)&&confirmed!==true)throw Error('Confirm this change to your notification email.');
if(action==='request'&&(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)||email.length>254))throw Error('Enter a valid email address.');
if(action==='confirm'&&!/^[a-f0-9]{36}$/.test(code.trim()))throw Error('Paste the complete verification code from your email.');
return {action,...(action==='request'?{email:email.trim(),confirmed:true}:action==='remove'?{confirmed:true}:action==='confirm'?{code:code.trim()}:{})};
}
export function mountSecurity(host,{fetcher=fetch}={}){
let active=true,busy=false,uncertain=false;const controller=new AbortController(),{request}=createUserAPI(fetcher,controller.signal);
const passwordBox=el('section',undefined,'cp-v2-personal-box'),contactBox=el('section',undefined,'cp-v2-personal-box'),body=el('div');body.append(passwordBox,contactBox);
const passwordForm=el('form'),passwordFields=el('fieldset');passwordFields.disabled=true;
passwordBox.append(el('h4','Website password'),el('p','Changing your password signs out your other website sessions. Your mailbox password remains separate.'));
function input(parent,title,type='text'){const label=el('label'),caption=el('span',title),field=el('input');field.type=type;if(type==='checkbox'){label.className='security-check';label.append(field,caption);}else label.append(caption,field);parent.append(label);return field;}
const current=input(passwordFields,'Current website password','password'),fresh=input(passwordFields,'New password · at least 12 characters','password');current.autocomplete='current-password';fresh.autocomplete='new-password';current.required=fresh.required=true;current.maxLength=fresh.maxLength=256;fresh.minLength=12;
const passwordConsent=input(passwordFields,'I confirm changing my website password.','checkbox');passwordConsent.required=true;
const passwordSave=el('button','Change password & sign out other sessions');passwordSave.type='submit';const passwordStatus=el('p');passwordStatus.setAttribute('role','status');passwordFields.append(passwordSave);passwordForm.append(passwordFields);passwordBox.append(passwordForm,passwordStatus);
const mailStatus=el('p','Opening your notification settings…');mailStatus.setAttribute('role','status');const mailBody=el('div'),reload=el('button','Reload security settings');reload.type='button';
contactBox.append(el('h4','Support notification email'),el('p','Add a private contact for ticket updates. Ownership must be verified before notifications use it. This does not change your website login.'),mailStatus,mailBody,reload);
const bankBox=el('section',undefined,'cp-v2-personal-box');body.append(bankBox);
async function loadPaymentSecurity(){
bankBox.replaceChildren(el('h4','Payment & ATM protection'));const status=el('p','Loading payment security…');status.setAttribute('role','status');const reloadBank=el('button','Reload payment security');reloadBank.type='button';reloadBank.onclick=()=>void loadPaymentSecurity();bankBox.append(status,reloadBank);
try{const data=await request('/api/bank/transfer-security');if(!active)return;status.textContent=(data.configured?'Payment secret set. ':'No payment secret set. ')+(data.enabled?'Required for instant transfers above '+data.threshold+' DM.':'Extra payment-secret protection is disabled.');
bankBox.append(el('p','One shared threshold for instant bank payments and future ATM cash withdrawals. Rihla is separate. ATM enforcement will be connected with the in-game ATM. This is a security check, not a spending cap.'));
const form=el('form'),fields=el('fieldset'),enabled=input(fields,'Require my payment secret above the threshold','checkbox'),threshold=input(fields,'Shared payment / ATM threshold · DM','number'),website=input(fields,'Current website password','password'),old=input(fields,'Current payment secret','password'),fresh=input(fields,'New payment secret · 12+ characters','password'),consent=input(fields,'I confirm these payment-security settings.','checkbox');
enabled.checked=data.enabled;threshold.value=data.threshold;threshold.min='0';threshold.max='1000000';threshold.step='0.01';threshold.required=true;website.autocomplete='current-password';website.required=true;old.autocomplete='off';old.required=data.configured;old.closest('label').hidden=!data.configured;fresh.placeholder=data.configured?'Leave blank to keep your existing secret':'Choose a payment secret';fresh.autocomplete='new-password';fresh.minLength=12;website.maxLength=old.maxLength=fresh.maxLength=256;consent.required=true;const updateRequired=()=>{fresh.required=enabled.checked&&!data.configured;};enabled.onchange=updateRequired;updateRequired();const save=el('button','Save payment security');save.type='submit';fields.append(save);form.append(fields);bankBox.append(form);const help=el('details'),summary=el('summary','Forgotten your payment secret?');help.append(summary,el('p','Use Standard bank transfers and contact Support. Changing an existing secret, its threshold or switching protection off requires the current secret.'));bankBox.append(help);
form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;fields.disabled=true;status.textContent='Saving payment security…';try{await request('/api/bank/transfer-security',{websitePassword:website.value,currentSecret:old.value,newSecret:fresh.value,threshold:threshold.value,enabled:enabled.checked,version:data.version,confirmed:consent.checked});website.value=old.value=fresh.value='';await loadPaymentSecurity();}catch(e){status.textContent=e.message;fields.disabled=false;}};
}catch(e){if(active)status.textContent=e.message;}
}
void loadPaymentSecurity();
const {root}=createCPV2Page({shellHost:host,title:'Account Security',description:'Protect your website account and manage verified support notifications.',artwork:'nav-account-v2.webp',tabs:[{id:'password',label:'Website password',content:passwordBox},{id:'notifications',label:'Notifications',content:contactBox},{id:'payment-security',label:'Payments & ATM',content:bankBox}]});host.replaceChildren(root);
function controls(){passwordFields.disabled=busy||uncertain;reload.disabled=busy;for(const control of mailBody.querySelectorAll('button,input'))control.disabled=busy||uncertain;}
async function load(){if(busy)return;busy=true;passwordFields.disabled=true;reload.disabled=true;mailBody.replaceChildren();
try{const session=await request('/api/auth/session');if(!session.authenticated)throw Error('Sign in to manage account security.');const data=await request('/api/account/email');if(!active)return;uncertain=false;
mailStatus.textContent=data.verified?'Verified contact: '+data.email:data.pendingEmail?'Verification pending: '+data.pendingEmail:'No verified contact email. Read updates on the Support website.';
const form=el('form'),fields=el('fieldset'),email=input(fields,'Email address','email');email.value=data.email||data.pendingEmail||'';email.autocomplete='email';email.maxLength=254;email.required=true;const consent=input(fields,'I confirm this change to my notification email.','checkbox');consent.required=true;
const send=el('button','Send verification email'),remove=el('button','Remove contact email');send.type=remove.type='submit';remove.formNoValidate=true;remove.hidden=!data.email&&!data.pendingEmail;fields.append(send,remove);form.append(fields);mailBody.append(form);
form.onsubmit=event=>{event.preventDefault();if(!consent.checked){mailStatus.textContent='Confirm this change before continuing.';return;}void act(event.submitter===remove?'remove':'request',{email:email.value,confirmed:consent.checked});};
if(data.pendingEmail){const confirmForm=el('form'),code=input(confirmForm,'Verification code','text');code.required=true;code.minLength=code.maxLength=36;code.autocomplete='one-time-code';const confirm=el('button','Confirm email');confirm.type='submit';confirmForm.append(confirm);mailBody.append(confirmForm);confirmForm.onsubmit=event=>{event.preventDefault();void act('confirm',{code:code.value});};}
if(data.syncPending){const sync=el('button','Retry Support sync');sync.type='button';sync.onclick=()=>void act('sync');mailBody.append(el('p','Support synchronisation is pending. Keep checking tickets online until it succeeds.'),sync);}
}catch(error){if(active){uncertain=true;mailStatus.textContent=error.message;}}
finally{busy=false;if(active)controls();}
}
async function act(action,fields={}){if(busy||uncertain)return;let payload;try{payload=contactPayload(action,fields);}catch(error){mailStatus.textContent=error.message;return;}busy=true;controls();mailStatus.textContent='Updating notification settings…';try{const result=await request('/api/account/email',payload);if(!active)return;busy=false;await load();if(active)mailStatus.textContent=result.message||'Notification settings updated.';}catch(error){if(active){uncertain=!!error.uncertain;mailStatus.textContent=error.message+(uncertain?' Reload settings before retrying.':'');}}finally{busy=false;if(active)controls();}}
passwordForm.onsubmit=async event=>{event.preventDefault();if(busy||uncertain)return;let payload;try{payload=passwordPayload(current.value,fresh.value,passwordConsent.checked);}catch(error){passwordStatus.textContent=error.message;return;}busy=true;controls();passwordStatus.textContent='Changing your website password…';try{const result=await request('/api/auth/password',payload);if(result.ok!==true)throw Object.assign(Error('The password change could not be confirmed.'),{uncertain:true});if(active){passwordForm.reset();passwordStatus.textContent='Password changed. Other website sessions have been signed out.';}}catch(error){if(active){uncertain=!!error.uncertain;passwordStatus.textContent=error.message+(uncertain?' Reload settings and check your login before retrying.':'');}}finally{current.value=fresh.value='';busy=false;if(active)controls();}};
reload.onclick=()=>void load();void load();return()=>{active=false;controller.abort();current.value=fresh.value='';root.remove();};
}