Files
SHiNE-server/shine-UI/tests/dm-security-notice.test.mjs
T
PixelandClaude Opus 5.5 51e12b1426 Личный чат: исправления по итогам проверки перед слиянием
- Безопасность: логин из адреса /chat/<логин> подставлялся в окно «Добавить в контакты»
  как HTML, по подготовленной ссылке выполнялся чужой код. Логин экранируется.
- Прослушивание на паузе: «Play» ждёт последний кусок записи; если звук не проигрался,
  кнопка возвращается в исходное состояние; дорожка доступна с клавиатуры, фокус после
  «Продолжить запись» не теряется.
- Настройки чатов (фон, «Без звука», «Закрепить») при переполненном хранилище действуют
  до перезагрузки вкладки, как и было заявлено в коде.
- translate="no" у окон удаления чата и добавления в контакты.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 19:30:16 +03:00

93 lines
6.1 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const source = (path) => readFileSync(new URL(path, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
const chat = source('../js/pages/chat-view.js');
const css = source('../styles/features/chat.css');
const ru = JSON.parse(source('../js/i18n/locales/ru.json'));
const en = JSON.parse(source('../js/i18n/locales/en.json'));
for (const [locale, language] of [['ru', ru], ['en', en]]) {
test(`в ${locale} есть полный текст предупреждения DM`, () => {
const note = language.screens.chat_view.security_notice;
for (const key of ['title', 'zero_knowledge_label', 'zero_knowledge', 'self_custody_label', 'self_custody', 'control_label', 'control']) {
assert.ok(typeof note[key] === 'string' && note[key].trim(), `${locale}/${key}`);
}
});
}
test('русский текст DM соответствует утверждённой пользователем редакции от 27.11.2026', () => {
assert.deepEqual(ru.screens.chat_view.security_notice, {
"title": "Ваша переписка защищена сквозным шифрованием",
"zero_knowledge_label": "Zero-Knowledge Architecture:",
"zero_knowledge": "Мы не доверяем серверам. SHiNE не хранит ваши приватные ключи и технически не имеет доступа к содержимому чатов.",
"self_custody_label": "Self-Custody & Open Source:",
"self_custody": "Ваш ключ генерируется локально из вашего логина и пароля. Никаких скрытых алгоритмов — код полностью открыт.",
"control_label": "Absolute Control:",
"control": "Забудете пароль — навсегда потеряете доступ к переписке."
});
// Текст должен отображаться напрямую через textContent, без HTML-сущностей.
for (const text of Object.values(ru.screens.chat_view.security_notice)) {
assert.doesNotMatch(text, /&#(?:x[0-9a-f]+|\d+);/iu);
}
});
test('уведомление формируется только локально и добавляется первым элементом ленты', () => {
const start = chat.indexOf('function createDmEncryptionNotice()');
const end = chat.indexOf('function renderLog(', start);
const functionBody = chat.slice(start, end);
assert.ok(start >= 0 && end > start);
assert.match(functionBody, /document\.createElement\('aside'\)/);
assert.match(functionBody, /dm-security-notice/);
assert.match(chat, /list\.innerHTML = '';\s*list\.append\(createDmEncryptionNotice\(\)\);\s*const messages = getChatMessages\(chatId\);/);
assert.doesNotMatch(functionBody, /authService|addSignedMessageToChat|sendDirectMessage|AddBlock|fetch\(/);
});
test('замок — значок приложения, шрифт справки лежит в приложении, а не грузится со стороны', () => {
const body = chat.slice(chat.indexOf('function createDmEncryptionNotice()'), chat.indexOf('function renderLog('));
assert.match(body, /iconHtml\('lock'\)/);
assert.doesNotMatch(body, /🔒/u);
const fonts = [...css.matchAll(/@font-face \{[^}]*url\("([^"]+)"\)/g)].map(([, path]) => path);
assert.equal(fonts.length, 2, 'кириллица и латиница');
for (const path of fonts) {
assert.match(path, /^\.\.\/\.\.\/assets\/fonts\//);
const data = readFileSync(new URL(path, new URL('../styles/features/', import.meta.url)));
assert.equal(data.toString('latin1', 0, 4), 'wOF2', path);
}
});
test('расшифрованная переписка не уходит в автоперевод браузера', () => {
for (const owner of ['screen', 'form', 'header']) assert.ok(chat.includes(`${owner}.translate = false;`), owner);
for (const id of ['chat-forward-modal', 'chat-external-link-modal', 'chat-delete-chat-modal', 'contact-confirm-modal']) assert.match(chat, new RegExp(`id="${id}" translate="no"`));
for (const page of ['messages-list', 'chat-media-view']) assert.match(source(`../js/pages/${page}.js`), /screen\.translate = false;/, page);
});
test('логин из адреса /chat/<логин> не становится разметкой окна «Добавить в контакты»', () => {
const start = chat.indexOf('function openConfirmContactModal(');
const body = chat.slice(start, chat.indexOf('const close', start));
assert.ok(start >= 0 && body.includes('${escapeDialogHtml(targetLogin)}'));
assert.ok(!body.includes('${targetLogin}'));
});
test('страница с первой секунды объявляет язык приложения', () => {
const index = source('../index.html');
const script = index.slice(index.indexOf('(function applyLanguageBeforePaint() {'), index.indexOf('}());', index.indexOf('applyLanguageBeforePaint')) + 5);
const key = source('../js/i18n/index.js').match(/const STORAGE_KEY = '([^']+)'/)[1];
const langFor = (saved, languages) => {
const document = { documentElement: { lang: 'en' } };
const localStorage = { getItem: (name) => (name === key ? saved : null) };
new Function('document', 'localStorage', 'navigator', script)(document, localStorage, { languages });
return document.documentElement.lang;
};
assert.equal(langFor(null, ['ru-RU', 'en-US']), 'ru');
assert.equal(langFor('en', ['ru-RU']), 'en', 'выбор в приложении важнее языка браузера');
assert.equal(langFor(null, ['de-DE', 'ru']), 'ru', 'неподдерживаемый язык пропускается, как в js/i18n');
assert.equal(langFor(null, ['de-DE']), 'en');
});
test('уведомление имеет собственные серые стили и не оформляется как bubble', () => {
assert.match(css, /\.dm-security-notice\s*\{[\s\S]*?color: var\(--text-secondary\)/);
assert.doesNotMatch(chat.slice(chat.indexOf('function createDmEncryptionNotice()'), chat.indexOf('function renderLog(')), /className = ['"`]bubble/);
});