'use strict'; const app = document.querySelector('#app'); const state = {account:null, csrf:null, setup:false, auth:'login', page:'overview', me:null, admin:null, lastKey:null, connected:false}; const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const uid = value => String(value).padStart(6,'0'); const date = value => value ? new Date(value * 1000).toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'}) : '—'; const time = value => value ? new Date(value * 1000).toLocaleString() : 'never'; const active = licenses => licenses.find(l => l.status === 'active' && !l.expires_at) || licenses.filter(l => l.status === 'active').sort((a,b) => b.expires_at-a.expires_at)[0]; const badge = status => `${esc(status)}`; const button = (action, label, extra='', style='') => ``; const field = (label, name, type='text', attributes='', hint='') => ``; const panel = (title, content, extra='') => `

${title}

${content}
`; const detail = (label,value) => `
${label}
${value}
`; const stat = (label,value,hint,compact=false) => `
${label}${esc(value)}${esc(hint)}
`; const heading = (title,description,extra='') => `
amnesia / ${esc(state.page.replace('admin-',''))}

${title}

${description}

${extra}
`; const errorSlot = ''; function toast(message,error=false) { const node = document.createElement('div');node.className=`toast ${error?'error':''}`;node.textContent=message; const container=document.querySelector('#toasts');container.append(node); while(container.children.length>4)container.firstElementChild.remove(); setTimeout(()=>{node.classList.add('leaving');setTimeout(()=>node.remove(),220);},5000); } async function api(path, data) { const options={credentials:'same-origin',headers:{},signal:AbortSignal.timeout(20000)}; if(data !== undefined) { options.method='POST';options.headers['Content-Type']='application/json';options.body=JSON.stringify(data); if(state.csrf)options.headers['X-CSRF-Token']=state.csrf; } let response; try {response=await fetch(`/api${path}`,options);} catch(error) { state.connected=false;throw new Error(error.name==='TimeoutError'?'the service took too long to respond':'cannot reach the licensing service'); } state.connected=true; const result=await response.json().catch(()=>({error:'the service returned an unexpected response'})); if(!response.ok) { if(response.status===401 && state.account && !path.includes('/auth/login')) { state.account=null;state.csrf=null;state.me=null;state.admin=null;state.lastKey=null;render(); } throw new Error(result.error || 'request failed'); } return result; } async function refresh() { const [me,admin]=await Promise.all([api('/account'),state.account.role==='admin'?api('/admin/overview'):Promise.resolve(null)]); state.me=me;state.account=me.account;state.admin=admin; } function nav() { if(!state.account)return ``; const item=(id,label)=>``; return `${state.account.role==='admin'?``:''}`; } function authView() { const setup=state.setup, register=state.auth==='register'; const title=setup?'initial setup':register?'register':'login'; return `

${title}

${!setup?`
`:''}
${field('account name','username','text','required minlength="3" maxlength="24" pattern="[a-zA-Z0-9_]{3,24}" autocomplete="username"')} ${field('password','password','password',`required minlength="12" maxlength="128" autocomplete="${register||setup?'new-password':'current-password'}"`)} ${register||setup?field('confirm password','confirm','password','required minlength="12" maxlength="128" autocomplete="new-password"'):''} ${errorSlot}
${setup?'the first account receives administrator access.':register?'license keys are redeemed after registration.':'use your amnesia account credentials.'}

account information

${detail('account names','3–24 letters, numbers or underscores.')} ${detail('passwords','12–128 characters.')} ${detail('uid','assigned at registration.')} ${detail('licenses','redeem a key from the licenses page.')} ${detail('hardware','linked on your first licensed client login.')}
`; } function overview() { const a=state.me.account,l=active(state.me.licenses); return heading('account','account and license information',badge(l?'active':'unlicensed'))+ `
${panel('account',`
${detail('account name',esc(a.username))} ${detail('uid',`${uid(a.uid)}`)} ${detail('registered',date(a.created_at))} ${detail('group',esc(a.role))} ${detail('last client login',esc(time(a.last_seen)))}
`)} ${panel('license',`
${detail('status',badge(l?'active':'unlicensed'))} ${detail('license',l?esc(l.label):'none')} ${detail('expires',l?(l.expires_at?date(l.expires_at):'lifetime'):'—')} ${detail('device',a.hwid_bound?esc(a.device_name):'not linked')}
${button('navigate',l?'licenses':'redeem key','data-target="licenses"')} ${button('navigate','device settings','data-target="security"')}
`)}
`+ (state.admin?panel('statistics',`
${stat('members',state.admin.counts.accounts,'')} ${stat('active licenses',state.admin.counts.active_licenses,'')} ${stat('unused keys',state.admin.counts.issued_keys,'')} ${stat('reset requests',state.admin.counts.reset_requests,'')}
`,'section-gap'):''); } function licenseRows(licenses,admin=false) { if(!licenses.length)return `
${admin?'no licenses issued yet':'no licenses on this account'}

