SHA256
Исправить подпись сигналов звонка и ширину чата
This commit is contained in:
@@ -4583,6 +4583,7 @@
|
||||
"connection_lost_reconnecting": "Connection lost. Reconnecting…",
|
||||
"call_ended": "Call ended",
|
||||
"user_is_busy": "User is busy",
|
||||
"user_is_offline": "User is offline",
|
||||
"connecting": "Connecting…",
|
||||
"shine_incoming_call": "SHiNE: incoming call",
|
||||
"another_user": "another user",
|
||||
|
||||
@@ -4583,6 +4583,7 @@
|
||||
"connection_lost_reconnecting": "Связь прервалась. Переподключаем…",
|
||||
"call_ended": "Звонок завершён",
|
||||
"user_is_busy": "Пользователь занят",
|
||||
"user_is_offline": "Абонент не в сети",
|
||||
"connecting": "Соединяем…",
|
||||
"shine_incoming_call": "SHiNE: входящий звонок",
|
||||
"another_user": "другим пользователем",
|
||||
|
||||
@@ -1314,7 +1314,7 @@ export class AuthService {
|
||||
const cleanLogin = (login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Нет login для авто-входа');
|
||||
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin, targetSessionId);
|
||||
if (!sessionMaterial?.sessionId || !sessionMaterial?.sessionKey || !sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет сохраненного ключа сессии');
|
||||
}
|
||||
@@ -1400,7 +1400,7 @@ export class AuthService {
|
||||
includeClientSignature = true,
|
||||
timeMs = Date.now(),
|
||||
} = {}) {
|
||||
const cleanToLogin = String(toLogin || '').trim();
|
||||
const requestedToLogin = String(toLogin || '').trim();
|
||||
const cleanTargetMode = String(targetMode || '').trim();
|
||||
const cleanTargetSessionId = String(targetSessionId || '').trim();
|
||||
const cleanSignalType = String(signalType || '').trim();
|
||||
@@ -1408,7 +1408,7 @@ export class AuthService {
|
||||
const cleanLogin = String(this.currentLogin || '').trim();
|
||||
const cleanSessionId = String(this.currentSessionId || '').trim();
|
||||
if (!cleanLogin || !cleanSessionId) throw new Error('SendSignal: нет активного login/sessionId');
|
||||
if (!cleanToLogin || !cleanSignalType || !cleanSignalRequestId) {
|
||||
if (!requestedToLogin || !cleanSignalType || !cleanSignalRequestId) {
|
||||
throw new Error('SendSignal: не переданы toLogin/signalType/signalRequestId');
|
||||
}
|
||||
if (cleanTargetMode !== SIGNAL_TARGET_SINGLE && cleanTargetMode !== SIGNAL_TARGET_ALL) {
|
||||
@@ -1418,12 +1418,17 @@ export class AuthService {
|
||||
throw new Error('SendSignal: targetSessionId обязателен для single_session');
|
||||
}
|
||||
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет сохранённого session key для SendSignal');
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin, cleanSessionId);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8 || String(sessionMaterial.sessionId || '').trim() !== cleanSessionId) {
|
||||
throw new Error('SendSignal: ключ активной сессии не найден; выполните вход заново');
|
||||
}
|
||||
const sessionPrivateKey = await importPkcs8Ed25519(sessionMaterial.sessionPrivPkcs8);
|
||||
|
||||
// Сервер заменяет login адресата на каноническое значение из user registry
|
||||
// до проверки подписи. Подписываем то же значение, а не вариант из UI.
|
||||
const cleanToLogin = await this.resolveCanonicalDisplayLogin(requestedToLogin);
|
||||
if (!cleanToLogin) throw new Error('SendSignal: не удалось определить канонический login адресата');
|
||||
|
||||
const dataText = typeof data === 'string' ? data : JSON.stringify(data || {});
|
||||
const dataSha256B64 = await sha256Base64FromText(dataText);
|
||||
|
||||
|
||||
@@ -2620,6 +2620,10 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
scheduleOutgoingAckTimeout(call);
|
||||
} catch (error) {
|
||||
recordCallTimeline(call, 'invite_broadcast_failed', toErrorText(error), 'warn');
|
||||
if (String(error?.code || '').toUpperCase() === 'NO_TARGET_SESSIONS') {
|
||||
await finalizeCall(call, { localReasonCode: 'no_answer', debugReason: 'invite_failed:peer_offline' });
|
||||
throw new Error(t('remaining.call.user_is_offline'));
|
||||
}
|
||||
const text = String(error?.message || '').toUpperCase();
|
||||
const isNotAuth = text.includes('NOT_AUTHENTICATED');
|
||||
if (isNotAuth) {
|
||||
|
||||
@@ -138,7 +138,7 @@ async function createUploadContext({ login, sessionId, wsUrl }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
if (!cleanLogin || !cleanSessionId) throw new Error('Нет активной пользовательской сессии');
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin, cleanSessionId);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет сохранённого session key для загрузки файла');
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ async function getBackgroundPreview(payload, session, signal, onRealtimeEvent, t
|
||||
// Never send a session signature to an unencrypted endpoint in production.
|
||||
if (url.protocol !== 'wss:' || url.username || url.password) { trace('unsafe_endpoint'); return ''; }
|
||||
trace('session_material_load');
|
||||
const material = await loadSessionMaterial(session.login);
|
||||
const material = await loadSessionMaterial(session.login, session.sessionId);
|
||||
if (material?.sessionId !== session.sessionId || !material?.sessionKey || !material?.sessionPrivPkcs8) { trace('session_material_missing'); return ''; }
|
||||
trace('session_material_ready');
|
||||
const privateKey = await importPkcs8Ed25519(material.sessionPrivPkcs8);
|
||||
|
||||
@@ -5,9 +5,10 @@ import {
|
||||
} from './crypto-utils.js';
|
||||
|
||||
const DB_NAME = 'shine-ui-auth';
|
||||
const DB_VERSION = 1;
|
||||
const DB_VERSION = 2;
|
||||
const STORE_SECRETS = 'encrypted-secrets';
|
||||
const STORE_SESSIONS = 'session-keys';
|
||||
const STORE_SESSIONS_V2 = 'session-keys-by-id';
|
||||
const FALLBACK_SECRETS_KEY = 'shine-ui-auth-secrets-fallback-v1';
|
||||
const FALLBACK_SESSIONS_KEY = 'shine-ui-auth-sessions-fallback-v1';
|
||||
|
||||
@@ -22,6 +23,11 @@ function normalizeLoginStorageKey(login) {
|
||||
return String(login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeSessionStorageKey(login, sessionId) {
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
return cleanSessionId ? `${normalizeLoginStorageKey(login)}\n${cleanSessionId}` : '';
|
||||
}
|
||||
|
||||
function readFallbackRow(storageKey, login) {
|
||||
try {
|
||||
if (typeof localStorage === 'undefined') return null;
|
||||
@@ -67,6 +73,9 @@ function openDb() {
|
||||
if (!db.objectStoreNames.contains(STORE_SESSIONS)) {
|
||||
db.createObjectStore(STORE_SESSIONS, { keyPath: 'login' });
|
||||
}
|
||||
if (!db.objectStoreNames.contains(STORE_SESSIONS_V2)) {
|
||||
db.createObjectStore(STORE_SESSIONS_V2, { keyPath: 'key' });
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error || new Error(t('remaining.key_storage.indexeddb_is_unavailable')));
|
||||
@@ -161,21 +170,51 @@ export async function updateEncryptedUserSecrets(login, storagePwd, updater) {
|
||||
|
||||
export async function saveSessionMaterial(login, material) {
|
||||
const normalizedLogin = normalizeLoginStorageKey(login);
|
||||
const sessionId = String(material?.sessionId || '').trim();
|
||||
if (!sessionId) throw new Error('Нельзя сохранить session material без sessionId');
|
||||
const row = {
|
||||
login: normalizedLogin,
|
||||
...material,
|
||||
sessionId,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
const sessionKey = normalizeSessionStorageKey(normalizedLogin, sessionId);
|
||||
const indexedRow = { ...row, key: sessionKey };
|
||||
memorySessions.set(sessionKey, row);
|
||||
memorySessions.set(normalizedLogin, row);
|
||||
try {
|
||||
await put(STORE_SESSIONS, row);
|
||||
// Старая запись нужна только чтобы resumeSession(login) мог выбрать
|
||||
// последнюю сессию без sessionId. Подписывающий код всегда берёт V2 по id.
|
||||
await Promise.all([
|
||||
put(STORE_SESSIONS_V2, indexedRow),
|
||||
put(STORE_SESSIONS, row),
|
||||
]);
|
||||
} catch {
|
||||
writeFallbackRow(FALLBACK_SESSIONS_KEY, sessionKey, row);
|
||||
writeFallbackRow(FALLBACK_SESSIONS_KEY, normalizedLogin, row);
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadSessionMaterial(login) {
|
||||
export async function loadSessionMaterial(login, sessionId = '') {
|
||||
const normalizedLogin = normalizeLoginStorageKey(login);
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
const sessionKey = normalizeSessionStorageKey(normalizedLogin, cleanSessionId);
|
||||
if (sessionKey) {
|
||||
let row = null;
|
||||
try { row = await get(STORE_SESSIONS_V2, sessionKey); } catch {}
|
||||
row = row || memorySessions.get(sessionKey) || readFallbackRow(FALLBACK_SESSIONS_KEY, sessionKey);
|
||||
if (row) return row;
|
||||
|
||||
// Совместимость с единственной записью старых версий: использовать её
|
||||
// можно только для того же sessionId, чтобы не подписать запрос чужим ключом.
|
||||
let legacyRow = null;
|
||||
try { legacyRow = await get(STORE_SESSIONS, normalizedLogin); } catch {}
|
||||
legacyRow = legacyRow || readFallbackRow(FALLBACK_SESSIONS_KEY, normalizedLogin);
|
||||
return String(legacyRow?.sessionId || '').trim() === cleanSessionId ? legacyRow : null;
|
||||
}
|
||||
|
||||
// Вызовы без sessionId оставлены только для выбора единственной старой
|
||||
// сессии при авто-входе. Подписи всегда должны передавать sessionId.
|
||||
let row = null;
|
||||
try { row = await get(STORE_SESSIONS, normalizedLogin); } catch {}
|
||||
row = row || memorySessions.get(normalizedLogin) || readFallbackRow(FALLBACK_SESSIONS_KEY, normalizedLogin);
|
||||
|
||||
@@ -62,7 +62,7 @@ async function createUploadContext({ login, sessionId, wsUrl }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
if (!cleanLogin || !cleanSessionId) throw new Error(t('remaining.file_errors.no_active_user_session'));
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin, cleanSessionId);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error(t('remaining.file_errors.session_key_for_uploading_files_is_missing_on_this_dev'));
|
||||
}
|
||||
|
||||
@@ -271,13 +271,18 @@
|
||||
.dm-chat-screen {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
|
||||
.dm-chat-screen > .dm-chat-wrap {
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
/* Скроллбар скрыт, как во всём приложении (app-shell--scrollbar-hidden действует только на
|
||||
@@ -327,6 +332,9 @@
|
||||
|
||||
|
||||
.dm-messages-log {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@@ -1378,6 +1386,7 @@
|
||||
|
||||
|
||||
.dm-chat-screen .bubble {
|
||||
min-width: 0;
|
||||
max-width: min(85%, 34rem);
|
||||
padding: 10px 12px 7px;
|
||||
border-radius: 17px;
|
||||
@@ -1387,6 +1396,9 @@
|
||||
box-shadow: none;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dm-chat-screen .bubble-reply-preview { min-width: 0; max-width: 100%; box-sizing: border-box; }
|
||||
.dm-chat-screen .bubble-reply-preview-author,
|
||||
.dm-chat-screen .bubble-reply-preview-text { min-width: 0; overflow-wrap: anywhere; }
|
||||
.dm-chat-screen .bubble.in { background: var(--surface); border-bottom-left-radius: 5px; }
|
||||
.dm-chat-screen .bubble.out { background: var(--bubble-out); border-bottom-right-radius: 5px; }
|
||||
/* Время и статус — в конце последней строки (эксперимент V4, принят); не влезают — переносятся */
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const auth = readFileSync(new URL('../js/services/auth-service.js', import.meta.url), 'utf8');
|
||||
const vault = readFileSync(new URL('../js/services/key-vault.js', import.meta.url), 'utf8');
|
||||
const handler = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/messages/Net_SendSignal_Handler.java', import.meta.url), 'utf8');
|
||||
|
||||
test('SendSignal берёт ключ только с текущим sessionId и подписывает канонический login адресата', () => {
|
||||
assert.match(auth, /loadSessionMaterial\(cleanLogin, cleanSessionId\)/);
|
||||
assert.match(auth, /resolveCanonicalDisplayLogin\(requestedToLogin\)/);
|
||||
assert.match(auth, /ключ активной сессии не найден/);
|
||||
});
|
||||
|
||||
test('key vault хранит независимый материал для каждой сессии одного login', () => {
|
||||
assert.match(vault, /session-keys-by-id/);
|
||||
assert.match(vault, /normalizeSessionStorageKey\(login, sessionId\)/);
|
||||
assert.match(vault, /loadSessionMaterial\(login, sessionId = ''\)/);
|
||||
assert.match(vault, /String\(legacyRow\?\.sessionId \|\| ''\)\.trim\(\) === cleanSessionId/);
|
||||
});
|
||||
|
||||
test('для call_invite без онлайн-сессии сервер возвращает NO_TARGET_SESSIONS', () => {
|
||||
assert.match(handler, /if \(targets\.isEmpty\(\)\) \{/);
|
||||
assert.doesNotMatch(handler, /sendIncomingCallPushToOfflineSessions/);
|
||||
});
|
||||
Reference in New Issue
Block a user