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

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
+45 -12
View File
@@ -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;
}
}