Доделать смену ключей в новой версии

Добавлена доработка сценариев ротации ключей, закрытия сессий и повторного шифрования DM.

Версия пока не проверена полностью, но ожидается рабочей.
This commit is contained in:
AidarKC
2026-10-06 18:42:55 +03:00
parent 72e62127b3
commit 79598fffa6
58 changed files with 1084 additions and 125 deletions
+119 -10
View File
@@ -62,6 +62,7 @@ const MSG_SUBTYPE_TEXT_EDIT_REPLY = 21;
const MSG_SUBTYPE_TEXT_RATING = 30;
const MSG_SUBTYPE_TEXT_REPOST = 50;
const MSG_SUBTYPE_TEXT_CHANNEL_META = 90;
const MSG_SUBTYPE_TEXT_CHANNEL_DELETE = 92;
const MSG_SUBTYPE_TEXT_ENTRYPOINT = 100;
const MSG_SUBTYPE_TEXT_EXERCISE = 110;
const MSG_SUBTYPE_TEXT_SERVICE = 120;
@@ -1453,6 +1454,12 @@ export class AuthService {
if (response.status !== 200) throw opError('CloseActiveSession', response);
}
async closeOtherSessions() {
const response = await this.ws.request('CloseOtherSessions', {});
if (response.status !== 200) throw opError('CloseOtherSessions', response);
return response.payload || {};
}
async getTrustedDeviceLoginSettings() {
const response = await this.ws.request('GetTrustedDeviceLoginSettings', {});
if (response.status !== 200) throw opError('GetTrustedDeviceLoginSettings', response);
@@ -2489,6 +2496,7 @@ export class AuthService {
MSG_SUBTYPE_TEXT_EDIT_POST,
MSG_SUBTYPE_TEXT_REPOST,
MSG_SUBTYPE_TEXT_CHANNEL_META,
MSG_SUBTYPE_TEXT_CHANNEL_DELETE,
MSG_SUBTYPE_TEXT_ENTRYPOINT,
MSG_SUBTYPE_TEXT_EXERCISE,
MSG_SUBTYPE_TEXT_SERVICE,
@@ -2631,6 +2639,40 @@ export class AuthService {
}
async addBlockChannelDelete({ login, channel, storagePwd }) {
const cleanLogin = (login || '').trim();
if (!cleanLogin) throw new Error('Missing login');
const selector = channel || {};
const owner = String(selector?.ownerBlockchainName || '').trim();
const root = Number(selector?.channelRootBlockNumber);
const key = `channel-line:${cleanLogin}:${owner}:${root}`;
return this.runLineWriteLocked(key, async () => {
const user = await this.ensureChainInitializedForLineOps(cleanLogin, storagePwd);
const blockchainName = String(user?.blockchainName || `${cleanLogin}-${BCH_SUFFIX}`).trim();
const tail = await this.resolveChannelLineTail({ login: cleanLogin, blockchainName, channel: selector });
const bodyBytes = makeTextLineBodyBytesAllowEmpty({
lineCode: tail.lineCode,
prevLineNumber: tail.prevLineNumber,
prevLineHashHex: tail.prevLineHashHex,
thisLineNumber: tail.thisLineNumber,
text: '',
});
const payload = await this.addBlockSigned({
login: cleanLogin,
storagePwd,
msgType: MSG_TYPE_TEXT,
msgSubType: MSG_SUBTYPE_TEXT_CHANNEL_DELETE,
msgVersion: 1,
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return { ...payload, channel: { ownerBlockchainName: tail.ownerBlockchainName, channelRootBlockNumber: tail.lineCode, channelRootBlockHash: tail.rootHashHex } };
});
}
onEvent(op, handler) {
if (!op || typeof handler !== 'function') return () => {};
if (!this.eventListeners.has(op)) {
@@ -2688,18 +2730,22 @@ export class AuthService {
revisionTimeMs = 0,
reencryptedAtMs = 0,
bodyBytes = new Uint8Array(0),
signerPrivatePkcs8B64 = '',
}) {
const cleanSignerLogin = this.normalizeDmLogin(signerLogin);
const cleanFromLogin = this.normalizeDmLogin(fromLogin);
const cleanToLogin = this.normalizeDmLogin(toLogin);
if (!cleanSignerLogin || !cleanFromLogin || !cleanToLogin) throw new Error('Не передан signerLogin/fromLogin/toLogin');
if (!storagePwd) throw new Error('Не передан storagePwd для подписи');
if (!storagePwd && !String(signerPrivatePkcs8B64 || '').trim()) throw new Error('Не передан ключ для подписи');
if (!(bodyBytes instanceof Uint8Array) || bodyBytes.length > DM_MAX_ENCRYPTED_BODY_BYTES) {
throw new Error(`body должен быть 0..${DM_MAX_ENCRYPTED_BODY_BYTES} байт`);
}
const secrets = await loadEncryptedUserSecrets(cleanSignerLogin, storagePwd);
const clientPriv = secrets?.clientKey || secrets?.clientKey;
let clientPriv = String(signerPrivatePkcs8B64 || '').trim();
if (!clientPriv) {
const secrets = await loadEncryptedUserSecrets(cleanSignerLogin, storagePwd);
clientPriv = String(secrets?.clientKey || '').trim();
}
if (!clientPriv) throw new Error('Не найден приватный clientKey');
const privateKey = await importPkcs8Ed25519(clientPriv);
@@ -2736,13 +2782,13 @@ export class AuthService {
return classifyDmDecryptFailure(error);
}
async decryptSignedMessageContent({ parsed, blobB64 = '', login, storagePwd }) {
async decryptSignedMessageContent({ parsed, blobB64 = '', login, storagePwd, clientPrivatePkcs8B64 = '' }) {
const parsedBlock = parsed || this.parseSignedMessageBlob(blobB64);
const messageType = Number(parsedBlock?.messageType || 0);
if (messageType !== DM_TYPE_INCOMING && messageType !== DM_TYPE_OUTGOING_COPY) {
return { text: '', plainBytes: new Uint8Array(0) };
}
if (!storagePwd) throw new Error('Не передан storagePwd для расшифровки');
if (!storagePwd && !String(clientPrivatePkcs8B64 || '').trim()) throw new Error('Не передан ключ для расшифровки');
const cleanLogin = String(login || '').trim();
if (!cleanLogin) throw new Error('Не передан login для расшифровки');
@@ -2751,8 +2797,11 @@ export class AuthService {
throw new Error('Неподдерживаемый метод шифрования DM');
}
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const clientPrivPkcs8 = String(secrets?.clientKey || '').trim();
let clientPrivPkcs8 = String(clientPrivatePkcs8B64 || '').trim();
if (!clientPrivPkcs8) {
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
clientPrivPkcs8 = String(secrets?.clientKey || '').trim();
}
if (!clientPrivPkcs8) throw new Error('Не найден приватный clientKey');
const recipientSeed = extractEd25519SeedFromPkcs8B64(clientPrivPkcs8);
const recipientX25519Priv = ed25519SeedToX25519Private(recipientSeed);
@@ -2970,7 +3019,7 @@ export class AuthService {
};
}
async getDirectMessages({ peerLogin, limit = 50, beforeTimeMs = 0, beforeMessageKey = '' } = {}) {
async getDirectMessages({ peerLogin, limit = 50, beforeTimeMs = 0, beforeMessageKey = '', reencryptedBeforeMs = 0 } = {}) {
const payload = {
peerLogin: String(peerLogin || '').trim(),
limit: Number(limit || 0),
@@ -2982,11 +3031,71 @@ export class AuthService {
if (String(beforeMessageKey || '').trim()) {
payload.beforeMessageKey = String(beforeMessageKey || '').trim();
}
if (Number.isFinite(Number(reencryptedBeforeMs)) && Number(reencryptedBeforeMs) > 0) {
payload.reencryptedBeforeMs = Math.trunc(Number(reencryptedBeforeMs));
}
const response = await this.ws.request('GetDirectMessages', payload);
if (response.status !== 200) throw opError('GetDirectMessages', response);
return response.payload || {};
}
async reencryptDirectMessage({ blobB64 }) {
const response = await this.ws.request('ReencryptDirectMessage', { blobB64: String(blobB64 || '').trim() });
if (response.status !== 200) throw opError('ReencryptDirectMessage', response);
return response.payload || {};
}
async buildReencryptedLocalDm({ blobB64, login, oldClientPrivatePkcs8B64, newClientPrivatePkcs8B64, reencryptedAtMs }) {
const parsed = this.parseSignedMessageBlob(blobB64);
const messageType = Number(parsed?.messageType || 0);
if (messageType !== DM_TYPE_INCOMING && messageType !== DM_TYPE_OUTGOING_COPY) throw new Error('Можно перешифровать только type=1/2');
const cleanLogin = this.normalizeDmLogin(login);
const owned = messageType === DM_TYPE_INCOMING
? this.normalizeDmLogin(parsed.toLogin) === cleanLogin
: this.normalizeDmLogin(parsed.fromLogin) === cleanLogin;
if (!owned) throw new Error('Сообщение не принадлежит текущему локальному архиву');
let decrypted;
try {
decrypted = await this.decryptSignedMessageContent({
parsed,
login: cleanLogin,
clientPrivatePkcs8B64: oldClientPrivatePkcs8B64,
});
} catch (oldKeyError) {
// Сообщение могло прийти уже после смены PDA и быть зашифровано новым client key.
// В этом случае нормализуем его в текущую эпоху миграции тем же новым ключом.
try {
decrypted = await this.decryptSignedMessageContent({
parsed,
login: cleanLogin,
clientPrivatePkcs8B64: newClientPrivatePkcs8B64,
});
} catch (newKeyError) {
const error = new Error('Не удалось расшифровать сообщение ни старым, ни новым client key');
error.cause = newKeyError;
throw error;
}
}
const newPublicKeyB64 = await publicKeyB64FromPkcs8Ed25519(newClientPrivatePkcs8B64);
const encryptedBody = await buildDmEncryptedBodyBytes({
plainBytes: decrypted.plainBytes,
recipientClientKeyB64: newPublicKeyB64,
});
const block = await this.buildSignedDmBlock({
signerLogin: cleanLogin,
fromLogin: parsed.fromLogin,
toLogin: parsed.toLogin,
timeMs: parsed.timeMs,
nonce: parsed.nonce,
messageType,
revisionTimeMs: parsed.revisionTimeMs,
reencryptedAtMs,
bodyBytes: encryptedBody,
signerPrivatePkcs8B64: newClientPrivatePkcs8B64,
});
return bytesToBase64(block);
}
async ackSessionDelivery(messageKey) {
const response = await this.ws.request('AckSessionDelivery', { messageKey });
if (response.status !== 200) throw opError('AckSessionDelivery', response);
@@ -3087,8 +3196,8 @@ export class AuthService {
return response.payload || {};
}
async listUserProfileChannels(login, mode, limit = 100, offset = 0) {
const response = await this.ws.request('ListUserProfileChannels', { login, mode, limit, offset });
async listUserProfileChannels(login, mode, limit = 100, offset = 0, includeDeleted = false) {
const response = await this.ws.request('ListUserProfileChannels', { login, mode, limit, offset, includeDeleted: !!includeDeleted });
if (response.status !== 200) throw opError('ListUserProfileChannels', response);
return response.payload || {};
}
+1 -2
View File
@@ -81,7 +81,7 @@ export class KeyRotationClient {
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 continuePlaceholder() { return assertOk(await this.auth.ws.request('KeyRotationContinue', {}), 'KeyRotationContinue'); }
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 }={}) {
@@ -185,7 +185,6 @@ export class KeyRotationClient {
if(storagePwd) {
await updateEncryptedUserSecrets(login, storagePwd, (current)=>({
...(current||{}),
rootKey:newBundle.rootPair.privatePkcs8B64,
blockchainKey:newBundle.blockchainPair.privatePkcs8B64,
clientKey:newBundle.clientPair.privatePkcs8B64,
}));