SHA256
232 lines
16 KiB
JavaScript
232 lines
16 KiB
JavaScript
import { createAns104DataItem, createAns104DataItemWithRawParts, parseAns104DataItem } from './ans104-data-item.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_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_TYPE_TAG_NAME } from './protocol-tags.js';
|
||
|
||
const TE = new TextEncoder();
|
||
const ZERO_HASH = '0'.repeat(64);
|
||
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 hexToBytes(hex) {
|
||
const s=String(hex||'').trim().toLowerCase(); if(!/^[0-9a-f]{64}$/.test(s)) throw new Error('Ожидался SHA-256 hash');
|
||
const out=new Uint8Array(32); for(let i=0;i<32;i++) out[i]=parseInt(s.slice(i*2,i*2+2),16); return out;
|
||
}
|
||
function bytesToHex(bytes) { return Array.from(bytes || [], (b)=>b.toString(16).padStart(2,'0')).join(''); }
|
||
function normalizeComment(value) { return String(value || '').trim().replace(/\r\n/g,'\n').replace(/\r/g,'\n'); }
|
||
function readFrameTimestampMs(frame) {
|
||
if (!(frame instanceof Uint8Array) || frame.length < 82) throw new Error('Некорректный SHiNE Frame');
|
||
const seconds = new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getBigInt64(74, false);
|
||
return Number(seconds * 1000n);
|
||
}
|
||
function readFrameType(frame) {
|
||
if (!(frame instanceof Uint8Array) || frame.length < 88) throw new Error('Некорректный SHiNE Frame');
|
||
const view=new DataView(frame.buffer,frame.byteOffset,frame.byteLength);
|
||
return { type:view.getUint16(82,false), subType:view.getUint16(84,false) };
|
||
}
|
||
function readExplicitLinePrefix(frame) {
|
||
if (!(frame instanceof Uint8Array) || frame.length < 132) throw new Error('Некорректный line Frame');
|
||
const view=new DataView(frame.buffer,frame.byteOffset,frame.byteLength);
|
||
return {
|
||
lineCode:view.getInt32(88,false),
|
||
prevLineNumber:view.getInt32(92,false),
|
||
prevLineHash:bytesToHex(frame.slice(96,128)),
|
||
lineSequence:view.getInt32(128,false),
|
||
};
|
||
}
|
||
function makeForkBody({ lineCode=0, prevLineNumber, prevLineHash, lineSequence, 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=Number(parentTipBlock)-Number(forkPointBlock);
|
||
if(discarded<0) throw new Error('Некорректная точка fork');
|
||
if(Number(lineCode)!==0 || !Number.isInteger(Number(prevLineNumber)) || Number(prevLineNumber)<0 || !Number.isInteger(Number(lineSequence)) || Number(lineSequence)<1) {
|
||
throw new Error('Некорректная TECH line для FORK');
|
||
}
|
||
return concat(be32(lineCode),be32(prevLineNumber),hexToBytes(prevLineHash),be32(lineSequence),oldKey,be32(forkPointBlock),hexToBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),hexToBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(Number(reasonCode)),be16(c.length),c);
|
||
}
|
||
function makeFrame({ prevHash, back32Hash=ZERO_HASH, blockNumber, type, subType, version=1, body, timestampMs=Date.now() }) {
|
||
const bodyBytes=body || new Uint8Array(0);
|
||
const size=2+32+32+4+4+8+2+2+2+bodyBytes.length;
|
||
return concat(be16(1),hexToBytes(prevHash),hexToBytes(back32Hash),be32(size),be32(blockNumber),be64(Math.floor(Number(timestampMs)/1000)),be16(type),be16(subType),be16(version),bodyBytes);
|
||
}
|
||
|
||
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 }={}) {
|
||
return assertOk(await this.auth.ws.request('GetMyBlockchain', { beforeBlock, limit, includeBlockBytes }), 'GetMyBlockchain');
|
||
}
|
||
async getBlock(blockchainName, blockNumber) {
|
||
return assertOk(await this.auth.ws.request('GetBlockchainBlock', { blockchainName, blockNumber }), 'GetBlockchainBlock');
|
||
}
|
||
async addCandidate({ blockNumber, prevBlockHash, blockBytesB64 }) {
|
||
return assertOk(await this.auth.ws.request('KeyRotationAddBlock', { blockNumber, prevBlockHash, blockBytesB64 }, 30000), 'KeyRotationAddBlock');
|
||
}
|
||
|
||
async #resolveTechLineTail(source, cutoff) {
|
||
for(let n=Number(cutoff);n>0;n--) {
|
||
const block=await this.getBlock(source,n);
|
||
const parsed=parseAns104DataItem(base64ToBytes(block.blockBytesB64));
|
||
const kind=readFrameType(parsed.data);
|
||
if(kind.type!==0 || (kind.subType!==1 && kind.subType!==TECH_FORK_SUBTYPE)) continue;
|
||
const line=readExplicitLinePrefix(parsed.data);
|
||
if(line.lineCode!==0 || line.lineSequence<1) throw new Error(`Некорректная TECH line в блоке #${n}`);
|
||
return {
|
||
prevLineNumber:n,
|
||
prevLineHash:String(block.blockHash||''),
|
||
lineSequence:line.lineSequence+1,
|
||
};
|
||
}
|
||
const header=await this.getBlock(source,0);
|
||
return { prevLineNumber:0, prevLineHash:String(header.blockHash||''), lineSequence:1 };
|
||
}
|
||
|
||
async copyCandidateChain({ rotation, newBundle, onProgress=()=>{} }) {
|
||
const cutoff=Number(rotation.forkFromBlock); const source=String(rotation.sourceBlockchainName||'');
|
||
if(!source || !Number.isInteger(cutoff) || cutoff<0) 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 forkSource=await this.getBlock(source,cutoff);
|
||
const tipBlock=Number(rotation.sourceTipBlock);
|
||
const tipSource=tipBlock===cutoff?forkSource:await this.getBlock(source,tipBlock);
|
||
const forkParsed=parseAns104DataItem(base64ToBytes(forkSource.blockBytesB64));
|
||
const tipParsed=parseAns104DataItem(base64ToBytes(tipSource.blockBytesB64));
|
||
const techTail=await this.#resolveTechLineTail(source,cutoff);
|
||
const forkBody=makeForkBody({
|
||
lineCode:0, prevLineNumber:techTail.prevLineNumber, prevLineHash:techTail.prevLineHash, lineSequence:techTail.lineSequence,
|
||
oldBlockchainKeyB64:rotation.oldBlockchainKey, forkPointBlock:cutoff, forkPointHash:rotation.forkFromHash,
|
||
forkPointTimestampMs:readFrameTimestampMs(forkParsed.data), parentTipBlock:tipBlock, parentTipHash:rotation.sourceTipHash,
|
||
parentTipTimestampMs:readFrameTimestampMs(tipParsed.data), reasonCode:rotation.reasonCode, comment:rotation.comment,
|
||
});
|
||
const techTimestampMs=Number(rotation.createdAtMs)||readFrameTimestampMs(tipParsed.data)+1000;
|
||
const techBlockNumber=cutoff+1;
|
||
const techBack32Hash=techBlockNumber<32?ZERO_HASH:String((await this.getBlock(source,techBlockNumber-32)).blockHash||'');
|
||
const techFrame=makeFrame({prevHash:rotation.forkFromHash,back32Hash:techBack32Hash,blockNumber:techBlockNumber,type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody,timestampMs:techTimestampMs});
|
||
const techRaw=await createAns104DataItem({owner32,privateKey,data:techFrame,tags:[{name:SHINE_APP_TAG_NAME,value:SHINE_APP_TAG_VALUE},{name:SHINE_TYPE_TAG_NAME,value:'tech'}]});
|
||
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,blockBytesB64:bytesToBase64(techRaw)});
|
||
onProgress({phase:'copy',current:1,total:1});
|
||
}
|
||
|
||
async #sourcePrevHash(source, blockNumber) {
|
||
if(blockNumber<=0) return ZERO_HASH;
|
||
const prev=await this.getBlock(source,blockNumber-1);
|
||
return String(prev.blockHash||'');
|
||
}
|
||
|
||
async waitUntilPublished({ timeoutMs=180000, onProgress=()=>{} }={}) {
|
||
const started=Date.now();
|
||
while(Date.now()-started<timeoutMs) {
|
||
const s=await this.status();
|
||
onProgress({ phase:'publish', current:Number(s.progressCurrent)||0, total:Number(s.progressTotal)||0, status:s.rotationStatus });
|
||
if(s.rotationStatus!=='COPYING_CHAIN') return s;
|
||
if(Number(s.progressTotal)>0 && 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),
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
|
||
function nullIfEmpty(value) { const s=String(value||'').trim(); return s || null; }
|