import { formatDateTime } from '../i18n/format.js'; import { t, th } from '../i18n/index.js'; import { createTopBar } from '../components/topbar.js'; import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js'; import { authService, state } from '../state.js'; import { bytesToBase64 } from '../services/crypto-utils.js'; import { readShineUserPda } from '../services/shine-user-pda-service.js'; import { KeyRotationClient, KEY_ROTATION_REASONS } from '../services/key-rotation-service.js'; import { formatSol, getBalanceSol, getSolanaWalletFromStoredSecret, transferAllSol } from '../services/solana-wallet-service.js'; export const pageMeta = { id:'key-rotation-view', get title() { return t('screens.key_rotation_view.text_001'); }, hideToolbar:true }; const POLL_MS=1800; function h(v){return String(v??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));} function short(v){const s=String(v||'');return s.length>20?`${s.slice(0,10)}…${s.slice(-8)}`:s;} function stageText(s){return ({COPYING_CHAIN:t('screens.key_rotation_view.text_037'),CHAIN_READY:t('screens.key_rotation_view.text_038'),ROTATING_PDA:t('screens.key_rotation_view.text_039'),PDA_ROTATED:t('screens.key_rotation_view.text_040'),REBUILDING_SERVER:t('screens.key_rotation_view.text_041'),WALLET_MIGRATION:t('screens.key_rotation_view.text_042'),MESSAGE_MIGRATION:t('screens.key_rotation_view.text_043'),FINALIZING:t('screens.key_rotation_view.text_044'),COMPLETE:t('screens.key_rotation_view.text_045'),NONE:t('screens.key_rotation_view.text_046')})[s]||s;} function input(label,type='password'){const wrap=document.createElement('label');wrap.className='stack';const t=document.createElement('span');t.className='field-label';t.textContent=label;const el=document.createElement('input');el.className='text-input';el.type=type;wrap.append(t,el);return {wrap,el};} export function render({navigate,chrome}){ const screen=document.createElement('section');screen.className='stack'; // До запуска смену можно закрыть; после старта выход назад запрещён. function updateTopbar(status){ const canExit=status==='NONE' || status==='COMPLETE'; chrome?.setTopbar(createTopBar({title:t('screens.key_rotation_view.text_002'),...(canExit?{back:{label:'←',onClick:()=>navigate('access-keys-view')}}:{})})); window.dispatchEvent(new CustomEvent('shine-key-rotation-active',{detail:{active:!canExit}})); } // Пока статус с сервера не прочитан, не разблокируем навигацию преждевременно. chrome?.setTopbar(createTopBar({title:t('screens.key_rotation_view.text_003')})); const root=document.createElement('div');root.className='stack';screen.append(root); const client=new KeyRotationClient(authService);let disposed=false;let timer=null;let cachedOldBundle=null;let cachedNewBundle=null; const login=String(state.session.login||'').trim(); const storagePwd=String(state.session.storagePwdInMemory||'').trim(); const solanaEndpoint=String(state.entrySettings.solanaServer||'').trim(); async function derive(password){return authService.derivePasswordKeyBundle(login,password,{onProgress:()=>{}});} async function verifyOldPassword(bundle){ const pda=await readShineUserPda({login,solanaEndpoint}); if(bundle.rootPair.publicKeyB64!==bytesToBase64(pda.rootKey) || bundle.blockchainPair.publicKeyB64!==bytesToBase64(pda.blockchain.blockchainPublicKey) || bundle.clientPair.publicKeyB64!==bytesToBase64(pda.clientKey)) throw new Error(t('screens.key_rotation_view.text_050')); } function setRoot(...nodes){root.replaceChildren(...nodes);} function exitAfterComplete(){updateTopbar('COMPLETE');navigate('access-keys-view');} function statusCard(s){const card=document.createElement('div');card.className='card stack';card.innerHTML=`${h(stageText(s.rotationStatus))}${h(s.sourceBlockchainName||'')} → ${h(s.candidateBlockchainName||'')}${th('remaining.html_key_rotation_view.progress')}${Number(s.progressCurrent||0)} / ${Number(s.progressTotal||0)}${s.lastError?`${h(s.lastError)}`:''}`;return card;} function note(text){const c=document.createElement('div');c.className='card';c.textContent=text;return c;} async function renderNone(){ const head=note(t('screens.key_rotation_view.text_017')); const oldP=input(t('screens.key_rotation_view.text_018')); const newP=input(t('screens.key_rotation_view.text_019')); const new2=input(t('screens.key_rotation_view.text_020')); const reason=document.createElement('select');reason.className='text-input';for(const r of KEY_ROTATION_REASONS){const o=document.createElement('option');o.value=String(r.code);o.textContent=r.label;reason.append(o);} const reasonWrap=document.createElement('label');reasonWrap.className='stack';reasonWrap.innerHTML=t('screens.key_rotation_view.text_051');reasonWrap.append(reason); const comment=document.createElement('textarea');comment.className='text-input';comment.rows=3;comment.maxLength=1024;comment.placeholder=t('screens.key_rotation_view.text_004'); const list=document.createElement('div');list.className='stack';const more=document.createElement('button');more.className='secondary-btn';more.type='button';more.textContent=t('screens.key_rotation_view.text_005'); let selected=null,before=null,loading=false; async function load(){if(loading)return;loading=true;more.disabled=true;try{const d=await client.getMyBlockchain({beforeBlock:before,limit:100});for(const b of d.blocks||[]){const btn=document.createElement('button');btn.type='button';btn.className='nav-row';btn.innerHTML=`#${b.blockNumber} · ${formatDateTime(new Date(Number(b.timestampMs)||0))}${short(b.blockHash)}`;btn.addEventListener('click',()=>{selected=b;list.querySelectorAll('button').forEach(x=>x.setAttribute('aria-pressed','false'));btn.setAttribute('aria-pressed','true');});if(selected==null && b.blockNumber===d.tipBlockNumber){selected=b;btn.setAttribute('aria-pressed','true');}list.append(btn);}before=d.nextBeforeBlock;more.hidden=before==null;}finally{loading=false;more.disabled=false;}} more.addEventListener('click',()=>void load()); const start=document.createElement('button');start.className='primary-btn';start.type='button';start.textContent=t('screens.key_rotation_view.text_006'); const error=document.createElement('div');error.className='meta-muted'; start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error(t('screens.key_rotation_view.text_052'));if(!oldP.el.value||!newP.el.value)throw new Error(t('screens.key_rotation_view.text_053'));if(newP.el.value!==new2.el.value)throw new Error(t('screens.key_rotation_view.text_054'));if(oldP.el.value===newP.el.value)throw new Error(t('screens.key_rotation_view.text_055'));if(!await confirmPasswordBoundarySpaces(newP.el.value)){start.disabled=false;return;}if(!window.confirm(t('screens.key_rotation_view.text_074'))){start.disabled=false;return;}cachedOldBundle=await derive(oldP.el.value);await verifyOldPassword(cachedOldBundle);cachedNewBundle=await derive(newP.el.value);const stateNow=await client.start({newRootKey:cachedNewBundle.rootPair.publicKeyB64,newBlockchainKey:cachedNewBundle.blockchainPair.publicKeyB64,newClientKey:cachedNewBundle.clientPair.publicKeyB64,forkFromBlock:selected.blockNumber,forkFromHash:selected.blockHash,reasonCode:Number(reason.value),comment:comment.value});updateTopbar(stateNow.rotationStatus);await runCopy(stateNow); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}}); setRoot(head,oldP.wrap,newP.wrap,new2.wrap,reasonWrap,comment,list,more,start,error);void load(); } async function askNewPasswordAndCopy(s){ const card=statusCard(s), p=input(t('screens.key_rotation_view.text_021'));const go=document.createElement('button');go.className='primary-btn';go.textContent=t('screens.key_rotation_view.text_007');const err=document.createElement('div');err.className='meta-muted';go.addEventListener('click',async()=>{go.disabled=true;try{cachedNewBundle=await derive(p.el.value);if(cachedNewBundle.blockchainPair.publicKeyB64!==s.newBlockchainKey)throw new Error(t('screens.key_rotation_view.text_056'));await runCopy(s);}catch(e){err.textContent=e?.message||e;go.disabled=false;}});setRoot(card,note(t('screens.key_rotation_view.text_022')),p.wrap,go,err); } async function runCopy(s){ const card=statusCard(s), info=note(t('screens.key_rotation_view.text_023'));setRoot(card,info); try{await client.copyCandidateChain({rotation:s,newBundle:cachedNewBundle,onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=t('screens.key_rotation_view.text_065', { value1: current, value2: total });}});await client.waitUntilPublished({onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=t('screens.key_rotation_view.text_066', { value1: current, value2: total });}});await client.finishChain();await refresh();}catch(e){root.append(note(e?.message||String(e)));const retry=document.createElement('button');retry.className='primary-btn';retry.textContent=t('screens.key_rotation_view.text_008');retry.addEventListener('click',()=>void refresh());root.append(retry);} } async function renderChainReady(s){ if(cachedOldBundle&&cachedNewBundle){ setRoot(statusCard(s),note(t('screens.key_rotation_view.text_024'))); try{const next=await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});if(next?.rotationStatus==='CHAIN_READY'){pollView(next);return;}await refresh();return;}catch(e){const latest=await client.status().catch(()=>null);if(latest?.rotationStatus!==s.rotationStatus&&latest?.rotationStatus){await refresh();return;}root.append(note(e?.message||String(e)));} } const oldP=input(t('screens.key_rotation_view.text_025'));const newP=input(t('screens.key_rotation_view.text_026'));const go=document.createElement('button');go.className='primary-btn';go.textContent=t('screens.key_rotation_view.text_009');const err=document.createElement('div');err.className='meta-muted'; go.addEventListener('click',async()=>{go.disabled=true;try{const oldCandidate=await derive(oldP.el.value);const newCandidate=await derive(newP.el.value);const next=await client.rotatePda({login,solanaEndpoint,oldBundle:oldCandidate,newBundle:newCandidate,storagePwd});cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate;if(next?.rotationStatus==='CHAIN_READY'){pollView(next);return;}await refresh();}catch(e){err.textContent=e?.message||String(e);go.disabled=false;void client.status().then(latest=>{if(latest.rotationStatus!==s.rotationStatus)void refresh();}).catch(()=>{});}});setRoot(statusCard(s),note(t('screens.key_rotation_view.text_027')),oldP.wrap,newP.wrap,go,err); } function pollView(s){setRoot(statusCard(s),note(s.rotationStatus==='REBUILDING_SERVER'?t('screens.key_rotation_view.text_047'):t('screens.key_rotation_view.text_048')));timer=setTimeout(()=>void refresh(),POLL_MS);} async function renderWalletMigration(s){ const oldP=cachedOldBundle?null:input(t('screens.key_rotation_view.text_028')); const newP=cachedNewBundle?null:input(t('screens.key_rotation_view.text_029')); const info=note(t('screens.key_rotation_view.text_030')); const warning=note(t('screens.key_rotation_view.text_031')); const details=document.createElement('div');details.className='card stack';details.innerHTML=t('screens.key_rotation_view.text_057'); const refreshBalance=document.createElement('button');refreshBalance.className='secondary-btn';refreshBalance.type='button';refreshBalance.textContent=t('screens.key_rotation_view.text_010'); const transfer=document.createElement('button');transfer.className='primary-btn';transfer.type='button';transfer.textContent=t('screens.key_rotation_view.text_011'); const skip=document.createElement('button');skip.className='secondary-btn';skip.type='button';skip.textContent=t('screens.key_rotation_view.text_012'); const continueButton=document.createElement('button');continueButton.className='primary-btn';continueButton.type='button';continueButton.textContent=t('screens.key_rotation_view.text_013');continueButton.style.display='none'; const err=document.createElement('div');err.className='meta-muted'; let oldWallet=null,newWallet=null,oldBalance=null; let transferFinished=false; const updateActions=()=>{ transfer.style.display=transferFinished?'none':''; skip.style.display=transferFinished?'none':''; continueButton.style.display=transferFinished?'':'none'; }; const resolveBundles=async()=>{ const oldCandidate=cachedOldBundle||(oldP?.el.value?await derive(oldP.el.value):null); const newCandidate=cachedNewBundle||(newP?.el.value?await derive(newP.el.value):null); if(!oldCandidate||!newCandidate)throw new Error(t('screens.key_rotation_view.text_058')); if(String(oldCandidate.blockchainPair?.publicKeyB64||'')!==String(s.oldBlockchainKey||''))throw new Error(t('screens.key_rotation_view.text_059')); if(String(newCandidate.blockchainPair?.publicKeyB64||'')!==String(s.newBlockchainKey||''))throw new Error(t('screens.key_rotation_view.text_060')); cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate; }; const prepareWallets=async()=>{ await resolveBundles(); oldWallet=await getSolanaWalletFromStoredSecret(cachedOldBundle.blockchainPair.privatePkcs8B64); newWallet=await getSolanaWalletFromStoredSecret(cachedNewBundle.blockchainPair.privatePkcs8B64); const [oldB,newB]=await Promise.all([ getBalanceSol({endpoint:solanaEndpoint,address:oldWallet.address}), getBalanceSol({endpoint:solanaEndpoint,address:newWallet.address}), ]); oldBalance=oldB; details.innerHTML=`${th('screens.key_rotation_view.text_072')}${h(oldWallet.address)}${h(formatSol(oldB.sol,9))} SOL${th('screens.key_rotation_view.text_073')}${h(newWallet.address)}${h(formatSol(newB.sol,9))} SOL`; if(!transferFinished)transfer.disabled=false; }; refreshBalance.addEventListener('click',async()=>{refreshBalance.disabled=true;if(!transferFinished)transfer.disabled=true;err.textContent='';try{await prepareWallets();}catch(e){err.textContent=e?.message||String(e);}finally{refreshBalance.disabled=false;}}); transfer.addEventListener('click',async()=>{transfer.disabled=true;refreshBalance.disabled=true;skip.disabled=true;err.textContent='';try{ if(!oldWallet||!newWallet||!oldBalance)await prepareWallets(); if(Number(oldBalance?.lamports||0)>0){ const result=await transferAllSol({endpoint:solanaEndpoint,fromKeypair:oldWallet.keypair,toAddress:newWallet.address}); details.insertAdjacentHTML('beforeend',`${result.skipped?t('screens.key_rotation_view.text_049'):t('screens.key_rotation_view.text_067', { value1: h(formatSol(Number(result.lamports)/1_000_000_000,9)), value2: h(result.signature) })}`); }else{ details.insertAdjacentHTML('beforeend', `${th('remaining.html_key_rotation_view.the_old_wallet_has_no_sol_to_transfer')}`); } transferFinished=true; updateActions(); }catch(e){err.textContent=e?.message||String(e);transfer.disabled=false;skip.disabled=false;}finally{refreshBalance.disabled=false;}}); continueButton.addEventListener('click',async()=>{continueButton.disabled=true;refreshBalance.disabled=true;err.textContent='';try{ const next=await client.continueRotation({walletMigrationStatus:'COMPLETE'}); if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;} await refresh(); }catch(e){err.textContent=e?.message||String(e);continueButton.disabled=false;refreshBalance.disabled=false;}}); skip.addEventListener('click',async()=>{skip.disabled=true;transfer.disabled=true;refreshBalance.disabled=true;err.textContent='';try{ const next=await client.continueRotation({walletMigrationStatus:'SKIPPED'}); if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;} await refresh(); }catch(e){err.textContent=e?.message||String(e);skip.disabled=false;transfer.disabled=!oldWallet;refreshBalance.disabled=false;}}); updateActions(); const nodes=[statusCard(s),info,warning];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(details,refreshBalance,transfer,skip,continueButton,err);setRoot(...nodes); if(cachedOldBundle&&cachedNewBundle)void prepareWallets().catch(e=>{err.textContent=e?.message||String(e);}); } async function renderMessageMigration(s){ const oldP=cachedOldBundle?null:input(t('screens.key_rotation_view.text_032')); const newP=cachedNewBundle?null:input(t('screens.key_rotation_view.text_033')); const progress=note(t('screens.key_rotation_view.text_034')); const go=document.createElement('button');go.className='primary-btn';go.type='button';go.textContent=t('screens.key_rotation_view.text_014'); const err=document.createElement('div');err.className='meta-muted'; const resolveBundles=async()=>{ const oldCandidate=cachedOldBundle||(oldP?.el.value?await derive(oldP.el.value):null); const newCandidate=cachedNewBundle||(newP?.el.value?await derive(newP.el.value):null); if(!oldCandidate||!newCandidate)throw new Error(t('screens.key_rotation_view.text_061')); if(String(oldCandidate.clientPair?.publicKeyB64||'')!==String(s.oldClientKey||''))throw new Error(t('screens.key_rotation_view.text_062')); if(String(newCandidate.clientPair?.publicKeyB64||'')!==String(s.newClientKey||''))throw new Error(t('screens.key_rotation_view.text_063')); cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate; }; const run=async()=>{ go.disabled=true;err.textContent='';await resolveBundles(); const cutoff=Number(s.updatedAtMs||0);if(!cutoff)throw new Error(t('screens.key_rotation_view.text_064')); let processed=0; const contacts=await authService.listContacts(); const items=Array.isArray(contacts?.dialogs)?contacts.dialogs:Array.isArray(contacts)?contacts:[]; const peers=[...new Set(items.map(x=>String(x?.login||x?.peerLogin||'').trim()).filter(Boolean))]; for(let i=0;ivoid run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;})); const nodes=[statusCard(s),note(t('screens.key_rotation_view.text_035')),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes); if(cachedOldBundle&&cachedNewBundle)void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}); } async function refresh(){if(disposed)return;if(timer){clearTimeout(timer);timer=null;}try{const s=await client.status();const st=String(s.rotationStatus||'NONE');updateTopbar(st);if(st==='NONE'){await renderNone();return;}if(st==='COPYING_CHAIN'){if(cachedNewBundle)await runCopy(s);else await askNewPasswordAndCopy(s);return;}if(st==='CHAIN_READY'){await renderChainReady(s);return;}if(['ROTATING_PDA','PDA_ROTATED','REBUILDING_SERVER'].includes(st)){pollView(s);return;}if(st==='WALLET_MIGRATION'){await renderWalletMigration(s);return;}if(st==='MESSAGE_MIGRATION'){await renderMessageMigration(s);return;}if(st==='FINALIZING'){const next=await client.continueRotation({});if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note(t('screens.key_rotation_view.text_036')),Object.assign(document.createElement('button'),{className:'primary-btn',textContent:t('screens.key_rotation_view.text_015'),onclick:exitAfterComplete}));return;}setRoot(note(t('screens.key_rotation_view.text_070', { value1: st })));}catch(e){const retry=document.createElement('button');retry.type='button';retry.className='primary-btn';retry.textContent=t('screens.key_rotation_view.text_016');retry.addEventListener('click',()=>void refresh());setRoot(note(t('screens.key_rotation_view.text_071', { value1: e?.message||e })),retry);timer=setTimeout(()=>void refresh(),5000);}} void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen; }