diff --git a/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/keyRotation/Net_KeyRotationRotatePda_Handler.java b/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/keyRotation/Net_KeyRotationRotatePda_Handler.java index 8ba85c3d..329122e1 100644 --- a/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/keyRotation/Net_KeyRotationRotatePda_Handler.java +++ b/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/keyRotation/Net_KeyRotationRotatePda_Handler.java @@ -41,7 +41,18 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_ACTIVE", "Активная ротация отсутствует"); } - if (current.getStatus() == KeyRotationStatus.PDA_ROTATED) { + // Solana sync и rebuild работают независимо от уведомления клиента. + // При повторе после подтверждённой PDA возвращаем реальный этап, а не 409. + if (current.getStatus() == KeyRotationStatus.PDA_ROTATED + || current.getStatus() == KeyRotationStatus.REBUILDING_SERVER + || current.getStatus() == KeyRotationStatus.WALLET_MIGRATION + || current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION + || current.getStatus() == KeyRotationStatus.FINALIZING) { + String stored = current.getPdaRotationSignature(); + if (stored != null && !stored.isBlank() && !stored.equals(signature)) { + return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_PDA_SIGNATURE_CONFLICT", + "Для этой ротации уже сохранена другая Solana transaction signature"); + } var fresh = CurrentUsersDAO.getInstance().getByLogin(login); if (fresh != null) ctx.setCurrentUser(fresh); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current); diff --git a/VERSION.properties b/VERSION.properties index b9386650..8e37a7f3 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.20.6 -server.version=1.16.5 +client.version=1.20.7 +server.version=1.16.6 diff --git a/docs/API/19_Key_Rotation_API.md b/docs/API/19_Key_Rotation_API.md index afc7aa1d..6458ae1c 100644 --- a/docs/API/19_Key_Rotation_API.md +++ b/docs/API/19_Key_Rotation_API.md @@ -248,7 +248,7 @@ Если Solana sync успел увидеть новое PDA раньше вызова `KeyRotationRotatePda`, он умеет подтвердить ожидаемые ключи прямо из `CHAIN_READY`. Поэтому потеря клиентского запроса после уже подтверждённой Solana-транзакции не оставляет ротацию зависшей. Если API-вызов всё же приходит, handler идемпотентно возвращает текущее подтверждённое состояние. -Повтор с той же signature идемпотентен. Другая signature для уже начатого `ROTATING_PDA` возвращает conflict. +Повтор с той же signature идемпотентен: при `PDA_ROTATED`, `REBUILDING_SERVER`, `WALLET_MIGRATION`, `MESSAGE_MIGRATION` и `FINALIZING` возвращается актуальное состояние без ошибки 409. Это закрывает гонку Solana sync с уведомлением UI. Если signature ранее сохранена, конфликтующая signature возвращает conflict. ### Основные ошибки diff --git a/shine-UI/js/app.js b/shine-UI/js/app.js index 7c8a4842..b50d8c5d 100644 --- a/shine-UI/js/app.js +++ b/shine-UI/js/app.js @@ -1463,12 +1463,15 @@ function attachPageScrollToBottom(pageId, screen) { }); } +let keyRotationRouteLock = false; + async function redirectToActiveKeyRotationIfNeeded() { if (!state.session.isAuthorized || state.session.isLocalDemo) return false; try { const rotation = await new KeyRotationClient(authService).status(); const status = String(rotation?.rotationStatus || 'NONE'); - if (status !== 'NONE' && getRoute().pageId !== 'key-rotation-view') { + keyRotationRouteLock = status !== 'NONE' && status !== 'COMPLETE'; + if (keyRotationRouteLock && getRoute().pageId !== 'key-rotation-view') { navigate('key-rotation-view'); return true; } @@ -1479,6 +1482,11 @@ async function redirectToActiveKeyRotationIfNeeded() { } function renderApp() { + if (keyRotationRouteLock && state.session.isAuthorized && getRoute().pageId !== 'key-rotation-view') { + // Нельзя покинуть начатую ротацию через browser back, прямую ссылку или меню. + navigate('key-rotation-view'); + return; + } syncTrackedRouteHistory(window.location.pathname || '/'); const route = getRoute(); if (state.session.isAuthorized) { @@ -1666,6 +1674,7 @@ async function init() { }); setSessionResetHandler(() => { + keyRotationRouteLock = false; sessionRuntimeStarted = false; stopChannelsPrefetch(); startConnectionMonitor(); @@ -1677,6 +1686,10 @@ async function init() { navigate('start-view'); }); + window.addEventListener('shine-key-rotation-active', event => { + keyRotationRouteLock = Boolean(event.detail?.active); + }); + setSessionAuthorizedHandler(() => { void ensureSessionRuntimeStarted(); void processPendingCallPushActionIfPossible(); diff --git a/shine-UI/js/pages/key-rotation-view.js b/shine-UI/js/pages/key-rotation-view.js index 068d9080..46f0aed2 100644 --- a/shine-UI/js/pages/key-rotation-view.js +++ b/shine-UI/js/pages/key-rotation-view.js @@ -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=`${h(stageText(s.rotationStatus))}${h(s.sourceBlockchainName||'')} → ${h(s.candidateBlockchainName||'')}Прогресс: ${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;} @@ -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; } diff --git a/shine-UI/js/services/key-rotation-service.js b/shine-UI/js/services/key-rotation-service.js index a8f61961..71057adf 100644 --- a/shine-UI/js/services/key-rotation-service.js +++ b/shine-UI/js/services/key-rotation-service.js @@ -1,6 +1,6 @@ import { createAns104DataItem, createAns104DataItemWithRawParts, parseAns104DataItem } from './ans104-data-item.js'; import { base64ToBytes, bytesToBase64 } from './crypto-utils.js'; -import { updateShineUserPdaOnSolana } from './shine-user-pda-service.js'; +import { updateShineUserPdaOnSolana, readShineUserPda } from './shine-user-pda-service.js'; import { updateEncryptedUserSecrets } from './key-vault.js'; import { SHINE_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_TYPE_TAG_NAME } from './protocol-tags.js'; @@ -161,11 +161,44 @@ export class KeyRotationClient { async rotatePda({ login, solanaEndpoint, oldBundle, newBundle, storagePwd }) { const rotation=await this.status(); - if(rotation.rotationStatus!=='CHAIN_READY' && rotation.rotationStatus!=='ROTATING_PDA') throw new Error('Новая цепочка ещё не готова к смене PDA'); + const stage=String(rotation.rotationStatus||'NONE'); + const advanced=['PDA_ROTATED','REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING','COMPLETE']; + if(!['CHAIN_READY','ROTATING_PDA',...advanced].includes(stage)) { + throw new Error(`Продолжение ротации недоступно на этапе ${stage}. Обновите состояние.`); + } const checks=[['root',oldBundle?.rootPair?.publicKeyB64,rotation.oldRootKey],['blockchain',oldBundle?.blockchainPair?.publicKeyB64,rotation.oldBlockchainKey],['client',oldBundle?.clientPair?.publicKeyB64,rotation.oldClientKey],['new root',newBundle?.rootPair?.publicKeyB64,rotation.newRootKey],['new blockchain',newBundle?.blockchainPair?.publicKeyB64,rotation.newBlockchainKey],['new client',newBundle?.clientPair?.publicKeyB64,rotation.newClientKey]]; for(const [name,actual,expected] of checks) if(String(actual||'')!==String(expected||'')) throw new Error(`Ключ «${name}» не соответствует начатой ротации`); + + const saveNewKeys=async()=>{ + if(storagePwd) await updateEncryptedUserSecrets(login, storagePwd, current=>({ + ...(current||{}), + blockchainKey:newBundle.blockchainPair.privatePkcs8B64, + clientKey:newBundle.clientPair.privatePkcs8B64, + })); + }; + // В первую очередь выясняем реальное состояние PDA. Если sync опередил UI, + // повторная Solana-транзакция не нужна (старый ключ уже недействителен). + const pda=await readShineUserPda({login,solanaEndpoint}); + const actual=[bytesToBase64(pda.rootKey),bytesToBase64(pda.blockchain.blockchainPublicKey),bytesToBase64(pda.clientKey)]; + const expectedNew=[rotation.newRootKey,rotation.newBlockchainKey,rotation.newClientKey]; + const expectedOld=[rotation.oldRootKey,rotation.oldBlockchainKey,rotation.oldClientKey]; + const matchesNew=actual.every((key,i)=>key===expectedNew[i]); + const matchesOld=actual.every((key,i)=>key===expectedOld[i]); + if(matchesNew){ + await saveNewKeys(); + // Сервер сам увидит PDA. Если уже находится на следующем этапе, просто продолжим. + // При ROTATING_PDA с известной signature безопасно повторяем уведомление. + if(stage==='ROTATING_PDA' && rotation.pdaRotationSignature){ + try{return await this.notifyPdaRotation(rotation.pdaRotationSignature);} + catch(e){const latest=await this.status();if(advanced.includes(latest.rotationStatus))return latest;throw e;} + } + return this.status(); + } + if(!matchesOld)throw new Error('Ключи в Solana PDA не соответствуют ни старому, ни новому набору. Повторная транзакция запрещена.'); + if(advanced.includes(stage))throw new Error('Сервер уже подтвердил смену PDA, но RPC вернул старые ключи. Проверьте Solana RPC и повторите проверку.'); + let signature=String(rotation.pdaRotationSignature||''); - if(!signature) { + if(!signature){ const tx=await updateShineUserPdaOnSolana({ login, solanaEndpoint, rootPrivatePkcs8B64:oldBundle.rootPair.privatePkcs8B64, @@ -179,17 +212,17 @@ export class KeyRotationClient { newBlockchainPrivatePkcs8B64:newBundle.blockchainPair.privatePkcs8B64, }); signature=String(tx.signature||''); - if(!signature) throw new Error('Solana не вернула signature ротации'); + if(!signature)throw new Error('Solana не вернула signature ротации'); } - const state=await this.notifyPdaRotation(signature); - if(storagePwd) { - await updateEncryptedUserSecrets(login, storagePwd, (current)=>({ - ...(current||{}), - blockchainKey:newBundle.blockchainPair.privatePkcs8B64, - clientKey:newBundle.clientPair.privatePkcs8B64, - })); + // После подтверждённой транзакции сначала сохраняем новые ключи локально; + // ответ сервера может потеряться при гонке с Solana sync. + await saveNewKeys(); + try{return await this.notifyPdaRotation(signature);} + catch(e){ + const latest=await this.status(); + if(advanced.includes(latest.rotationStatus))return latest; + throw e; } - return state; } } diff --git a/shine-UI/tests/key-rotation-resume-lock.test.mjs b/shine-UI/tests/key-rotation-resume-lock.test.mjs new file mode 100644 index 00000000..5eb46f9b --- /dev/null +++ b/shine-UI/tests/key-rotation-resume-lock.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +const read = p => readFileSync(new URL(`../../${p}`, import.meta.url), 'utf8'); +const ui = read('shine-UI/js/pages/key-rotation-view.js'); +const app = read('shine-UI/js/app.js'); +const client = read('shine-UI/js/services/key-rotation-service.js'); +const server = read('SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/keyRotation/Net_KeyRotationRotatePda_Handler.java'); + +test('после начала смены в шапке нет кнопки назад и нет abort в UI', () => { + assert.match(ui, /const canExit=status==='NONE' \|\| status==='COMPLETE'/); + assert.match(ui, /updateTopbar\(stateNow\.rotationStatus\)/); + assert.doesNotMatch(ui, /client\.abort\(/); + assert.match(app, /keyRotationRouteLock && state\.session\.isAuthorized/); + assert.match(app, /navigate\('key-rotation-view'\)/); +}); +test('при восстановлении проверяются оба введённых пароля относительно ключей ротации', () => { + assert.match(ui, /await derive\(oldP\.el\.value\)/); + assert.match(ui, /await derive\(newP\.el\.value\)/); + assert.match(ui, /Старый пароль выводит другой blockchain key/); + assert.match(ui, /Новый пароль выводит другой client key/); +}); +test('серверное уведомление PDA идемпотентно на всех этапах после PDA', () => { + for (const stage of ['PDA_ROTATED','REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING']) { + assert.match(server, new RegExp('KeyRotationStatus\\.' + stage)); + } + assert.match(server, /KEY_ROTATION_PDA_SIGNATURE_CONFLICT/); +}); +test('повторное обращение не отправляет новый Solana tx, если PDA уже обновлена', () => { + assert.match(client, /const pda=await readShineUserPda/); + assert.match(client, /if\(matchesNew\)/); + assert.match(client, /if\(!matchesOld\)throw new Error/); + assert.ok(client.indexOf('if(matchesNew)') < client.indexOf('updateShineUserPdaOnSolana({')); + assert.ok(client.indexOf('await saveNewKeys();\n try{return await this.notifyPdaRotation(signature)') > 0); +}); +test('полное завершение снимает блокировку навигации', () => { + assert.match(ui, /function exitAfterComplete\(\)\{updateTopbar\('COMPLETE'\);navigate\('access-keys-view'\);\}/); + assert.match(ui, /shine-key-rotation-active/); + assert.match(app, /keyRotationRouteLock = Boolean\(event\.detail\?\.active\)/); +});