Смена пароля работает: восстановить ротацию ключей

This commit is contained in:
AidarKC
2026-10-28 19:00:46 +03:00
parent ab61787ee7
commit 7b88b61b22
7 changed files with 144 additions and 35 deletions
+30 -18
View File
@@ -15,7 +15,14 @@ function input(label,type='password'){const wrap=document.createElement('label')
export function render({navigate,chrome}){
const screen=document.createElement('section');screen.className='stack';
chrome?.setTopbar(createTopBar({title:'Смена ключей',back:{label:'←',onClick:()=>navigate('access-keys-view')}}));
// До запуска смену можно закрыть; после старта выход назад запрещён.
function updateTopbar(status){
const canExit=status==='NONE' || status==='COMPLETE';
chrome?.setTopbar(createTopBar({title:'Смена ключей',...(canExit?{back:{label:'←',onClick:()=>navigate('access-keys-view')}}:{})}));
window.dispatchEvent(new CustomEvent('shine-key-rotation-active',{detail:{active:!canExit}}));
}
// Пока статус с сервера не прочитан, не разблокируем навигацию преждевременно.
chrome?.setTopbar(createTopBar({title:'Смена ключей'}));
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();
@@ -27,6 +34,7 @@ export function render({navigate,chrome}){
if(bundle.rootPair.publicKeyB64!==bytesToBase64(pda.rootKey) || bundle.blockchainPair.publicKeyB64!==bytesToBase64(pda.blockchain.blockchainPublicKey) || bundle.clientPair.publicKeyB64!==bytesToBase64(pda.clientKey)) throw new Error('Текущий пароль не соответствует ключам PDA');
}
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=`<strong>${h(stageText(s.rotationStatus))}</strong><span class="meta-muted">${h(s.sourceBlockchainName||'')} → ${h(s.candidateBlockchainName||'')}</span><span class="meta-muted">Прогресс: ${Number(s.progressCurrent||0)} / ${Number(s.progressTotal||0)}</span>${s.lastError?`<span>${h(s.lastError)}</span>`:''}`;return card;}
function note(text){const c=document.createElement('div');c.className='card';c.textContent=text;return c;}
@@ -42,12 +50,12 @@ export function render({navigate,chrome}){
more.addEventListener('click',()=>void load());
const start=document.createElement('button');start.className='primary-btn';start.type='button';start.textContent='Начать смену ключей';
const error=document.createElement('div');error.className='meta-muted';
start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error('Выберите последний доверенный блок');if(!oldP.el.value||!newP.el.value)throw new Error('Введите текущий и новый пароль');if(newP.el.value!==new2.el.value)throw new Error('Новые пароли не совпадают');if(oldP.el.value===newP.el.value)throw new Error('Новый пароль должен отличаться');if(!window.confirm('После запуска все остальные сеансы этого аккаунта будут закрыты. Продолжить?')){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});await runCopy(stateNow); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}});
start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error('Выберите последний доверенный блок');if(!oldP.el.value||!newP.el.value)throw new Error('Введите текущий и новый пароль');if(newP.el.value!==new2.el.value)throw new Error('Новые пароли не совпадают');if(oldP.el.value===newP.el.value)throw new Error('Новый пароль должен отличаться');if(!window.confirm('После запуска все остальные сеансы этого аккаунта будут закрыты. Продолжить?')){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('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить публикацию TECH_FORK';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('Этот пароль выводит другой новый blockchain key');await runCopy(s);}catch(e){err.textContent=e?.message||e;go.disabled=false;}});const abort=document.createElement('button');abort.className='secondary-btn';abort.textContent='Прервать смену ключей';abort.addEventListener('click',async()=>{await client.abort();await refresh();});setRoot(card,note('Для продолжения на этом устройстве введите тот же новый пароль, который использовался при запуске.'),p.wrap,go,abort,err);
const card=statusCard(s), p=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить публикацию TECH_FORK';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('Этот пароль выводит другой новый blockchain key');await runCopy(s);}catch(e){err.textContent=e?.message||e;go.disabled=false;}});setRoot(card,note('Для продолжения введите новый пароль, использованный при начале ротации. Пока смена ключей активна, выйти из процедуры нельзя.'),p.wrap,go,err);
}
async function runCopy(s){
@@ -58,10 +66,10 @@ export function render({navigate,chrome}){
async function renderChainReady(s){
if(cachedOldBundle&&cachedNewBundle){
setRoot(statusCard(s),note('Новая цепочка готова. Ключи в Solana меняются автоматически в рамках той же процедуры.'));
try{await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});await refresh();return;}catch(e){root.append(note(e?.message||String(e)));}
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('Текущий пароль');const newP=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить смену ключей';const abort=document.createElement('button');abort.className='secondary-btn';abort.textContent='Прервать смену ключей';const err=document.createElement('div');err.className='meta-muted';
go.addEventListener('click',async()=>{go.disabled=true;try{cachedOldBundle=await derive(oldP.el.value);cachedNewBundle=await derive(newP.el.value);await client.rotatePda({login,solanaEndpoint,oldBundle:cachedOldBundle,newBundle:cachedNewBundle,storagePwd});await refresh();}catch(e){err.textContent=e?.message||String(e);go.disabled=false;}});abort.addEventListener('click',async()=>{await client.abort();await refresh();});setRoot(statusCard(s),note('Процедура была перезапущена на другом этапе. Введите старый и новый пароль, чтобы продолжить автоматическую смену ключей в Solana.'),oldP.wrap,newP.wrap,go,abort,err);
const oldP=input('Текущий пароль');const newP=input('Новый пароль');const go=document.createElement('button');go.className='primary-btn';go.textContent='Продолжить смену ключей';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('Введите старый и новый пароль. Мы восстановим ключи и продолжим существующую процедуру с актуального этапа.'),oldP.wrap,newP.wrap,go,err);
}
function pollView(s){setRoot(statusCard(s),note(s.rotationStatus==='REBUILDING_SERVER'?'Сервер перестраивает текущую рабочую историю по новому fork.':'Ожидаем подтверждение нового состояния PDA в Solana.'));timer=setTimeout(()=>void refresh(),POLL_MS);}
@@ -86,10 +94,12 @@ export function render({navigate,chrome}){
};
const resolveBundles=async()=>{
if(!cachedOldBundle){if(!oldP?.el.value)throw new Error('Введите старый пароль');cachedOldBundle=await derive(oldP.el.value);}
if(!cachedNewBundle){if(!newP?.el.value)throw new Error('Введите новый пароль');cachedNewBundle=await derive(newP.el.value);}
if(String(cachedOldBundle?.blockchainPair?.publicKeyB64||'')!==String(s.oldBlockchainKey||''))throw new Error('Старый пароль выводит другой blockchain key');
if(String(cachedNewBundle?.blockchainPair?.publicKeyB64||'')!==String(s.newBlockchainKey||''))throw new Error('Новый пароль выводит другой blockchain key');
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('Введите старый и новый пароли');
if(String(oldCandidate.blockchainPair?.publicKeyB64||'')!==String(s.oldBlockchainKey||''))throw new Error('Старый пароль выводит другой blockchain key');
if(String(newCandidate.blockchainPair?.publicKeyB64||'')!==String(s.newBlockchainKey||''))throw new Error('Новый пароль выводит другой blockchain key');
cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate;
};
const prepareWallets=async()=>{
@@ -119,12 +129,12 @@ export function render({navigate,chrome}){
}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'){navigate('access-keys-view');return;}
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'){navigate('access-keys-view');return;}
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;}});
@@ -140,10 +150,12 @@ export function render({navigate,chrome}){
const go=document.createElement('button');go.className='primary-btn';go.type='button';go.textContent='Продолжить перешифрование';
const err=document.createElement('div');err.className='meta-muted';
const resolveBundles=async()=>{
if(!cachedOldBundle){if(!oldP?.el.value)throw new Error('Введите старый пароль');cachedOldBundle=await derive(oldP.el.value);}
if(!cachedNewBundle){if(!newP?.el.value)throw new Error('Введите новый пароль');cachedNewBundle=await derive(newP.el.value);}
if(String(cachedOldBundle?.clientPair?.publicKeyB64||'')!==String(s.oldClientKey||''))throw new Error('Старый пароль выводит другой client key');
if(String(cachedNewBundle?.clientPair?.publicKeyB64||'')!==String(s.newClientKey||''))throw new Error('Новый пароль выводит другой client key');
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('Введите старый и новый пароли');
if(String(oldCandidate.clientPair?.publicKeyB64||'')!==String(s.oldClientKey||''))throw new Error('Старый пароль выводит другой client key');
if(String(newCandidate.clientPair?.publicKeyB64||'')!==String(s.newClientKey||''))throw new Error('Новый пароль выводит другой client key');
cachedOldBundle=oldCandidate;cachedNewBundle=newCandidate;
};
const run=async()=>{
go.disabled=true;err.textContent='';await resolveBundles();
@@ -172,7 +184,7 @@ export function render({navigate,chrome}){
}
}
const next=await client.continueRotation({});
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('access-keys-view');return;}
if(String(next?.rotationStatus||'')==='COMPLETE'){exitAfterComplete();return;}
await refresh();
};
go.addEventListener('click',()=>void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}));
@@ -180,6 +192,6 @@ export function render({navigate,chrome}){
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');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'){navigate('access-keys-view');return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note('Смена ключей завершена.'));return;}setRoot(note(`Неизвестное состояние ротации: ${st}`));}catch(e){setRoot(note(`Не удалось прочитать состояние смены ключей: ${e?.message||e}`));}}
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('Смена ключей завершена.'),Object.assign(document.createElement('button'),{className:'primary-btn',textContent:'Вернуться в настройки ключей',onclick:exitAfterComplete}));return;}setRoot(note(`Неизвестное состояние ротации: ${st}`));}catch(e){const retry=document.createElement('button');retry.type='button';retry.className='primary-btn';retry.textContent='Повторить проверку и продолжить';retry.addEventListener('click',()=>void refresh());setRoot(note(`Не удалось прочитать состояние смены ключей: ${e?.message||e}. Не начинайте новую ротацию — восстановим текущую.`),retry);timer=setTimeout(()=>void refresh(),5000);}}
void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen;
}