${admin?'create a key above to get started.':'redeem your first key above.'}

`; return `
${admin?'':''}${admin?'':''}${licenses.map(l=>`${admin?``:''}${admin?``:''}`).join('')}
licenseaccount uidstatusexpiresaction
${esc(l.label)}${esc(l.key_hint)}${l.account_uid?uid(l.account_uid):'unclaimed'}${badge(l.status)}${l.expires_at?date(l.expires_at):!l.activated_at?(l.status==='issued'?(l.duration_days?`${l.duration_days} days on redemption`:'lifetime on redemption'):'not redeemed'):'lifetime'}${l.status!=='revoked'?button('revoke','revoke',`data-id="${esc(l.id)}"`,'small danger'):'—'}
`; } function licensesView() { return heading('licenses','redeem a key to attach access to your account.')+panel('redeem a license',`
${field('license key','key','text','required maxlength="128" autocomplete="off" spellcheck="false" placeholder="AMN-XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX"')}
${errorSlot}

license time begins when you redeem it. redeemed keys cannot be transferred to another account.

`)+`

license history ${state.me.licenses.length} total

${licenseRows(state.me.licenses)}
`; } function security() { const a=state.me.account,request=state.me.reset_request; return heading('device & security','manage your linked hardware and keep your account private.')+`
${panel('linked device',`
${detail('device',a.hwid_bound?esc(a.device_name):'not linked')}${detail('linked on',date(a.bound_at))}${detail('last seen',esc(time(a.last_seen)))}${detail('hardware tie',a.hwid_bound?'bound to this account':'awaiting first client sign-in')}
${a.hwid_bound?'hardware details stay private. a keyed fingerprint is used to recognize your device.':'your device is linked automatically the first time you sign in through the client with an active license.'}
${request?`

request pending since ${date(request.requested_at)}. submitting again updates your request.

`:''}${errorSlot}
`)}${panel('change password',`

changing your password signs out all browser and client sessions, including this one.

${field('current password','current_password','password','required maxlength="128" autocomplete="current-password"')}${field('new password','new_password','password','required minlength="12" maxlength="128" autocomplete="new-password"')}${field('confirm new password','confirm','password','required minlength="12" maxlength="128" autocomplete="new-password"')}${errorSlot}
`)}
`; } function adminLicenses() { return heading('license manager','issue a key, track its owner, or revoke access.')+panel('create a license',`
${field('label','label','text','required maxlength="60" value="amnesia access"')}${field('duration in days','duration_days','number','required min="1" max="3650" value="30"')}
${errorSlot}
${state.lastKey?`

key created — copy it now. the full key is only shown once.

${esc(state.lastKey)}${button('copy-key','copy key','','small')}
`:''}`)+`

licenses

${licenseRows(state.admin.licenses,true)}
`; } function members() { const requests=new Map(state.admin.reset_requests.map(r=>[r.account_uid,r])); return heading('members','accounts, linked devices and hardware reset requests.',`${state.admin.counts.accounts} accounts`)+`

members

${state.admin.accounts.map(a=>``).join('')}
accountstatusdeviceactions
${esc(a.username)}uid ${uid(a.uid)} / ${esc(a.role)}${badge(a.enabled?'enabled':'disabled')}${a.hwid_bound?esc(a.device_name):'not linked'}${requests.has(a.uid)?`reset requested: ${esc(requests.get(a.uid).reason)}`:''}
${a.hwid_bound||requests.has(a.uid)?button('reset-hwid',requests.has(a.uid)?'approve reset':'reset hwid',`data-uid="${a.uid}"`,'small'):''}${a.uid!==state.account.uid?button('account-status',a.enabled?'disable':'enable',`data-uid="${a.uid}" data-enabled="${a.enabled?'false':'true'}"`,'small'):'you'}

resetting a hardware tie immediately invalidates client sessions. the next client sign-in links a new device.

`; } function activity() { return heading('activity log','account and licensing changes, recorded as they happen.')+`

recent activity latest 100 events

