import { coreHashBytes, coreHex, readCoreBlock, signCoreContentPair } from './core-content.js'; import { base64ToBytes, bytesToBase64 } from './crypto-utils.js'; import { updateShineUserPdaOnSolana, readShineUserPda } from './shine-user-pda-service.js'; import { updateEncryptedUserSecrets } from './key-vault.js'; import { SHINE_CORE_LINE_TECH, SHINE_CORE_MAX_BLOCK_NUMBER } from './protocol-tags.js'; const TE = new TextEncoder(); const TECH_FORK_SUBTYPE = 2; function payload(resp) { return resp?.payload && typeof resp.payload === 'object' ? resp.payload : (resp || {}); } function assertOk(resp, op) { if (Number(resp?.status) >= 200 && Number(resp?.status) < 300) return payload(resp); const p = payload(resp); const responseCode = resp?.code || resp?.error || resp?.errorCode || ''; const responseMessage = resp?.message || ''; const message = p?.message || p?.error || p?.code || responseMessage || responseCode || `${op} failed (${resp?.status ?? '?'})`; const error = new Error(String(message)); error.code = p?.code || p?.errorCode || responseCode; error.response = resp; throw error; } function concat(...chunks) { const len = chunks.reduce((n, c) => n + c.length, 0); const out = new Uint8Array(len); let p = 0; for (const c of chunks) { out.set(c, p); p += c.length; } return out; } function be16(v) { const a=new Uint8Array(2); new DataView(a.buffer).setUint16(0, Number(v), false); return a; } function be32(v) { const a=new Uint8Array(4); new DataView(a.buffer).setUint32(0, Number(v), false); return a; } function be64(v) { const a=new Uint8Array(8); new DataView(a.buffer).setBigInt64(0, BigInt(v), false); return a; } function normalizeComment(value) { return String(value || '').trim().replace(/\r\n/g,'\n').replace(/\r/g,'\n'); } function blockNumber(value) { if (!Number.isInteger(value) || value < 0 || value > SHINE_CORE_MAX_BLOCK_NUMBER) throw new Error('Некорректный номер CORE'); return value; } function timestampMs(core) { const ms = Number(core.timestamp * 1000n); if (!Number.isSafeInteger(ms)) throw new Error('Некорректное время CORE'); return ms; } function makeForkBody({ oldBlockchainKeyB64, forkPointBlock, forkPointHash, forkPointTimestampMs, parentTipBlock, parentTipHash, parentTipTimestampMs, reasonCode, comment }) { const oldKey=base64ToBytes(oldBlockchainKeyB64); if(oldKey.length!==32) throw new Error('Некорректный старый blockchain key'); const c=TE.encode(normalizeComment(comment)); if(c.length>1024) throw new Error('Комментарий больше 1024 UTF-8 байт'); const discarded=blockNumber(parentTipBlock)-blockNumber(forkPointBlock); if(discarded<0 || ![1,2,3,4].includes(reasonCode)) throw new Error('Некорректная точка fork или причина'); return concat(oldKey,be32(forkPointBlock),coreHashBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),coreHashBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(reasonCode),be16(c.length),c); } export const KEY_ROTATION_REASONS = Object.freeze([ { code:1, label:'Обычная смена пароля / ключей' }, { code:2, label:'Возможная компрометация ключей' }, { code:3, label:'Подтверждённая компрометация – откат истории' }, { code:4, label:'Восстановление доступа' }, ]); export class KeyRotationClient { constructor(authService) { this.auth = authService; } async status() { return assertOk(await this.auth.ws.request('KeyRotationStatus', {}), 'KeyRotationStatus'); } async start(args) { return assertOk(await this.auth.ws.request('KeyRotationStart', args), 'KeyRotationStart'); } async abort() { return assertOk(await this.auth.ws.request('KeyRotationAbort', {}), 'KeyRotationAbort'); } async continueRotation(args={}) { return assertOk(await this.auth.ws.request('KeyRotationContinue', args), 'KeyRotationContinue'); } async finishChain() { return assertOk(await this.auth.ws.request('KeyRotationFinishChain', {}), 'KeyRotationFinishChain'); } async notifyPdaRotation(signature) { return assertOk(await this.auth.ws.request('KeyRotationRotatePda', { pdaRotationSignature: signature }), 'KeyRotationRotatePda'); } async getMyBlockchain({ beforeBlock=null, limit=50, includeBlockBytes=false }={}) { const page=assertOk(await this.auth.ws.request('GetMyBlockchain', { beforeBlock, limit, includeBlockBytes }), 'GetMyBlockchain'); // The original cutoff picker needs time and hash, now derived from signed CORE. return {...page, blocks:await Promise.all((page.blocks||[]).map(async row=>{ const checked=await readCoreBlock(row); return {...row,blockHash:checked.coreHash,timestampMs:timestampMs(checked.core)}; }))}; } async getBlock(blockchainName, number) { const row=assertOk(await this.auth.ws.request('GetBlockchainBlock', { blockchainName, blockNumber:number }), 'GetBlockchainBlock'); if(row.blockNumber!==number || String(row.blockchainName||'').toLowerCase()!==blockchainName.toLowerCase()) throw new Error('CORE source mismatch'); return readCoreBlock({...row,contentDataItemB64:null}); } async addCandidate({ blockNumber, prevBlockHash, coreDataItemB64, contentDataItemB64 }) { return assertOk(await this.auth.ws.request('KeyRotationAddBlock', { blockNumber, prevBlockHash, coreDataItemB64, contentDataItemB64 }, 30000), 'KeyRotationAddBlock'); } async #resolveTechLineTail(source, point) { // Search the frozen source prefix, not the active TECH head (which may be after cutoff). // The line selector lives in CORE and works even when CONTENT is missing. let entry=point; for(;;) { if(entry.core.blockNumber===0 || entry.core.line?.lineCode===SHINE_CORE_LINE_TECH) { return {lineCode:SHINE_CORE_LINE_TECH,prevLineBlockNumber:entry.core.blockNumber,prevLineCoreHash32:coreHashBytes(entry.coreHash)}; } const previous=await this.getBlock(source,entry.core.blockNumber-1); if(previous.coreHash!==coreHex(entry.core.prevCoreHash32)) throw new Error('Нарушена связь CORE в исходной цепочке'); entry=previous; } } async copyCandidateChain({ rotation, newBundle, onProgress=()=>{} }) { const cutoff=blockNumber(rotation.forkFromBlock); const source=String(rotation.sourceBlockchainName||''); if(!source || cutoff===SHINE_CORE_MAX_BLOCK_NUMBER) throw new Error('Некорректное состояние ротации'); if(String(newBundle?.blockchainPair?.publicKeyB64||'') !== String(rotation.newBlockchainKey||'')) throw new Error('Новый пароль выводит другой blockchain key'); const total=1; if((Number(rotation.progressCurrent)||0)>=total){onProgress({phase:'copy',current:total,total});return;} const owner32=base64ToBytes(newBundle.blockchainPair.publicKeyB64); const privateKey=newBundle.blockchainPair.privateKey; const tipBlock=blockNumber(rotation.sourceTipBlock); if(tipBlock{} }={}) { const started=Date.now(); while(Date.now()-started0 && Number(s.progressCurrent)>=Number(s.progressTotal)) return s; await new Promise(r=>setTimeout(r,1500)); } throw new Error('Публикация candidate-цепочки ещё не завершилась. Можно закрыть окно и продолжить позже.'); } async rotatePda({ login, solanaEndpoint, oldBundle, newBundle, storagePwd }) { const rotation=await this.status(); 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){ const tx=await updateShineUserPdaOnSolana({ login, solanaEndpoint, rootPrivatePkcs8B64:oldBundle.rootPair.privatePkcs8B64, blockchainPrivatePkcs8B64:oldBundle.blockchainPair.privatePkcs8B64, clientPrivatePkcs8B64:oldBundle.clientPair.privatePkcs8B64, payerPrivatePkcs8B64:oldBundle.blockchainPair.privatePkcs8B64, authorityMode:'root', newRootPublicKey32:base64ToBytes(newBundle.rootPair.publicKeyB64), newRootPrivatePkcs8B64:newBundle.rootPair.privatePkcs8B64, nextClientPublicKey32:base64ToBytes(newBundle.clientPair.publicKeyB64), newBlockchainPublicKey32:base64ToBytes(newBundle.blockchainPair.publicKeyB64), newBlockchainPrivatePkcs8B64:newBundle.blockchainPair.privatePkcs8B64, }); signature=String(tx.signature||''); if(!signature)throw new Error('Solana не вернула signature ротации'); } // После подтверждённой транзакции сначала сохраняем новые ключи локально; // ответ сервера может потеряться при гонке с 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; } } }