Files
SHiNE-server/shine-UI/js/pages/key-rotation-view.js
T

198 lines
23 KiB
JavaScript

import { createTopBar } from '../components/topbar.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', title:'Смена ключей', hideToolbar:true };
const POLL_MS=1800;
function h(v){return String(v??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[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:'Публикация TECH_FORK',CHAIN_READY:'Новая цепочка готова',ROTATING_PDA:'Ожидание Solana',PDA_ROTATED:'PDA обновлена',REBUILDING_SERVER:'Перестройка сервера',WALLET_MIGRATION:'Перенос средств',MESSAGE_MIGRATION:'Перешифрование сообщений',FINALIZING:'Завершение',COMPLETE:'Готово',NONE:'Новая ротация'})[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:'Смена ключей',...(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();
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('Текущий пароль не соответствует ключам 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;}
async function renderNone(){
const head=note('Выберите последний блок, которому вы доверяете. Новый fork начнётся после него одним TECH_FORK, подписанным новым blockchain key; старый префикс цепочки не перепубликуется.');
const oldP=input('Текущий пароль'); const newP=input('Новый пароль'); const new2=input('Повторите новый пароль');
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='<span class="field-label">Причина</span>';reasonWrap.append(reason);
const comment=document.createElement('textarea');comment.className='text-input';comment.rows=3;comment.maxLength=1024;comment.placeholder='Необязательный комментарий для истории';
const list=document.createElement('div');list.className='stack';const more=document.createElement('button');more.className='secondary-btn';more.type='button';more.textContent='Показать более ранние блоки';
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=`<span class="nav-row__label">#${b.blockNumber} · ${new Date(Number(b.timestampMs)||0).toLocaleString('ru-RU')}</span><span class="nav-row__hint">${short(b.blockHash)}</span>`;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='Начать смену ключей';
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});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;}});setRoot(card,note('Для продолжения введите новый пароль, использованный при начале ротации. Пока смена ключей активна, выйти из процедуры нельзя.'),p.wrap,go,err);
}
async function runCopy(s){
const card=statusCard(s), info=note('Создаётся и публикуется TECH_FORK нового сегмента в Arweave/Turbo. Обычные записи аккаунта в это время заблокированы.');setRoot(card,info);
try{await client.copyCandidateChain({rotation:s,newBundle:cachedNewBundle,onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=`Прогресс: ${current} / ${total}`;}});await client.waitUntilPublished({onProgress:({current,total})=>{card.querySelectorAll('.meta-muted')[1].textContent=`Опубликовано: ${current} / ${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='Повторить / продолжить';retry.addEventListener('click',()=>void refresh());root.append(retry);}
}
async function renderChainReady(s){
if(cachedOldBundle&&cachedNewBundle){
setRoot(statusCard(s),note('Новая цепочка готова. Ключи в Solana меняются автоматически в рамках той же процедуры.'));
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 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);}
async function renderWalletMigration(s){
const oldP=cachedOldBundle?null:input('Старый пароль');
const newP=cachedNewBundle?null:input('Новый пароль');
const info=note('После смены blockchain key меняется и Solana-кошелёк. На этом шаге можно перевести весь доступный SOL со старого кошелька на новый за вычетом сетевой комиссии.');
const warning=note('Автоматически переносится только SOL. Другие активы и средства автоматически не переносятся; при необходимости переведите их со старых адресов вручную.');
const details=document.createElement('div');details.className='card stack';details.innerHTML='<span class="meta-muted">Проверьте старый и новый кошельки.</span>';
const refreshBalance=document.createElement('button');refreshBalance.className='secondary-btn';refreshBalance.type='button';refreshBalance.textContent='Обновить баланс';
const transfer=document.createElement('button');transfer.className='primary-btn';transfer.type='button';transfer.textContent='Перевести';
const skip=document.createElement('button');skip.className='secondary-btn';skip.type='button';skip.textContent='Пропустить';
const continueButton=document.createElement('button');continueButton.className='primary-btn';continueButton.type='button';continueButton.textContent='Продолжить';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('Введите старый и новый пароли');
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()=>{
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=`<strong>Старый кошелёк</strong><span class="meta-muted">${h(oldWallet.address)}</span><span>${h(formatSol(oldB.sol,9))} SOL</span><strong>Новый кошелёк</strong><span class="meta-muted">${h(newWallet.address)}</span><span>${h(formatSol(newB.sol,9))} SOL</span>`;
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',`<span class="meta-muted">${result.skipped?'Перевод не потребовался.':`Переведено ${h(formatSol(Number(result.lamports)/1_000_000_000,9))} SOL. Tx: ${h(result.signature)}`}</span>`);
}else{
details.insertAdjacentHTML('beforeend','<span class="meta-muted">На старом кошельке нет SOL для переноса.</span>');
}
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('Старый пароль');
const newP=cachedNewBundle?null:input('Новый пароль');
const progress=note('Подготовка перешифрования личных сообщений…');
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()=>{
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();
const cutoff=Number(s.updatedAtMs||0);if(!cutoff)throw new Error('Сервер не вернул время начала миграции сообщений');
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;i<peers.length;i++){
const peer=peers[i];
while(true){
progress.textContent=`Перешифрование сообщений: ${processed}. Диалог ${i+1}/${peers.length}: ${peer}`;
const page=await authService.getDirectMessages({peerLogin:peer,limit:100,reencryptedBeforeMs:cutoff});
const messages=Array.isArray(page?.messages)?page.messages:[];
if(messages.length===0)break;
for(const m of messages){
const blobB64=await authService.buildReencryptedLocalDm({
blobB64:m.blobB64,login,
oldClientPrivatePkcs8B64:cachedOldBundle.clientPair.privatePkcs8B64,
newClientPrivatePkcs8B64:cachedNewBundle.clientPair.privatePkcs8B64,
reencryptedAtMs:cutoff,
});
await authService.reencryptDirectMessage({blobB64});processed++;
progress.textContent=`Перешифровано сообщений: ${processed}. Диалог ${i+1}/${peers.length}: ${peer}`;
}
}
}
const next=await client.continueRotation({});
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;}));
const nodes=[statusCard(s),note('Локальные входящие и исходящие копии будут приведены к новому client key. Клиент сначала пробует старый ключ, а для сообщений, уже пришедших после смены PDA, – новый. На сервер собеседника повторная отправка не выполняется.'),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('Смена ключей завершена.'),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;
}