${state.admin.audit.map(row=>``).join('')}
eventactorsubjecttime
${esc(row.action.replaceAll('.',' / ').replaceAll('_',' '))}${esc(row.username||'system')}${esc(row.subject)}${esc(time(row.created_at))}
`; } function render() { document.title=`amnesia // ${state.account?state.page.replace('admin-',''):'account'}`; const views={overview,licenses:licensesView,security,'admin-licenses':adminLicenses,'admin-accounts':members,activity}; const body=state.account&&state.me?(views[state.page]||overview)():authView(); app.removeAttribute('aria-busy'); app.innerHTML=`
${body}
`; } async function confirmAction(message) { const dialog=document.querySelector('#confirm-dialog');document.querySelector('#confirm-message').textContent=message; return new Promise(resolve=>{dialog.returnValue='cancel';dialog.addEventListener('close',()=>resolve(dialog.returnValue==='confirm'),{once:true});dialog.showModal();}); } document.addEventListener('click',async event=>{ const target=event.target.closest('button');if(!target)return; if(target.dataset.auth){state.auth=target.dataset.auth;render();return;} if(target.dataset.page||target.dataset.action==='navigate') { state.page=target.dataset.page||target.dataset.target;state.lastKey=null;render();return; } const action=target.dataset.action;if(!action)return; try { if(action==='copy-key') { if(!state.lastKey)return; await navigator.clipboard.writeText(state.lastKey);toast('license key copied');return; } if(action==='logout') { await api('/auth/logout',{});state.account=null;state.csrf=null;state.me=null;state.admin=null;state.lastKey=null;state.auth='login';render();return; } const messages={revoke:'revoke this license? its client sessions will stop working immediately.','reset-hwid':'reset this hardware tie? existing client sessions will end and the next sign-in can link a new device.','account-status':target.dataset.enabled==='true'?'enable this account again?':'disable this account? all browser and client sessions will end.'}; if(!messages[action]||!await confirmAction(messages[action]))return; target.disabled=true; if(action==='revoke'){await api(`/admin/licenses/${target.dataset.id}/revoke`,{});state.lastKey=null;} if(action==='reset-hwid')await api(`/admin/accounts/${target.dataset.uid}/reset-hwid`,{}); if(action==='account-status')await api(`/admin/accounts/${target.dataset.uid}/status`,{enabled:target.dataset.enabled==='true'}); await refresh();render();toast(action==='reset-hwid'?'hardware tie reset':action==='revoke'?'license revoked':'account updated'); } catch(error){target.disabled=false;toast(error.message,true);} }); document.addEventListener('input',event=>{ if(event.target.matches('[data-filter]')) { const term=event.target.value.toLowerCase();document.querySelectorAll('tr[data-search]').forEach(row=>{row.hidden=!row.dataset.search.includes(term);}); } }); document.addEventListener('change',event=>{ if(event.target.name==='lifetime') { const days=event.target.form.elements.duration_days;days.disabled=event.target.checked;days.required=!event.target.checked; } }); document.addEventListener('submit',async event=>{ const form=event.target;if(!form.matches('[data-form]'))return;event.preventDefault(); const kind=form.dataset.form,fields=Object.fromEntries(new FormData(form)),submit=form.querySelector('[type="submit"]'),error=form.querySelector('.form-error'); error.textContent='';submit.disabled=true; try { if(['login','register','setup'].includes(kind)) { if(kind!=='login'&&fields.password!==fields.confirm)throw new Error('passwords do not match'); const result=await api(kind==='setup'?'/setup':`/auth/${kind}`,{username:fields.username,password:fields.password}); state.account=result.account;state.csrf=result.csrf;state.setup=false;state.page='overview';await refresh();render();toast(kind==='login'?'signed in':'account created');return; } if(kind==='redeem')await api('/licenses/redeem',{key:fields.key}); if(kind==='hwid-reset')await api('/account/hwid-reset',{reason:fields.reason}); if(kind==='issue') { const result=await api('/admin/licenses',{label:fields.label,duration_days:fields.lifetime?null:Number(fields.duration_days)});state.lastKey=result.key; } if(kind==='password') { if(fields.new_password!==fields.confirm)throw new Error('passwords do not match'); await api('/account/password',{current_password:fields.current_password,new_password:fields.new_password}); state.account=null;state.csrf=null;state.me=null;state.admin=null;state.lastKey=null;state.auth='login';render();toast('password changed. sign in again.');return; } await refresh();render();toast(kind==='redeem'?'license activated':kind==='issue'?'license key created':'hardware reset requested'); } catch(problem){error.textContent=problem.message;submit.disabled=false;} }); async function boot() { try { const result=await api('/session');state.account=result.account;state.csrf=result.csrf;state.setup=result.setup_required; if(state.account)await refresh();render(); } catch(error) { state.connected=false;render();toast(error.message,true); } } boot();