Локализовать интерфейс SHiNE на русский и английский

This commit is contained in:
AidarKC
2026-11-09 16:45:21 +03:00
parent 526941eb33
commit 405b9a91a7
133 changed files with 12464 additions and 3296 deletions
+46 -45
View File
@@ -1,3 +1,4 @@
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';
@@ -6,12 +7,12 @@ 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 };
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=>({'&':'&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 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}){
@@ -19,11 +20,11 @@ export function render({navigate,chrome}){
// До запуска смену можно закрыть; после старта выход назад запрещён.
function updateTopbar(status){
const canExit=status==='NONE' || status==='COMPLETE';
chrome?.setTopbar(createTopBar({title:'Смена ключей',...(canExit?{back:{label:'←',onClick:()=>navigate('access-keys-view')}}:{})}));
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:'Смена ключей'}));
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();
@@ -32,7 +33,7 @@ export function render({navigate,chrome}){
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');
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');}
@@ -40,50 +41,50 @@ export function render({navigate,chrome}){
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 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='<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='Показать более ранние блоки';
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=`<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 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('Выберите последний доверенный блок');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(!await confirmPasswordBoundarySpaces(newP.el.value)){start.disabled=false;return;}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;}});
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('Новый пароль');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);
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('Создаётся и публикуется 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);}
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('Новая цепочка готова. Ключи в Solana меняются автоматически в рамках той же процедуры.'));
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('Текущий пароль');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);
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'?'Сервер перестраивает текущую рабочую историю по новому fork.':'Ожидаем подтверждение нового состояния PDA в Solana.'));timer=setTimeout(()=>void refresh(),POLL_MS);}
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('Старый пароль');
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 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;
@@ -97,9 +98,9 @@ export function render({navigate,chrome}){
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');
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;
};
@@ -112,7 +113,7 @@ export function render({navigate,chrome}){
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>`;
details.innerHTML=`<strong>${th('screens.key_rotation_view.text_072')}</strong><span class="meta-muted">${h(oldWallet.address)}</span><span>${h(formatSol(oldB.sol,9))} SOL</span><strong>${th('screens.key_rotation_view.text_073')}</strong><span class="meta-muted">${h(newWallet.address)}</span><span>${h(formatSol(newB.sol,9))} SOL</span>`;
if(!transferFinished)transfer.disabled=false;
};
@@ -121,7 +122,7 @@ export function render({navigate,chrome}){
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>`);
details.insertAdjacentHTML('beforeend',`<span class="meta-muted">${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) })}</span>`);
}else{
details.insertAdjacentHTML('beforeend','<span class="meta-muted">На старом кошельке нет SOL для переноса.</span>');
}
@@ -145,22 +146,22 @@ export function render({navigate,chrome}){
}
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 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('Введите старый и новый пароли');
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');
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('Сервер не вернул время начала миграции сообщений');
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:[];
@@ -168,7 +169,7 @@ export function render({navigate,chrome}){
for(let i=0;i<peers.length;i++){
const peer=peers[i];
while(true){
progress.textContent=`Перешифрование сообщений: ${processed}. Диалог ${i+1}/${peers.length}: ${peer}`;
progress.textContent=t('screens.key_rotation_view.text_068', { value1: processed, value2: i+1, value3: peers.length, value4: 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;
@@ -180,7 +181,7 @@ export function render({navigate,chrome}){
reencryptedAtMs:cutoff,
});
await authService.reencryptDirectMessage({blobB64});processed++;
progress.textContent=`Перешифровано сообщений: ${processed}. Диалог ${i+1}/${peers.length}: ${peer}`;
progress.textContent=t('screens.key_rotation_view.text_069', { value1: processed, value2: i+1, value3: peers.length, value4: peer });
}
}
}
@@ -189,10 +190,10 @@ export function render({navigate,chrome}){
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);
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('Смена ключей завершена.'),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);}}
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;
}