CORE/CONTENT test5593 и адаптация UI

This commit is contained in:
AidarKC
2026-11-27 00:47:13 +03:00
parent 205b7ad971
commit 873535654e
1271 changed files with 219621 additions and 1900 deletions
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const read = (p) => fs.readFileSync(path.join(root, p), 'utf8');
test('Тестовая эпоха Arweave одинакова в UI, Server и Viewer', () => {
const ui = read('shine-UI/js/services/protocol-tags.js');
const server = read('SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java');
const viewer = read('shine-UI/static-sites/arweave-viewer/index.html');
const reg = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationCertificateV1.java');
assert.match(ui, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5592'/);
assert.match(server, /NAMESPACE\s*=\s*"test5592"/);
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5592'/);
assert.match(reg, /ShineProtocolTags\.APP_TAG_VALUE/);
for (const txt of [ui, server, viewer, reg]) assert.doesNotMatch(txt, /test5591/);
});
@@ -0,0 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildAttachmentBlock, parseMessageAttachments } from '../js/services/attachment-format.js';
const root = '4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi';
const source = (name) => ({ name, size: 1837243, pr: root, mm: 'video/mp4' });
test('v2: UTF-8 имена без лишних %-кодов', () => {
const marker = buildAttachmentBlock(source('Водопад.mp4'));
assert.match(marker, /^<S:att;v=2;nm=Водопад.mp4;sz=1837243;/u);
assert.equal(parseMessageAttachments(`${marker}\nцук`).attachments[0].name, 'Водопад.mp4');
assert.equal(parseMessageAttachments(`${marker}\nцук`).text, 'цук');
});
test('v2: только служебные символы экранируются; круговой обмен', () => {
for (const name of ['Лето;фильм=1%.mp4', 'Привет<мир>.mp4', '中文;عربي=тест%.mp4']) {
const marker = buildAttachmentBlock(source(name));
assert.equal(parseMessageAttachments(marker).attachments[0].name, name);
assert.equal(marker.includes('nm='+encodeURIComponent(name)), false);
assert.doesNotMatch(marker, /nm=[^;]*;фильм/u);
}
});
test('v1: прежние URI-имена остаются читаемыми', () => {
const name = 'Водопад.mp4';
const marker = `<S:att;v=1;nm=${encodeURIComponent(name)};sz=10;pr=${root};mm=video/mp4>`;
assert.equal(parseMessageAttachments(marker).attachments[0].name, name);
});
test('v2: дубликаты, неизвестные поля и плохие escape не интерпретируются как вложение', () => {
for (const body of [
`v=2;nm=a;sz=10;sz=500;pr=${root}`,
`v=2;nm=foo;bad=value;sz=10;pr=${root}`,
`v=2;nm=abc%zz;sz=10;pr=${root}`,
`v=2;nm=abc%3;sz=10;pr=${root}`,
`v=2;nm=abc%0Aevil;sz=10;pr=${root}`,
`v=2;nm=abc;sz=-1;pr=${root}`,
`v=2;nm=abc;sz=01;pr=${root}`,
`v=2;nm=abc<b;sz=10;pr=${root}`,
`v=2;nm=abc=d;sz=10;pr=${root}`,
`v=2;nm=abc;sz=10;pr=${root};ar=wrong-id`,
]) {
assert.equal(parseMessageAttachments(`<S:att;${body}>`).attachments.length, 0, body);
}
});
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import { avatarR2Url } from '../js/services/public-file-service.js';
import { buildAvatarReference, parseAvatarReference } from '../js/services/avatar-reference.js';
import { encodePublicPiecesRoot } from '../js/services/public-pieces-root.js';
import { preparePublicFile } from '../js/services/file-preparation-service.js';
const ui = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const source = (path) => readFileSync(resolve(ui, path), 'utf8');
const pr = encodePublicPiecesRoot(new Uint8Array(32).fill(255));
test('avatar v2: PR Base58 exactly as public attachment; Arweave TX ID unchanged', () => {
assert.equal(avatarR2Url(pr), `https://files.shineup.me/${pr}`);
const value = buildAvatarReference({ pr, size: 1000 });
assert.equal(value, `<S:ava;v=2;sz=1000;pr=${pr}>`);
assert.equal(parseAvatarReference(value).pr, pr);
assert.equal(parseAvatarReference(value).source, 'r2');
const ar = 'A'.repeat(43);
const withAr = buildAvatarReference({ pr, size: 1000, ar });
assert.equal(parseAvatarReference(withAr).ar, ar);
assert.equal(parseAvatarReference(withAr).source, 'arweave');
for (const legacy of [`<S:ava;v=1;sz=1000;sha256=${'a'.repeat(64)}>`, 'AR:' + ar]) {
assert.equal(parseAvatarReference(legacy).ok, false);
}
assert.throws(() => buildAvatarReference({ pr: pr.toLowerCase(), size: 1000 }));
assert.throws(() => avatarR2Url('not-a-root'));
});
test('Avatar PR computed on the same exact bytes as public attachments', async () => {
const file = new File([Uint8Array.of(1, 2, 3, 4, 5)], 'avatar.webp', { type: 'image/webp' });
const prepared = await preparePublicFile(file);
assert.equal(prepared.pr, (await preparePublicFile(file)).pr);
assert.equal(avatarR2Url(prepared.pr), `https://files.shineup.me/${prepared.pr}`);
});
test('avatar R2 upload reuses signed public PR prepare; no avatar-specific endpoint/path', () => {
const service = source('js/services/public-file-service.js');
assert.match(service, /return uploadR2PublicFile\(\{ file, login, sessionId, wsUrl, onStatus \}\)/);
assert.match(service, /\/api\/files\/prepare/);
assert.doesNotMatch(service, /\/api\/avatars\/prepare/);
assert.doesNotMatch(service, /avatars\/\$\{/);
assert.match(source('js/components/avatar-image.js'), /resolvePublicFileUrl\(\{ pr: expectedPr, authorLogin \}\)/);
assert.match(source('js/pages/network/graph-canvas.js'), /resolvePublicFileUrl\(\{ pr, authorLogin \}\)/);
assert.match(source('js/pages/network-legacy/force-graph.js'), /resolvePublicFileUrl\(\{ pr, authorLogin \}\)/);
});
@@ -0,0 +1,38 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { verifyAns104DataItem } from '../js/services/ans104-data-item.js';
import { arweaveBlockUrl, readSignedBlock } from '../js/services/blockchain-proof-service.js';
import { bytesToBase64Url } from '../js/services/crypto-utils.js';
import { webcrypto } from 'node:crypto';
if (!globalThis.crypto?.subtle) globalThis.crypto = webcrypto;
// Изолированный эталон ANS104 (файл взят из текущего тестового блока проекта).
const signedPath = new URL('./fixtures/block11.ans104', import.meta.url);
const expectedHash = '46db963eab3e9a9aeddba0b67bb2c44daf3be3472706c25a8035ad4ae914e99f';
const expectedId = 'T0dcFEjRymardqVuTEU5HdkPjkKm8ALU7nyf6LOzCXE';
test('подпись Ed25519 полного DataItem и SHA-256 полезного блока', async () => {
const bytes = new Uint8Array(await readFile(signedPath));
const proof = await verifyAns104DataItem(bytes);
assert.equal(bytes.length, 412);
assert.equal(proof.data.length, 274);
assert.equal(proof.signatureValid, true);
assert.equal(bytesToBase64Url(proof.dataItemIdBytes), expectedId);
assert.equal(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
});
test('подмена payload не проходит проверку подписи и SHA-256', async () => {
const bytes = new Uint8Array(await readFile(signedPath));
bytes[bytes.length - 1] ^= 0x01;
const proof = await verifyAns104DataItem(bytes);
assert.equal(proof.signatureValid, false);
assert.notEqual(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
});
test('по API нельзя скачать DataItem с подменённым хешем или ID', async () => {
const bytes = new Uint8Array(await readFile(signedPath));
const authService = { ws: { request: async () => ({ status: 200, payload: {
blockHash: expectedHash, blockBytesB64: Buffer.from(bytes).toString('base64'),
} }) } };
assert.equal((await readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId})).bytes.length, 412);
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:'A'.repeat(43)}), /Arweave/);
assert.equal(arweaveBlockUrl('../evil'), '');
});
@@ -0,0 +1,114 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import {
makeSharedProfileRoute,
makeProfileRoute,
makeShineChannelRoute,
makeShineChannelShortRoute,
makeShineChannelStreamRoute,
makeShineMessageRoute,
} from '../js/services/shine-routes.js';
import { profileCardHtml } from '../js/components/profile-card.js';
const ui = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const source = (name) => readFileSync(resolve(ui, name), 'utf8');
test('публичная ссылка профиля содержит /SHiNE/Prof/<login>', () => {
assert.equal(makeSharedProfileRoute('alice@free'), 'SHiNE/Prof/alice@free');
assert.equal(makeSharedProfileRoute('Пользователь'), 'SHiNE/Prof/%D0%9F%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C');
assert.equal(makeProfileRoute('alice@free'), 'SHiNE/alice@free');
});
test('открытые ссылки профиля, канала и сообщения показывают @, а не %40', () => {
assert.equal(makeSharedProfileRoute('@innaa@free'), 'SHiNE/Prof/innaa@free');
assert.equal(makeProfileRoute('innaa@free'), 'SHiNE/innaa@free');
assert.equal(makeShineChannelShortRoute({ ownerLogin: 'innaa@free', channelName: 'news' }), 'SHiNE/innaa@free/news');
assert.equal(makeShineChannelStreamRoute({ ownerLogin: 'innaa@free', channelName: 'news', messageOrdinal: 19 }), 'SHiNE/innaa@free/news/s/19');
assert.equal(makeShineChannelRoute({ ownerBlockchainName: 'innaa@free-002', channelName: 'news' }), 'SHiNE/innaa@free-002/news');
assert.equal(makeShineMessageRoute({ ownerLogin: 'innaa@free', messageBlockchainName: 'innaa@free-002', messageBlockNumber: 25, messageOrdinal: 3, channelName: 'news' }), 'SHiNE/innaa@free/news/3');
assert.equal(makeShineMessageRoute({ messageBlockchainName: 'innaa@free-002', messageBlockNumber: 25 }), 'SHiNE/innaa@free-002/25');
// Без потери безопасности: пробел, слэш и Unicode в пути по-прежнему кодируются.
assert.equal(makeShineChannelShortRoute({ ownerLogin: 'innaa@free', channelName: 'мои новости/2026' }),
'SHiNE/innaa@free/%D0%BC%D0%BE%D0%B8%20%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8%2F2026');
const url = new URL('https://t2.shineup.me');
url.pathname = `/${makeSharedProfileRoute('innaa@free')}`;
assert.equal(url.toString(), 'https://t2.shineup.me/SHiNE/Prof/innaa@free');
});
test('отображение профиля не добавляет вторую собачку перед логином', () => {
for (const value of ['innaa@free', '@innaa@free']) {
const html = profileCardHtml({ card: { login: value }, isSelf: false });
assert.match(html, /<div class="pf-login">innaa@free<\/div>/);
assert.doesNotMatch(html, /@innaa@free/);
}
const shareSource = source('js/pages/profile-view.js');
assert.doesNotMatch(shareSource, /kicker: name \?[^\n]*· @\$\{login\}/);
});
test('при навигации старые вручную закодированные SHiNE-пути становятся читаемыми', async () => {
const previousWindow = globalThis.window;
globalThis.window = { location: { pathname: '/' } };
try {
const { toPrettyPath } = await import('../js/router.js');
assert.equal(toPrettyPath('SHiNE/innaa%40free/news/3'), 'SHiNE/innaa@free/news/3');
assert.equal(toPrettyPath('SHiNE/Prof/innaa%40free'), 'SHiNE/Prof/innaa@free');
assert.equal(toPrettyPath('chat/innaa%40free'), 'chat/innaa%40free');
} finally {
globalThis.window = previousWindow;
}
});
test('новые и старые ссылки профиля ведут на пользователя, не на канал', async () => {
const previousWindow = globalThis.window;
globalThis.window = { location: { pathname: '/' } };
try {
const { parseRouteFromPath } = await import('../js/router.js');
for (const route of ['/SHiNE/Prof/alice@free', '/SHiNE/Prof/alice%40free', '/shine/prof/alice%40free', '/SHiNE/alice@free', '/SHiNE/alice%40free']) {
const page = parseRouteFromPath(route);
assert.equal(page.pageId, 'user');
assert.equal(page.params.login, 'alice@free');
}
for (const path of ['/SHiNE/alice@free/news', '/SHiNE/alice%40free/news']) {
const channel = parseRouteFromPath(path);
assert.equal(channel.pageId, 'channel-view');
assert.equal(channel.params.channelName, 'news');
}
for (const path of ['/SHiNE/alice@free/news/3', '/SHiNE/alice%40free/news/3']) {
const thread = parseRouteFromPath(path);
assert.equal(thread.pageId, 'channel-thread-view');
assert.equal(thread.params.messageOrdinal, '3');
}
} finally {
globalThis.window = previousWindow;
}
});
test('лента получает логин владельца и может запросить фото канала', () => {
const js = source('js/pages/channel-view.js');
assert.match(js, /name: payload\.channel\?\.channelName[^\n]*\n\s+ownerLogin,/);
assert.match(js, /authorLogin: String\(channel\?\.ownerLogin \|\| channel\?\.ownerName/);
assert.match(js, /hasEventAvatar \? event\?\.avaPr : fallbackChannel\?\.avaPr/);
assert.doesNotMatch(js, /Аватар<\/span><span>.*Установлен/);
assert.match(js, /class="channel-meta-avatar-slot"/);
});
test('аватары каналов в списке, карточках, обсуждениях и шапке круглые', () => {
const files = [
['styles/features/channel.css', ['.channel-profile-avatar', '.channel-about-avatar.avatar']],
['styles/features/channels-common.css', ['.topbar-identity .avatar.channel-profile-avatar', '.channel-message-card--threads .avatar.channel-profile-avatar']],
['styles/features/channel-thread.css', ['.thread-comment--ancestor .avatar.channel-profile-avatar']],
];
for (const [file, selectors] of files) {
const css = source(file);
for (const selector of selectors) {
const declaration = css.slice(css.indexOf(selector) + selector.length).match(/^\s*\{([^}]+)\}/);
assert.ok(declaration, `${file} ${selector}`);
assert.match(declaration[1], /border-radius:\s*50%\s*;/, `${file} ${selector}`);
}
}
const channelsListCss = source('styles/features/channels-list.css');
assert.match(channelsListCss, /\.channels-screen--list \.channel-row \.avatar\s*\{[^}]*border-radius:\s*50%;/s);
});
@@ -0,0 +1,40 @@
import { expandRussian } from './i18n-source-helper.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { isDmSendEnter } from '../js/services/dm-composer-keys.js';
const read = (relative) => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8'));
test('обычный Enter отправляет, модификаторы и IME не отправляют', () => {
const normal = { key: 'Enter', shiftKey: false, ctrlKey: false, altKey: false, metaKey: false, isComposing: false };
assert.equal(isDmSendEnter(normal), true);
for (const modifier of ['shiftKey', 'ctrlKey', 'altKey', 'metaKey', 'isComposing']) {
assert.equal(isDmSendEnter({ ...normal, [modifier]: true }), false, modifier);
}
assert.equal(isDmSendEnter({ ...normal, keyCode: 229 }), false);
assert.equal(isDmSendEnter({ ...normal, key: 'a' }), false);
});
test('Enter использует существующий submit, кнопка продолжает использовать его же', () => {
const chat = read('../js/pages/chat-view.js');
assert.match(chat, /input\.addEventListener\('keydown', \(event\) => \{[\s\S]*?isDmSendEnter\(event\)[\s\S]*?event\.preventDefault\(\)[\s\S]*?form\.requestSubmit\(\)/);
assert.match(chat, /form\.addEventListener\('submit', async \(event\) =>/);
});
test('регистрация использует Alice из пяти символов', () => {
const registration = read('../js/pages/register-view.js');
assert.match(registration, /Например, Alice/);
assert.match(registration, /Alice и alice/);
assert.doesNotMatch(registration, /Например, Alex/);
});
test('список каналов учитывает бесплатные идентичности и нормализованный регистр подписок', () => {
const handler = read('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/channels/Net_ListSubscriptionsFeed_Handler.java');
const support = read('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/channels/ChannelsReadSupport.java');
assert.match(handler, /SELECT blockchain_name FROM user_identity_current WHERE LOWER\(login\)=LOWER\(\?\)/);
assert.match(handler, /WHERE LOWER\(cs\.login\)=LOWER\(\?\) AND cs\.rel_type=\?/);
assert.match(handler, /FROM user_identity_current su WHERE LOWER\(su\.login\)=LOWER\(cs\.to_login\)/);
assert.doesNotMatch(handler, /FROM solana_user_pda_current/);
assert.doesNotMatch(support, /FROM solana_user_pda_current/);
});
@@ -0,0 +1,66 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { formatChannelAddress, makeShineChannelShortRoute } from '../js/services/shine-routes.js';
import { validateChannelDisplayName, channelNameErrorText } from '../js/services/channel-name-rules.js';
const source = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
test('новый канал: 1–3 символа запрещены, 4 и 32 разрешены, 33 запрещены', () => {
for (const value of ['a', 'ab', 'abc', ' АБВ ']) {
assert.equal(validateChannelDisplayName(value).ok, false, value);
}
for (const value of ['abcd', 'tantra', 'ABC_', 'x'.repeat(32)]) {
assert.equal(validateChannelDisplayName(value).ok, true, value);
}
assert.equal(validateChannelDisplayName('x'.repeat(33)).code, 'too_long');
assert.equal(validateChannelDisplayName('1234').code, 'digits_only');
assert.equal(validateChannelDisplayName('a.bc').code, 'bad_chars');
const ru = JSON.parse(source('../js/i18n/locales/ru.json'));
assert.equal(ru.remaining.channel_validation.channel_name_is_too_short_minimum_4_characters, 'Название слишком короткое: минимум 4 символа.');
assert.equal(channelNameErrorText('too_short'), 'remaining.channel_validation.channel_name_is_too_short_minimum_4_characters'); // no browser i18n bootstrap in this unit test
});
test('адрес канала не получает лишнюю @, даже если логин начинается с @', () => {
for (const ownerLogin of ['Alice@free', '@Alice@free', '@@Alice@free']) {
assert.equal(formatChannelAddress({ ownerLogin, channelName: 'tantra' }), 'Alice@free/tantra');
}
assert.equal(formatChannelAddress({ ownerLogin: 'Alice@shine', channelName: 'course' }), 'Alice@shine/course');
assert.equal(formatChannelAddress({ ownerLogin: 'Alice@free' }), 'Alice@free');
assert.equal(makeShineChannelShortRoute({ ownerLogin: '@Alice@free', channelName: 'tantra' }), 'SHiNE/Alice@free/tantra');
});
test('адрес используется в шапке, списке, о канале, обсуждении, поиске, донате', () => {
for (const path of [
'../js/pages/channel-view.js',
'../js/pages/channels-list.js',
'../js/pages/channel-about-view.js',
'../js/pages/channel-thread-view.js',
'../js/pages/search-view.js',
'../js/pages/channel-donate-view.js',
]) {
assert.match(source(path), /formatChannelAddress\(/, path);
}
const list = source('../js/pages/channels-list.js');
assert.match(list, /technical\.textContent = channel\.technicalLabel/);
assert.doesNotMatch(list, /technical\.hidden = !!channel\.isOwnChannel/);
});
test('сервер проверяет 4–32 при AddBlock, но декодер исторических блоков не ограничивает минимум', () => {
const rules = source('../../SHiNE-server/shine-server-db/src/main/java/shine/db/channels/ChannelNameRules.java');
const handler = source('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler.java');
const body = source('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/body/CreateChannelBody.java');
assert.match(rules, /MIN_DISPLAY_NAME_LENGTH = 4;/);
assert.match(rules, /channelName length must be 4\.\.32/);
assert.match(handler, /ChannelNameRules\.requireValidPublicDisplayNameForCreate\(createChannelBody\.channelName\)/);
assert.match(handler, /"bad_channel_name"/);
assert.match(body, /MIN_NAME_LENGTH_FOR_CREATE = 4/);
assert.match(body, /checkForCreate\(\)/);
assert.match(body, /public byte\[\] toBytes\(\) \{[\s\S]*?checkForCreate\(\)/);
assert.match(handler, /createChannelBody\.checkForCreate\(\)/);
assert.match(handler, /legacyReplayName = replayMode/);
assert.match(handler, /if \(legacyReplayName\)/);
assert.doesNotMatch(body.slice(body.indexOf('public CreateChannelBody check()'), body.indexOf('public CreateChannelBody checkForCreate()')), /length < MIN_NAME_LENGTH_FOR_CREATE/);
const auth = source('../js/services/auth-service.js');
assert.match(auth, /length < 4 \|\| length > 20/);
});
@@ -0,0 +1,198 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
globalThis.window = {
location: {
origin: 'https://shineup.me', pathname: '/app',
hash: '#/chat?token=DONT_LOG', href: 'https://shineup.me/app?password=DONT_LOG',
},
__SHINE_BUILD_HASH__: 'build-test',
};
globalThis.document = { visibilityState: 'visible', title: 'Secret chat title' };
Object.defineProperty(globalThis, 'navigator', { value: { userAgent: 'Test browser' }, configurable: true });
const reporter = await import(`data:text/javascript,${encodeURIComponent(read('../js/services/client-error-reporter.js'))}`);
test('автоматическая отправка без переключателя: только при accepted=true', async () => {
const received = [];
const notified = [];
reporter.setClientErrorTransport(async (payload) => { received.push(payload); return true; });
reporter.setClientErrorSentNotifier((payload) => notified.push(payload));
assert.equal(await reporter.captureClientError({ kind: 'unit_accept', message: 'Unexpected failure' }), true);
assert.equal(received.length, 1);
assert.match(received[0].errorId, /^ERR-/);
assert.equal(received[0].clientVersion, 'build-test');
assert.equal(notified.length, 1);
reporter.setClientErrorTransport(async () => false);
assert.equal(await reporter.captureClientError({ kind: 'unit_reject', message: 'not accepted' }), false);
assert.equal(notified.length, 1);
});
test('ошибки не отправляются повторно и не создают локальную очередь', async () => {
let calls = 0;
reporter.setClientErrorTransport(async () => { calls++; throw new Error('offline'); });
assert.equal(await reporter.captureClientError({ kind: 'unit_offline', message: 'Failed to send' }), false);
assert.equal(await reporter.captureClientError({ kind: 'unit_offline', message: 'Failed to send' }), false);
assert.equal(calls, 1);
assert.equal(await reporter.captureClientError({ kind: 'unit_local', message: 'Local only', skipTransport: true }), false);
assert.equal(calls, 1);
});
test('контекст ограничен и URL/пароли/ключи не передаются', async () => {
let payload;
reporter.setClientErrorTransport(async (value) => { payload = value; return true; });
assert.equal(await reporter.captureClientError({
kind: 'unit_privacy',
message: 'password=VerySensitive token=DoNotStore Bearer ABCDEFG',
stack: 'TypeError at https://shineup.me/a?token=SECRET',
sourceUrl: 'https://shineup.me/asset.js?token=SECRET#password=other',
context: {
pageId: 'channel', status: 500, secret: 'DO_NOT_SEND',
raw: 'PRIVATE_MESSAGE', password: 'passphrase', token: 'tokenvalue',
},
}), true);
const json = JSON.stringify(payload);
for (const secret of ['VerySensitive', 'DoNotStore', 'ABCDEFG', 'DO_NOT_SEND', 'PRIVATE_MESSAGE', 'passphrase', 'tokenvalue', 'SECRET', 'DONT_LOG', 'Secret chat title']) {
assert.ok(!json.includes(secret), `leaked ${secret}`);
}
assert.equal(payload.sourceUrl, 'https://shineup.me/asset.js');
assert.equal(payload.route, '/app');
assert.equal(JSON.parse(payload.contextJson).status, '500');
});
test('все 5xx кроме 507 отслеживаются, ожидаемые 4xx и ответ логгера — нет', async () => {
const captured = [];
const source = read('../js/services/ws-client.js')
.replace("import { t } from '../i18n/index.js';", "const t = (s) => s;")
.replace("import { captureClientError } from './client-error-reporter.js';", 'const captureClientError = (value) => globalThis.__wsCaptured.push(value);')
.replace("import { defaultServerWs } from '../deploy-config.js';", "const defaultServerWs = 'wss://shineup.me/ws';");
globalThis.__wsCaptured = captured;
const { WsJsonClient } = await import(`data:text/javascript,${encodeURIComponent(source)}`);
const ws = new WsJsonClient('wss://shineup.me/ws');
for (const [op, status] of [['GetChannels', 500], ['GetChannels', 501], ['GetChannels', 400], ['GetChannels', 507], ['ClientErrorLog', 500]]) {
const requestId = `${op}-${status}`;
let resolved;
ws.pending.set(requestId, { op, resolve: (value) => { resolved = value; } });
ws.handleMessage(JSON.stringify({ op, requestId, status }));
assert.equal(resolved.status, status);
}
assert.deepEqual(captured.map((item) => item.context.status), [500, 501]);
assert.deepEqual(captured.map((item) => item.kind), ['api_server_error', 'api_server_error']);
});
test('конфиг сервера изолирует client-errors.log на 14 дней', () => {
const xml = read('../../SHiNE-server/src/main/resources/logback.xml');
assert.match(xml, /client-errors\.log/);
assert.match(xml, /<maxHistory>14<\/maxHistory>/);
assert.match(xml, /<logger name="client\.frontend" level="error" additivity="false">/);
assert.match(xml, /<totalSizeCap>150MB<\/totalSizeCap>/);
});
test('ClientErrorLog подтверждается по payload.accepted, а не по корневому полю', async () => {
const src = read('../js/services/auth-service.js');
const match = src.match(/async reportClientError\(details\) \{([\s\S]*?)\n \}/);
assert.ok(match, 'reportClientError method exists');
const report = new Function('details', `return (async function () {${match[1]}\n}).call(this);`);
globalThis.WebSocket = { OPEN: 1 };
const request = async () => ({ status: 200, payload: { accepted: true } });
const ws = { ws: { readyState: 1 }, request };
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), true);
ws.request = async () => ({ status: 200, payload: { accepted: false } });
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false);
ws.request = async () => ({ status: 500, payload: { accepted: true } });
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false);
ws.ws.readyState = 3;
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false);
});
test('BOOT ERROR отключает аварийную плашку после подключения штатного обработчика', () => {
const index = read('../index.html');
const app = read('../js/app.js');
assert.match(app, /window\.__SHINE_APP_ERROR_HANDLERS_READY__ = true;/);
const handlers = [...index.matchAll(/window\.addEventListener\('(error|unhandledrejection)', \(e\) => \{\s*([\s\S]*?)\n \}\);/g)];
assert.equal(handlers.length, 2);
for (const match of handlers) {
assert.match(match[2], /if \(window\.__SHINE_APP_ERROR_HANDLERS_READY__ === true\) return;/);
}
});
test('аварийный экран нейтральный, с причиной, источником и кнопкой перезагрузки', () => {
const index = read('../index.html');
assert.match(index, /Не удалось запустить SHiNE/);
assert.match(index, /Причина: \$/);
assert.match(index, /Источник: \$/);
assert.match(index, /Обновить страницу/);
assert.match(index, /Подробности/);
assert.match(index, /Отправка отчёта не подтверждена/);
assert.match(index, /state\.sentToServer === true/);
assert.match(index, /sentToServer: true/);
assert.doesNotMatch(index, /rgba\(120, 0, 0/);
assert.doesNotMatch(index, /\[BOOT ERROR\] \$/);
});
test('аварийный экран не показывает stack и произвольный текст исключения', () => {
const index = read('../index.html');
const match = index.match(/const updateBootOverlay = \(\) => \{([\s\S]*?)\n \};/);
assert.ok(match, 'есть функция обновления аварийного экрана');
assert.doesNotMatch(match[1], /\.stack|state\.message\s*;/);
assert.match(index, /Ошибка выполнения JavaScript \(TypeError\)/);
assert.match(index, /if \(window\.__SHINE_APP_ERROR_HANDLERS_READY__ === true\) return;/);
});
test('BOOT ERROR показывает краткую причину без приватного текста и позволяет перезагрузить страницу', async () => {
const { runInNewContext } = await import('node:vm');
const index = read('../index.html');
const match = index.match(/\(function attachBootErrorOverlay\(\) \{[\s\S]*?\}\(\)\);/);
assert.ok(match, 'загрузочный обработчик найден');
class FakeElement {
constructor(tag = 'div') { this.tag = tag; this.children = []; this.style = {}; this.dataset = {}; this.handlers = {}; this.attributes = {}; this.textContent = ''; }
setAttribute(name, value) { this.attributes[name] = value; }
append(...els) { this.children.push(...els); }
appendChild(el) { this.children.push(el); }
addEventListener(name, handler) { this.handlers[name] = handler; }
querySelector(selector) {
const key = selector.match(/^\[data-boot-error="(.*?)"\]$/)?.[1];
const descend = (el) => {
if (key && el.dataset?.bootError === key) return el;
for (const child of el.children) { const found = descend(child); if (found) return found; }
return null;
};
return descend(this);
}
}
const body = new FakeElement('body');
const handlers = {};
let reloads = 0;
const fakeWindow = {
addEventListener: (type, handler) => { handlers[type] = handler; },
location: { origin: 'https://shineup.me', reload: () => reloads++ },
};
const fakeDocument = {
documentElement: { dataset: { theme: 'dark' } }, body,
createElement: (tag) => new FakeElement(tag),
getElementById: (id) => body.children.find((el) => el.id === id) || null,
};
runInNewContext(match[0], { window: fakeWindow, document: fakeDocument, navigator: { userAgent: 'test' }, console, URL, Date, Number, String, Math });
handlers.error({
message: 'TypeError: private message text: NEVER_SHOW_ME',
filename: 'https://shineup.me/js/app.js?password=NEVER_SHOW_ME', lineno: 42, colno: 9,
error: { stack: 'TypeError: NEVER_SHOW_ME' },
});
const overlay = fakeDocument.getElementById('boot-error-overlay');
assert.ok(overlay);
assert.equal(overlay.querySelector('[data-boot-error="cause"]').textContent, 'Причина: Ошибка выполнения JavaScript (TypeError).');
assert.equal(overlay.querySelector('[data-boot-error="source"]').textContent, 'Источник: app.js:42');
assert.match(overlay.querySelector('[data-boot-error="status"]').textContent, /не подтверждена/);
const rendered = JSON.stringify(body, (k, v) => k === 'handlers' ? undefined : v);
assert.ok(!rendered.includes('NEVER_SHOW_ME'));
const buttons = overlay.children[0].children.at(-1).children;
assert.equal(buttons[0].textContent, 'Обновить страницу');
buttons[0].handlers.click();
assert.equal(reloads, 1);
});
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
getConnectionsGraphCached,
cachedConnectionsGraph,
invalidateConnectionsGraphCache,
CONNECTIONS_GRAPH_CHANGED,
} from '../js/services/connections-graph-cache.js';
import { peopleFromGraphModel } from '../js/pages/network/adapter.js';
import { engineModelFromGraphModel } from '../js/pages/network-legacy/adapter.js';
const screenPaths = ['../js/pages/network-view.js', '../js/pages/network-legacy/network-view.js'];
// Исполняем саму функцию построения модели из каждого экрана в минимальном окружении.
// Это проверяет реальные реализации, не требуя браузерного DOM для огромных экранов.
function graphModelBuilder(relativePath) {
const code = readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8');
const functionSource = code.slice(code.indexOf('function buildGraphModel('));
const stop = functionSource.indexOf('\n}\n');
assert.ok(stop > 0, `${relativePath}: buildGraphModel не найдена`);
const normalizeLogin = (value) => String(value || '').trim();
const normKey = (value) => normalizeLogin(value).toLowerCase();
const uniqueLogins = (values) => [...new Map(values.map((value) => [normKey(value), normalizeLogin(value)])).values()];
const toSet = (values) => new Set(uniqueLogins(values || []).map(normKey));
const hasLogin = (set, value) => set.has(normKey(value));
const getMarkByLogin = (rows) => new Map((rows || []).map((row) => [normKey(row.login), row]));
const state = { session: { login: 'alice' } };
const body = `${functionSource.slice(0, stop + 2)}\nreturn buildGraphModel;`;
return new Function('normalizeLogin', 'normKey', 'uniqueLogins', 'toSet', 'hasLogin', 'getMarkByLogin', 'state', 'GENDER_UNKNOWN', body)(
normalizeLogin, normKey, uniqueLogins, toSet, hasLogin, getMarkByLogin, state, 'unknown',
);
}
for (const path of screenPaths) {
test(`граф ${path}: только исходящие друзья и строгая взаимность`, () => {
const build = graphModelBuilder(path);
const graph = {
login: 'alice',
outFriends: ['Bob', 'Jill'],
outCloseFriends: ['Cara'],
inFriends: ['BOB', 'Nope'],
inCloseFriends: ['Lisa'],
outContacts: ['Contact'],
inContacts: ['Jill', 'IncomingContact'],
outFollows: ['Follow'],
};
const result = build(graph, 'alice');
assert.deepEqual(result.relations.map((r) => r.login), ['Cara', 'Bob', 'Jill']);
assert.equal(result.relations.find((r) => r.login === 'Cara').relationType, 'close_friend');
assert.equal(result.relations.find((r) => r.login === 'Bob').backward, true);
assert.equal(result.relations.find((r) => r.login === 'Jill').backward, false,
'Контакт в ответ не превращает одностороннюю дружбу во взаимную');
assert.equal(result.relations.find((r) => r.login === 'Cara').backward, false);
assert.deepEqual(build({ login: 'alice', inFriends: ['OnlyIncoming'], outContacts: ['OnlyContact'] }, 'alice').relations, []);
});
}
test('адаптеры обеих версий получают одинаковую взаимность и тип дружбы', () => {
const model = graphModelBuilder(screenPaths[0])({
login: 'alice', outFriends: ['bob'], outCloseFriends: ['cara'], inFriends: ['cara'],
}, 'alice');
const modern = peopleFromGraphModel(model).peers;
const legacy = engineModelFromGraphModel(model).nodes.slice(1);
assert.deepEqual(modern.map((peer) => [peer.person.login, peer.relationType, peer.mutual]),
[['cara', 'close_friend', true], ['bob', 'friend', false]]);
assert.deepEqual(legacy.map((peer) => [peer.login, peer.relationType, peer.mutual]),
[['cara', 'close_friend', true], ['bob', 'friend', false]]);
});
test('TTL графа — 2 минуты: до истечения повторный запрос не нужен', async () => {
const originalNow = Date.now;
let now = 10_000_000;
Date.now = () => now;
try {
invalidateConnectionsGraphCache();
let queries = 0;
const service = { serverUrl: 'wss://ttl.test', async getUserConnectionsGraph() { return { queries: ++queries }; } };
await getConnectionsGraphCached(service, 'alice');
now += 119_999;
assert.equal((await getConnectionsGraphCached(service, 'alice')).queries, 1);
now += 1;
assert.equal((await getConnectionsGraphCached(service, 'alice')).queries, 2);
} finally { Date.now = originalNow; }
});
test('общий кэш: два экрана / серверы / инвалидация / изменение в незавершённом запросе', async () => {
const previousWindow = globalThis.window;
const windowMock = new EventTarget();
globalThis.window = windowMock;
try {
let seen = 0;
windowMock.addEventListener(CONNECTIONS_GRAPH_CHANGED, () => { seen += 1; });
let queries = 0;
const service = { serverUrl: 'wss://first.test', async getUserConnectionsGraph() { return { version: ++queries }; } };
const first = await getConnectionsGraphCached(service, 'Alice');
const second = await getConnectionsGraphCached(service, 'ALICE');
assert.strictEqual(first, second);
assert.equal(queries, 1);
assert.strictEqual(cachedConnectionsGraph(service, 'alice'), first);
const secondServer = { serverUrl: 'wss://second.test', async getUserConnectionsGraph() { return { version: 77 }; } };
assert.equal((await getConnectionsGraphCached(secondServer, 'alice')).version, 77);
invalidateConnectionsGraphCache();
assert.equal(seen, 1);
assert.equal(cachedConnectionsGraph(service, 'alice'), null);
assert.equal((await getConnectionsGraphCached(service, 'alice')).version, 2);
let releaseOld;
let current = 0;
const pendingService = { serverUrl: 'wss://pending.test', getUserConnectionsGraph() {
current += 1;
return current === 1 ? new Promise((resolve) => { releaseOld = resolve; }) : Promise.resolve({ version: 'new' });
} };
const pending = getConnectionsGraphCached(pendingService, 'alice', { force: true });
invalidateConnectionsGraphCache();
releaseOld({ version: 'old' });
assert.equal((await pending).version, 'new', 'ответ старого запроса не должен воскресить устаревший снимок');
assert.equal(cachedConnectionsGraph(pendingService, 'alice').version, 'new');
} finally {
globalThis.window = previousWindow;
}
});
@@ -0,0 +1,54 @@
const fs=require('fs');
const path=require('path');
const vm=require('vm');
const assert=require('assert');
const registrations=[];
const events={};
const stateDb=new Map();
const notifications=new Map();
const cacheObj={
async match(key){return stateDb.get(key)?.clone() || null},
async put(key, response){stateDb.set(key, response)},
};
const context={
self:{
__shineStoppedCalls:new Map(),
registration:{scope:'https://shineup.me/',
async showNotification(title, options){ registrations.push({title,options}); if(options.tag) notifications.set(options.tag,{data:options.data, close(){ notifications.delete(options.tag) }}) },
async getNotifications({tag}){return notifications.get(tag)?[notifications.get(tag)]:[]},
},
clients:{async matchAll(){return []}},
addEventListener(name, handler){events[name]=handler},
skipWaiting(){},
},
caches:{async open(){return cacheObj}},
Response, URL, Promise, Date, Number, String, Math, Map, Object, JSON, encodeURIComponent,
};
vm.createContext(context);
vm.runInContext(fs.readFileSync(path.resolve(__dirname, '../firebase-messaging-sw.js'),'utf8'), context);
async function push(data){const pending=[];events.push({data:{text(){return JSON.stringify(data)}}, waitUntil(p){pending.push(p)}});await Promise.all(pending)}
async function read(to,from){const pending=[];events.message({data:{type:'SHINE_DM_READ',toLogin:to,fromLogin:from},waitUntil(p){pending.push(p)}});await Promise.all(pending)}
(async()=>{
for(let i=1;i<=5;i++){
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:`m${i}`,unreadCount:i,notificationVersionMs:1000+i});
}
assert.strictEqual(registrations.length,5,'every new message renotifies');
assert(registrations.every(x=>x.options.renotify===true && x.options.silent===false));
assert.strictEqual(notifications.size,1,'one tag per conversation');
assert.strictEqual(registrations.at(-1).options.body,'5 непрочитанных сообщений');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Kolya',messageKey:'k1',unreadCount:2,notificationVersionMs:2000});
assert.strictEqual(notifications.size,2);
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m5',unreadCount:5,notificationVersionMs:1005});
assert.strictEqual(registrations.length,6,'duplicate push ignored');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m6',unreadCount:4,notificationVersionMs:1003});
assert.strictEqual(registrations.at(-1).options.body,'5 непрочитанных сообщений','late push cannot downgrade unread count');
await read('AnNa','Vasya');
assert.strictEqual(notifications.size,1,'read closes only Vasya notification');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m7',unreadCount:4,notificationVersionMs:1004});
assert.strictEqual(notifications.size,1,'old push after read suppressed');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'Vasya',messageKey:'m8',unreadCount:1,notificationVersionMs:1008});
assert.strictEqual(notifications.size,2,'new push after read can notify');
await push({kind:'new_message',toLogin:'AnNa',fromLogin:'MashA',messageKey:'z1',unreadCount:21,notificationVersionMs:3000});
assert.strictEqual(registrations.at(-1).options.body,'21 непрочитанное сообщение');
console.log('PASS: 5 alerts, tags per conversation, counter, replay suppression, late-push ordering, read close and newer-push delivery');
})().catch(e=>{console.error(e);process.exitCode=1});
@@ -0,0 +1,52 @@
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');
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', 'encryption', 'servers', 'derivation', 'rotation', 'source', 'warning_label', 'warning', 'recovery']) {
assert.ok(typeof note[key] === 'string' && note[key].trim(), `${locale}/${key}`);
}
});
}
test('русский текст DM соответствует утверждённой пользователем редакции от 13.11.2026', () => {
assert.deepEqual(ru.screens.chat_view.security_notice, {
"title": "Ваша переписка защищена сквозным шифрованием",
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
"warning_label": "Важно:",
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
});
// Текст должен отображаться напрямую через 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('уведомление имеет собственные серые стили и не оформляется как 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/);
});
@@ -0,0 +1,95 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { state } from '../js/state.js';
import {
clearUserFileServerCache, getUserFileServer, resolveUserFileUrl,
refreshUserFileServerOnError, updatedUserFileUrlAfterError, userFileObjectUrl,
SERVER_LOOKUP_COOLDOWN_MS,
} from '../js/services/user-file-server-service.js';
import { buildDmFileTechBlock, parseDmTechBlocks } from '../js/services/dm-tech-blocks.js';
import { DM_FILE_RETENTION_MS, isDmFileExpired } from '../js/services/dm-file-service.js';
import { encodePublicPiecesRoot } from '../js/services/public-pieces-root.js';
const login = 'anna@shine';
const id = encodePublicPiecesRoot(new Uint8Array(32).fill(7));
// Чистим RAM-кэш между сценариями: без IndexedDB, localStorage и таймеров.
test('федерация: единый API, один параллельный запрос, правильные файловые домены', async () => {
clearUserFileServerCache();
state.entrySettings.shineServerHttp = 'https://reader.example.com';
const originalFetch = globalThis.fetch;
const requests = [];
globalThis.fetch = async (url) => {
requests.push(url);
return { ok: true, json: async () => ({ serverLogin: 'node-b@shine', serverUrl: 'https://node-b.example.net/ws' }) };
};
try {
const results = await Promise.all(Array.from({ length: 12 }, () => getUserFileServer(login)));
assert.equal(requests.length, 1);
assert.equal(requests[0], 'https://reader.example.com/api/files/user-server?login=anna%40shine');
assert.equal(results[0].hostname, 'node-b.example.net');
assert.equal(await resolveUserFileUrl({ login, id }), `https://files.node-b.example.net/${id}`);
assert.equal(await resolveUserFileUrl({ login, id, kind: 'dm' }), `https://dm-files.node-b.example.net/${id}`);
assert.equal(requests.length, 1);
} finally { globalThis.fetch = originalFetch; clearUserFileServerCache(); }
});
test('федерация: Solana server_address может быть WSS с портом и путём', async () => {
clearUserFileServerCache();
state.entrySettings.shineServerHttp = 'https://reader.example.com';
const savedFetch = globalThis.fetch;
globalThis.fetch = async () => ({ ok: true, json: async () => ({
serverLogin: 'node@shine', serverUrl: 'wss://node.example.com:8443/ws',
}) });
try {
assert.equal(await resolveUserFileUrl({ login, id, kind: 'public' }), `https://files.node.example.com/${id}`);
assert.equal(await resolveUserFileUrl({ login, id, kind: 'dm' }), `https://dm-files.node.example.com/${id}`);
} finally { globalThis.fetch = savedFetch; clearUserFileServerCache(); }
});
test('федерация: проверка при ошибке не чаще одного раза в час и только при смене адреса', async () => {
clearUserFileServerCache();
const originalFetch = globalThis.fetch;
const originalNow = Date.now;
let now = 100_000_000;
let calls = 0;
let address = 'server-a.example.com';
Date.now = () => now;
globalThis.fetch = async () => { calls++; return { ok: true, json: async () => ({ serverLogin: 's@shine', serverUrl: address }) }; };
try {
const first = userFileObjectUrl(await getUserFileServer(login), id);
assert.equal(calls, 1);
assert.equal(await updatedUserFileUrlAfterError({ login, id, previousUrl: first }), null);
assert.equal(calls, 1);
now += SERVER_LOOKUP_COOLDOWN_MS + 1;
address = 'server-b.example.com';
const responses = await Promise.all(Array.from({ length: 12 }, () => refreshUserFileServerOnError(login)));
assert.equal(calls, 2);
assert.equal(responses[0].hostname, 'server-b.example.com');
assert.equal(await updatedUserFileUrlAfterError({ login, id, previousUrl: first }), `https://files.server-b.example.com/${id}`);
assert.equal(calls, 2);
} finally { Date.now = originalNow; globalThis.fetch = originalFetch; clearUserFileServerCache(); }
});
test('DM v3: новые сообщения не содержат адреса, прежний v3 с URL продолжает читаться', () => {
const base = { version: 3, id, url: `https://dm-files.shineup.me/${id}`,
keyB64Url: 'AQID', ivPrefixB64Url: 'AQID',
name: 'photo.png', mime: 'image/png', size: 123, encryptedSize: 139,
chunkSize: 8388608, chunkCount: 1, kind: 'file', uploadedAtMs: 1005000 };
const text = buildDmFileTechBlock(base);
assert.doesNotMatch(text, /;url=/);
const parsed = parseDmTechBlocks(text).fileAttachment;
assert.equal(parsed.id, id);
assert.equal(parsed.uploadedAtMs, base.uploadedAtMs);
assert.equal(parsed.url, '');
const oldText = text.replace(`;id=${id}`, `;id=${id};url=${encodeURIComponent(base.url)}`);
assert.equal(parseDmTechBlocks(oldText).fileAttachment.url, base.url);
});
test('R2 DM v3: после 14 дней не пробуем скачивание; старые legacy v2 без R2 TTL', () => {
const now = Date.now();
assert.equal(isDmFileExpired({ version: 3, uploadedAtMs: now - DM_FILE_RETENTION_MS - 1 }), true);
assert.equal(isDmFileExpired({ version: 3, uploadedAtMs: now - DM_FILE_RETENTION_MS + 60_000 }), false);
assert.equal(isDmFileExpired({ version: 3, messageTimestampMs: now - DM_FILE_RETENTION_MS - 1 }), true);
assert.equal(isDmFileExpired({ version: 2, messageTimestampMs: now - 2 * DM_FILE_RETENTION_MS }), false);
});
Binary file not shown.
@@ -0,0 +1,71 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const read = path => fs.readFileSync(new URL(path, import.meta.url), 'utf8');
const auth = read('../js/services/auth-service.js');
const inspector = read('../js/services/blockchain-entry-inspector.js');
const source = auth.split('function makeHeaderBodyBytes(')[1]?.split('\nfunction makeUserParamBodyBytes(')[0];
assert.ok(source, 'production makeHeaderBodyBytes must exist');
const utf8 = value => new TextEncoder().encode(value);
const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeHeaderBodyBytes`, {
utf8Bytes: utf8,
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
Uint8Array,
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
});
test('client writes HEADER v2 as SHiNE → login → literal license → key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine';
const body = encode({ login, initialBlockchainKey32: key });
const loginBytes = utf8(login);
const expected = Uint8Array.from([
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
...utf8('license:CC0-1.0'), ...key,
]);
assert.deepEqual(Array.from(body), Array.from(expected));
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
});
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, {
TextDecoder, DataView, Uint8Array, BigInt,
bytesToBase64Url: bytes => Buffer.from(bytes).toString('base64url'),
Buffer,
});
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = utf8('Alice@shine');
const prefix = Uint8Array.from([...utf8('SHiNE'), login.length, ...login]);
const bodyV1 = Uint8Array.from([...prefix, ...key]);
const bodyV2 = Uint8Array.from([...prefix, ...utf8('license:CC0-1.0'), ...key]);
const frameFor = (version, body) => {
const frame = new Uint8Array(88 + body.length);
const view = new DataView(frame.buffer);
view.setUint16(0, 1, false); // frameCode
view.setInt32(66, frame.length, false);
view.setInt32(70, 0, false); // blockNumber
view.setBigInt64(74, 0n, false);
view.setUint16(82, 0, false); // type TECH
view.setUint16(84, 0, false); // subtype HEADER
view.setUint16(86, version, false);
frame.set(body, 88);
return frame;
};
const old = inspect(frameFor(1, bodyV1));
assert.equal(old.body.kind, 'header');
assert.equal(old.body.license, null);
const current = inspect(frameFor(2, bodyV2));
assert.equal(current.body.kind, 'header');
assert.equal(current.body.license, 'CC0-1.0');
assert.equal(current.body.initialBlockchainKey, Buffer.from(key).toString('base64url'));
assert.throws(() => inspect(frameFor(2, Uint8Array.from([...prefix, ...key, ...utf8('license:CC0-1.0')]))));
const invalid = bodyV2.slice();
invalid[prefix.length + 8] = 'X'.charCodeAt(0);
assert.throws(() => inspect(frameFor(2, invalid)));
assert.throws(() => inspect(frameFor(2, new Uint8Array(0))));
});
@@ -0,0 +1,128 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
const moduleUrl = new URL('../js/i18n/index.js', import.meta.url);
const assets = new URL('../js/i18n/', import.meta.url);
function setupBrowser({ languages = ['ru-RU', 'en-US'], selected = '' } = {}) {
const values = new Map(selected ? [['shine-ui-language-v1', selected]] : []);
const element = { lang: '' };
const existing = {
window: globalThis.window,
navigator: globalThis.navigator,
document: globalThis.document,
localStorage: globalThis.localStorage,
fetch: globalThis.fetch,
};
Object.defineProperty(globalThis, 'navigator', { value: { languages, language: languages[0] }, configurable: true });
globalThis.window = { __SHINE_BUILD_HASH__: 'test' };
globalThis.document = { documentElement: element };
globalThis.localStorage = {
getItem: (key) => values.get(key) ?? null,
setItem: (key, value) => values.set(key, String(value)),
};
globalThis.fetch = async (url) => {
const path = new URL(url);
const content = await readFile(fileURLToPath(new URL(path.pathname, assets)));
return { ok: true, json: async () => JSON.parse(content.toString()) };
};
return {
values, element,
restore() {
Object.defineProperty(globalThis, 'navigator', { value: existing.navigator, configurable: true });
for (const key of ['window', 'document', 'localStorage', 'fetch']) {
if (existing[key] === undefined) delete globalThis[key];
else globalThis[key] = existing[key];
}
},
};
}
async function freshModule() {
return import(`${moduleUrl.href}?test=${Math.random().toString(36).slice(2)}`);
}
test('системный ru-RU определяется как ru и подгружается русский словарь', async () => {
const env = setupBrowser({ languages: ['ru-RU', 'en-US'] });
try {
const i18n = await freshModule();
await i18n.initI18n();
assert.equal(i18n.getLanguage(), 'ru');
assert.equal(i18n.t('language.menu'), 'Язык / Language');
assert.equal(env.element.lang, 'ru');
assert.deepEqual(i18n.getLanguages().map(({ code }) => code), ['ru', 'en']);
} finally { env.restore(); }
});
test('если язык браузера не поддерживается, язык по умолчанию English', async () => {
const env = setupBrowser({ languages: ['de-DE', 'fr-FR'] });
try {
const i18n = await freshModule();
await i18n.initI18n();
assert.equal(i18n.getLanguage(), 'en');
assert.equal(i18n.t('language.menu'), 'Language / Language');
assert.equal(env.element.lang, 'en');
} finally { env.restore(); }
});
test('первый поддерживаемый язык из navigator.languages побеждает', async () => {
const env = setupBrowser({ languages: ['de-DE', 'ru-BY', 'en-US'] });
try {
const i18n = await freshModule();
await i18n.initI18n();
assert.equal(i18n.getLanguage(), 'ru');
} finally { env.restore(); }
});
test('ручной выбор общий для профилей, сохраняется в отдельном ключе и меняет html lang', async () => {
const env = setupBrowser({ languages: ['ru-RU'] });
try {
const i18n = await freshModule();
await i18n.initI18n();
let updates = 0;
const unsubscribe = i18n.onLanguageChange(() => { updates++; });
assert.equal(await i18n.setLanguage('en'), true);
assert.equal(i18n.getLanguage(), 'en');
assert.equal(env.values.get('shine-ui-language-v1'), 'en');
assert.equal(env.element.lang, 'en');
assert.equal(updates, 1);
await i18n.setLanguage('en');
assert.equal(updates, 1);
unsubscribe();
await i18n.setLanguage('ru');
assert.equal(updates, 1);
assert.equal(await i18n.setLanguage('zz'), false);
assert.equal(i18n.getLanguage(), 'ru');
} finally { env.restore(); }
});
test('ручной выбор языка имеет приоритет над браузером', async () => {
const env = setupBrowser({ languages: ['ru-RU'], selected: 'en' });
try {
const i18n = await freshModule();
await i18n.initI18n();
assert.equal(i18n.getLanguage(), 'en');
} finally { env.restore(); }
});
test('недостающие английские ключи возвращают русский текст; параметры подставляются', async () => {
const env = setupBrowser();
try {
const i18n = await freshModule();
await i18n.initI18n();
assert.equal(i18n.t('screens.start_view.text_003'), 'Войти');
assert.equal(i18n.t('unknown.key'), 'unknown.key');
assert.equal(i18n.t('missing.{who}', { who: 'Alice' }), 'missing.Alice');
} finally { env.restore(); }
});
test('в профилях не сохраняется язык, а экран выбора строится из реестра', async () => {
const state = await readFile(new URL('../js/state.js', import.meta.url), 'utf8');
const page = await readFile(new URL('../js/pages/language-view.js', import.meta.url), 'utf8');
assert.ok(state.includes('language: getLanguage()'));
assert.ok(!state.includes("language: String(settings?.language || 'ru')"));
assert.ok(page.includes('getLanguages().forEach'));
assert.ok(page.includes('await saveEntryLanguage(code)'));
});
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const uiRoot = fileURLToPath(new URL('../', import.meta.url));
const russian = JSON.parse(readFileSync(join(uiRoot, 'js/i18n/locales/ru.json'), 'utf8'));
const english = JSON.parse(readFileSync(join(uiRoot, 'js/i18n/locales/en.json'), 'utf8'));
function flatten(node, prefix = '') {
return Object.entries(node).flatMap(([name, value]) => {
const key = prefix ? `${prefix}.${name}` : name;
return typeof value === 'string' ? [[key, value]] : flatten(value, key);
});
}
function javascriptFiles(directory) {
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const full = join(directory, entry.name);
return entry.isDirectory() ? javascriptFiles(full) : (entry.name.endsWith('.js') ? [full] : []);
});
}
test('оба словаря содержат одинаковые ключи и параметры', () => {
const ru = new Map(flatten(russian));
const en = new Map(flatten(english));
assert.deepEqual([...en.keys()].sort(), [...ru.keys()].sort());
for (const [key, value] of ru) {
const parameters = (text) => [...text.matchAll(/\{([a-zA-Z0-9_]+)\}/gu)].map((match) => match[1]).sort();
assert.deepEqual(parameters(en.get(key)), parameters(value), key);
assert.ok(en.get(key).trim(), key);
}
});
test('каждое статическое обращение t/th имеет русский ключ', () => {
const ru = new Map(flatten(russian));
for (const file of javascriptFiles(join(uiRoot, 'js'))) {
if (file.includes('/i18n/')) continue;
const source = readFileSync(file, 'utf8');
for (const match of source.matchAll(/\b(?:t|th)\('([^']+)'/gu)) {
assert.ok(ru.has(match[1]), `${file}: ${match[1]}`);
}
}
});
@@ -0,0 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ui = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const ru = JSON.parse(fs.readFileSync(path.join(ui, 'js/i18n/locales/ru.json'), 'utf8'));
const source = (name) => fs.readFileSync(path.join(ui, `js/${name}`), 'utf8');
const key = (name) => name.split('.').reduce((value, part) => value?.[part], ru);
test('русский словарь содержит новые блоки аудита диалогов', () => {
const required = [
'dialogs.final.consent.remember_public_history',
'dialogs.final.consent.public_history_warning',
'dialogs.final.chat.delete_contact_confirm',
'dialogs.final.chat.delete_protected_confirm',
'dialogs.final.chat.confirm_clear_history_text',
'dialogs.final.profile.char_limit',
'dialogs.remaining.components.share_sheet.markup.skopirovat_ssylku',
];
for (const name of required) {
assert.ok(typeof key(name) === 'string' && key(name).length, name);
}
assert.match(key('dialogs.final.chat.delete_contact_confirm'), /\{name\}/);
});
test('окно «Поделиться»: функция t не перекрыта локальной переменной', () => {
const share = source('components/share-sheet.js');
assert.match(share, /import \{ t \} from '\.\.\/i18n\/index\.js'/);
assert.doesNotMatch(share, /\b(?:const|let|var)\s+t\s*=/);
assert.match(share, /previewText\.textContent\s*=\s*text/);
assert.match(share, /t\('dialogs\.remaining\.components\.share_sheet\.markup\.skopirovat_ssylku'\)/);
});
test('подпись редактирования канала подставляется, а не показывается как ${t(...)}', () => {
const channel = source('pages/channel-view.js');
assert.match(channel, /title="\$\{t\('dialogs\.modals\.channel_view\.label_001'\)\}"/);
assert.doesNotMatch(channel, /title="\\\$\{t\(/);
});
test('переводы согласий вычисляются при открытии окна, а не при загрузке модуля', () => {
const consent = source('services/public-history-consent.js');
const likes = source('components/like-action-sheet.js');
const profile = source('pages/profile-edit-view.js');
assert.match(consent, /export function getPublicHistoryRememberLabel\(\)/);
assert.match(consent, /label:\s*getPublicHistoryRememberLabel\(\)/);
assert.match(likes, /getPublicHistoryRememberLabel\(\)/);
assert.doesNotMatch(likes, /PUBLIC_HISTORY_REMEMBER_LABEL/);
assert.match(profile, /function shiningSteps\(\)/);
assert.match(profile, /steps:\s*shiningSteps\(\)/);
assert.doesNotMatch(profile, /const SHINING_STEPS/);
});
test('динамические имена в подтверждениях чата экранируются для HTML', () => {
const chat = source('pages/chat-view.js');
assert.equal((chat.match(/function escapeDialogHtml\(/g) || []).length, 1);
assert.match(chat, /escapeDialogHtml\(t\('dialogs\.final\.chat\.delete_contact_confirm'/);
assert.match(chat, /escapeDialogHtml\(t\('dialogs\.final\.chat\.delete_protected_confirm'/);
});
@@ -0,0 +1,10 @@
import { readFileSync } from 'node:fs';
const russian = JSON.parse(readFileSync(new URL('../js/i18n/locales/ru.json', import.meta.url), 'utf8'));
export function expandRussian(source) {
return source.replace(/t\('([a-z0-9_.]+)'\)/gu, (call, key) => {
const value = key.split('.').reduce((node, part) => node?.[part], russian);
return typeof value === 'string' ? JSON.stringify(value) : call;
});
}
@@ -0,0 +1,111 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { AuthService } from '../js/services/auth-service.js';
const target = {
login: 'alexsmith@shine', // case из имени цепочки, а не из регистрации
blockchainName: 'alexsmith@shine-001',
blockNumber: 4,
blockHash: 'ab'.repeat(32),
forkNumber: 1,
};
const original = 'AlexSmith@shine';
const input = { login: 'tester@shine', storagePwd: 'test', message: target, text: 'ответ' };
function mockService({ registered = original, exists = true } = {}) {
const service = new AuthService('wss://local.example/ws');
const sent = [];
const requested = [];
service.getUser = async (login) => {
requested.push(login);
return { exists, login: registered, blockchainName: 'alexsmith@shine-001' };
};
service.addBlockSigned = async (args) => {
sent.push(args);
return { serverLastGlobalNumber: 1, serverLastGlobalHash: 'ac'.repeat(32) };
};
return { service, sent, requested };
}
const hasLogin = (bodyBytes, login) => Buffer.from(bodyBytes).includes(Buffer.from(login, 'utf8'));
test('ссылки reply, rating, status, like и unlike подписываются с регистром регистрации', async () => {
for (const method of ['addBlockReply', 'addBlockRating', 'addBlockStatusAction', 'addBlockLike', 'addBlockUnlike']) {
const { service, sent, requested } = mockService();
await service[method]({ ...input, statusSubType: 110 });
assert.equal(sent.length, 1, method);
assert.deepEqual(requested, [target.login], method);
assert.ok(hasLogin(sent[0].bodyBytes, original), `${method}: оригинальный логин отсутствует`);
assert.ok(!hasLogin(sent[0].bodyBytes, target.login), `${method}: записан lowercase`);
}
});
test('если регистрационный логин не подтверждён, клиент не подписывает блок', async () => {
for (const data of [{ exists: false }, { registered: 'Other@shine' }]) {
const { service, sent } = mockService(data);
await assert.rejects(() => service.addBlockReply(input), /Не удалось подтвердить/);
assert.equal(sent.length, 0);
}
});
test('связи между пользователями фиксируют исходный регистр цели', async () => {
const { service, sent } = mockService();
service.ensureChainInitializedForLineOps = async () => ({ blockchainName: 'tester@shine-001' });
service.resolveFixedLineTail = async () => ({ prevLineNumber: 0, prevLineHashHex: 'ac'.repeat(32), thisLineNumber: 1 });
service.rememberLineTail = () => {};
await service.addBlockConnectionTarget({
login: 'tester@shine', storagePwd: 'test', subType: 30,
toLogin: target.login, toForkNumber: 1, toBlockNumber: 0, toBlockHashHex: 'ab'.repeat(32),
});
assert.equal(sent.length, 1);
assert.ok(hasLogin(sent[0].bodyBytes, original));
assert.ok(!hasLogin(sent[0].bodyBytes, target.login));
});
test('HEADER и PostgreSQL требуют неизменяемого регистра, Solana sync отклоняет переименование', () => {
const client = readFileSync(new URL('../js/services/auth-service.js', import.meta.url), 'utf8');
const handler = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler.java', import.meta.url), 'utf8');
const header = readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/body/HeaderBody.java', import.meta.url), 'utf8');
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v37.sql', import.meta.url), 'utf8');
assert.match(client, /bodyBytes: makeHeaderBodyBytes\(\{ login: registeredLogin, initialBlockchainKey32 \}\)/);
assert.doesNotMatch(client, /makeHeaderBodyBytes\(\{ login: cleanLogin\.toLowerCase\(\)/);
assert.match(handler, /headerBody\.login\.equals\(registeredOwner\.getLogin\(\)\)/);
assert.match(header, /\[A-Za-z0-9_\]\+@\[a-z0-9_\]\+/);
assert.match(migration, /old_user\.login <> NEW\.login/);
assert.match(migration, /NEW\.login IS DISTINCT FROM OLD\.login/);
});
test('runtime-state блокчейна использует normalized_login, не отображаемое написание', () => {
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v43.sql', import.meta.url), 'utf8');
const state = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/java/shine/db/entities/BlockchainStateEntry.java', import.meta.url), 'utf8');
assert.match(migration, /FOREIGN KEY \(login\) REFERENCES user_identity_current\(normalized_login\)/);
assert.match(migration, /SET login = LOWER\(BTRIM\(login\)\)/);
assert.match(migration, /NEW\.login := LOWER\(BTRIM\(NEW\.login\)\)/);
assert.match(state, /toLowerCase\(Locale\.ROOT\)/);
});
test('адресат уведомления хранится и ищется по normalized_login', () => {
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v44.sql', import.meta.url), 'utf8');
const dao = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/java/shine/db/dao/UserNotificationsStateDAO.java', import.meta.url), 'utf8');
assert.match(migration, /SET owner_login = LOWER\(BTRIM\(owner_login\)\)/);
assert.match(migration, /NEW\.owner_login := LOWER\(BTRIM\(NEW\.owner_login\)\)/);
assert.match(dao, /ps\.setString\(i\+\+, normalizedLogin\(e\.getOwnerLogin\(\)\)\)/);
assert.match(dao, /ps\.setString\(1, normalizedLogin\(ownerLogin\)\)/);
assert.match(dao, /toLowerCase\(Locale\.ROOT\)/);
});
test('лента, список подписок и дерево обсуждения возвращают оригинальный регистр автора', () => {
const base = new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/channels/', import.meta.url);
const read = (file) => readFileSync(new URL(file, base), 'utf8');
const channel = read('Net_GetChannelMessages_Handler.java');
const thread = read('Net_GetMessageThread_Handler.java');
const feed = read('Net_ListSubscriptionsFeed_Handler.java');
const helper = read('ChannelsReadSupport.java');
assert.match(channel, /setAuthorLogin\(ChannelsReadSupport\.officialLogin\(/);
assert.match(channel, /setOwnerLogin\(ChannelsReadSupport\.officialLogin\(/);
assert.match(thread, /node\.setAuthorLogin\(ChannelsReadSupport\.officialLogin\(/);
assert.match(feed, /lm\.setAuthorLogin\(ChannelsReadSupport\.officialLogin\(/);
assert.match(feed, /channelRef\.setOwnerLogin\(ChannelsReadSupport\.officialLogin\(/);
assert.match(helper, /value = canonicalLogin\(c, raw\)/);
});
@@ -0,0 +1,41 @@
import test from 'node:test';
import { expandRussian } from './i18n-source-helper.mjs';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const read = p => expandRussian(readFileSync(new URL(`../../${p}`, import.meta.url), 'utf8'));
const ui = read('shine-UI/js/pages/key-rotation-view.js');
const app = read('shine-UI/js/app.js');
const client = read('shine-UI/js/services/key-rotation-service.js');
const server = read('SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/keyRotation/Net_KeyRotationRotatePda_Handler.java');
test('после начала смены в шапке нет кнопки назад и нет abort в UI', () => {
assert.match(ui, /const canExit=status==='NONE' \|\| status==='COMPLETE'/);
assert.match(ui, /updateTopbar\(stateNow\.rotationStatus\)/);
assert.doesNotMatch(ui, /client\.abort\(/);
assert.match(app, /keyRotationRouteLock && state\.session\.isAuthorized/);
assert.match(app, /navigate\('key-rotation-view'\)/);
});
test('при восстановлении проверяются оба введённых пароля относительно ключей ротации', () => {
assert.match(ui, /await derive\(oldP\.el\.value\)/);
assert.match(ui, /await derive\(newP\.el\.value\)/);
assert.match(ui, /Старый пароль выводит другой blockchain key/);
assert.match(ui, /Новый пароль выводит другой client key/);
});
test('серверное уведомление PDA идемпотентно на всех этапах после PDA', () => {
for (const stage of ['PDA_ROTATED','REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING']) {
assert.match(server, new RegExp('KeyRotationStatus\\.' + stage));
}
assert.match(server, /KEY_ROTATION_PDA_SIGNATURE_CONFLICT/);
});
test('повторное обращение не отправляет новый Solana tx, если PDA уже обновлена', () => {
assert.match(client, /const pda=await readShineUserPda/);
assert.match(client, /if\(matchesNew\)/);
assert.match(client, /if\(!matchesOld\)throw new Error/);
assert.ok(client.indexOf('if(matchesNew)') < client.indexOf('updateShineUserPdaOnSolana({'));
assert.ok(client.indexOf('await saveNewKeys();\n try{return await this.notifyPdaRotation(signature)') > 0);
});
test('полное завершение снимает блокировку навигации', () => {
assert.match(ui, /function exitAfterComplete\(\)\{updateTopbar\('COMPLETE'\);navigate\('access-keys-view'\);\}/);
assert.match(ui, /shine-key-rotation-active/);
assert.match(app, /keyRotationRouteLock = Boolean\(event\.detail\?\.active\)/);
});
@@ -0,0 +1,74 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
const baseUrl = new URL('../js/i18n/', import.meta.url);
const i18n = await import('../js/i18n/index.js');
const fmt = await import('../js/i18n/format.js');
function withMockBrowser(browserLanguages = ['ru-RU']) {
const originals = {
navigator: globalThis.navigator,
fetch: globalThis.fetch,
localStorage: globalThis.localStorage,
document: globalThis.document,
window: globalThis.window,
};
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: { languages: browserLanguages, language: browserLanguages[0] },
});
const saved = new Map();
globalThis.document = { documentElement: { lang: '' } };
globalThis.window = { __SHINE_BUILD_HASH__: 'test' };
globalThis.localStorage = { getItem: (k) => saved.get(k) ?? null, setItem: (k,v) => saved.set(k,String(v)) };
globalThis.fetch = async (url) => {
const u = new URL(url);
const text = await readFile(fileURLToPath(new URL(u.pathname, baseUrl)), 'utf8');
return { ok: true, json: async () => JSON.parse(text) };
};
return {
saved,
setBrowserLanguages(list) {
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: { languages: list, language: list[0] },
});
},
restore() {
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: originals.navigator });
for (const key of ['fetch', 'localStorage', 'document', 'window']) {
if (originals[key] === undefined) delete globalThis[key];
else globalThis[key] = originals[key];
}
},
};
}
test('даты/время/числа реагируют на единый язык, английский по умолчанию en-US', async () => {
const env = withMockBrowser(['ru-RU']);
try {
await i18n.initI18n();
await i18n.setLanguage('ru');
const date = new Date(2026, 10, 10, 14, 5);
assert.equal(fmt.getIntlLocale(), 'ru-RU');
assert.match(fmt.formatDate(date), /^10 ноября 2026/u);
assert.equal(fmt.formatTime(date), '14:05');
assert.equal(fmt.formatNumber(1234.5).replace(/\s/gu, ' '), '1 234,5');
await i18n.setLanguage('en');
assert.equal(fmt.getIntlLocale(), 'en-US');
assert.match(fmt.formatDate(date), /^10 November 2026$/u);
assert.equal(fmt.formatTime(date), '14:05');
assert.match(fmt.formatDateTime(date), /^10\/11\/2026, 14:05$/u);
assert.equal(fmt.formatNumber(1234.5), '1,234.5');
assert.equal(fmt.formatRelative(-1, 'day'), 'yesterday');
assert.equal(fmt.formatRelative(0, 'second'), 'now');
env.setBrowserLanguages(['en-GB', 'en-US']);
assert.equal(fmt.getIntlLocale(), 'en-GB');
env.setBrowserLanguages(['en']);
assert.equal(fmt.getIntlLocale(), 'en-US');
} finally { env.restore(); }
});
@@ -0,0 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const text = path => readFileSync(new URL(path, import.meta.url), 'utf8');
test('opcode 8 требует upgrade authority, строго один код SOL и индексируемую economy PDA', () => {
const rust = text('../../shine-solana/shine/programs/shine_users/src/lib.rs');
const body = rust.split('fn process_update_namespace_price')[1].split('fn validate_upgrade_authority')[0];
assert.match(rust, /const IX_UPDATE_NAMESPACE_PRICE: u8 = 8;/);
assert.match(body, /validate_upgrade_authority\(program_id, signer, program_ai, programdata_ai\)/);
assert.match(body, /read_namespace\(program_id, namespace_pda, name\)/);
assert.match(body, /validate_users_economy_config_pda\(program_id, economy_pda\)/);
assert.match(body, /ensure_pda_size_and_rent/);
assert.match(rust, /state\.currency_code == NAMESPACE_CURRENCY_SOL/);
});
test('server sync узнаёт update цены, а UPSERT сохраняет новые fee/currency, не старые', () => {
const codec = text('../../SHiNE-server/shine-server-solana-users-sync/src/main/java/sync/codec/ShineUsersCodec.java');
const repo = text('../../SHiNE-server/shine-server-solana-users-sync/src/main/java/sync/storage/postgres/PostgresStorageRepository.java');
const migrations = text('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v40.sql');
assert.match(codec, /case IX_UPDATE_NAMESPACE_PRICE ->/);
assert.match(codec, /TxKind\.UPDATE_NAMESPACE_PRICE/);
assert.match(repo, /registration_fee_lamports=EXCLUDED.registration_fee_lamports/);
assert.match(repo, /currency_code=EXCLUDED.currency_code/);
assert.doesNotMatch(repo, /shine_namespace_current\.raw_data_base64=EXCLUDED\.raw_data_base64/);
assert.match(migrations, /ADD COLUMN currency_code SMALLINT NOT NULL DEFAULT 1/);
});
@@ -0,0 +1,133 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createExplorerGraph } from '../js/pages/network-explorer/graph-model.js';
import {
getExplorerGraph, clearExplorerGraphCache, readExplorerCachedGraphs,
EXPLORER_CACHE_TTL_MS, explorerGraphSavedAt,
} from '../js/pages/network-explorer/graph-cache.js';
function friends(login, links = [], close = [], inFriends = [], marked = []) {
return {
login, outFriends: links, outCloseFriends: close, inFriends,
allUsers: marked.map(([user, shine]) => ({ login: user, shine })),
};
}
const find = (model, login) => model.nodes.find((node) => node.id === login);
test('V3: BFS, радиусы X2 + 0..4, переход в любую сторону без истории центров', () => {
const g = createExplorerGraph();
g.add(friends('a', ['b']));
g.add(friends('b', ['c']));
g.add(friends('c', ['d']));
g.add(friends('d', ['e']));
g.add(friends('e', ['f']));
g.add(friends('f', ['g']));
const zero = g.snapshot('a', { x2: true, depth: 0 });
assert.deepEqual(zero.nodes.map((n) => n.id), ['a', 'b', 'c']);
const one = g.snapshot('d', { x2: true, depth: 1 });
assert.deepEqual(one.nodes.map((n) => n.id), ['d', 'c', 'e', 'b', 'f', 'a', 'g']);
const two = g.snapshot('d', { x2: true, depth: 2 });
assert.equal(two.nodes.length, 7);
const back = g.snapshot('b', { x2: false, depth: 0 });
assert.deepEqual(back.nodes.map((n) => n.id), ['b', 'a', 'c']);
});
test('V3: маленький при скрытом друге; раскрывается, когда все друзья видны', () => {
const g = createExplorerGraph();
g.add(friends('a', ['b']));
g.add(friends('b', ['c']));
g.add(friends('c', ['d']));
const shallow = g.snapshot('a', { x2: false, depth: 0 });
assert.equal(find(shallow, 'a').visualSmall, false);
assert.equal(find(shallow, 'b').visualSmall, true);
const deeper = g.snapshot('a', { x2: true, depth: 1 });
assert.equal(find(deeper, 'b').visualSmall, false);
assert.equal(find(deeper, 'c').visualSmall, false);
assert.equal(find(deeper, 'd').visualSmall, true); // список d пока не был загружен
assert.deepEqual(deeper.nodes.filter((n) => n.id === 'b').flatMap((n) => n.edgeParents).map((n) => n.id), ['a']);
});
test('V3: кратчайший путь через пересечение, без дубликатов; направление ребра', () => {
const g = createExplorerGraph();
g.add(friends('z', ['a', 'b']));
g.add(friends('a', ['z', 'b'], [], ['z']));
g.add(friends('b', ['c']));
g.add(friends('c', ['d']));
const m = g.snapshot('z', { x2: true, depth: 0 });
assert.equal(m.nodes.length, 4);
assert.equal(find(m, 'b').distance, 1);
assert.equal(find(m, 'c').distance, 2);
assert.ok(find(m, 'a').edgeParents.some((e) => e.id === 'z'));
assert.equal(m.nodes.length, new Set(m.nodes.map((n) => n.id)).size);
});
test('V3: фильтры близкие/сияющие и полнота раскрытия', () => {
const g = createExplorerGraph();
g.add(friends('a', ['b'], ['c'], [], [['b', false], ['c', true]]));
g.add(friends('c', []));
const all = g.snapshot('a', { x2: false, depth: 0 });
assert.equal(all.nodes.length, 3);
assert.deepEqual(g.snapshot('a', { close: true, depth: 0 }).nodes.map((n) => n.id), ['a', 'c']);
const shiny = g.snapshot('a', { shining: true, depth: 0 });
assert.deepEqual(shiny.nodes.map((n) => n.id), ['a', 'c']);
assert.equal(find(shiny, 'a').visualSmall, false);
});
test('V3: TTL 24h, ручная очистка, разделение серверов/аккаунтов и восстановление', async () => {
const clock = Date.now;
let now = 1_900_000_000_000;
Date.now = () => now;
try {
await clearExplorerGraphCache();
let count = 0;
const service = { serverUrl: 'wss://test', getUserConnectionsGraph: async (login) => ({ login, count: ++count }) };
const scope = 'wss://test|alice';
const scopeOther = 'wss://test|bob';
await getExplorerGraph(service, 'alice', { scope });
now += EXPLORER_CACHE_TTL_MS - 1;
await getExplorerGraph(service, 'alice', { scope });
assert.equal(count, 1);
assert.equal(explorerGraphSavedAt(scope, 'alice'), 1_900_000_000_000);
assert.equal((await readExplorerCachedGraphs(scope)).length, 1);
now += 1;
await getExplorerGraph(service, 'alice', { scope });
assert.equal(count, 2);
await getExplorerGraph(service, 'alice', { scope: scopeOther });
assert.equal(count, 3);
await clearExplorerGraphCache();
assert.equal((await readExplorerCachedGraphs(scope)).length, 0);
await getExplorerGraph(service, 'alice', { scope });
assert.equal(count, 4);
} finally { Date.now = clock; await clearExplorerGraphCache(); }
});
test('V3: регистр логина для запросов, обновление списка и статуса сияния', () => {
const g = createExplorerGraph();
g.add(friends('Alice', ['BobUser', 'Carol'], [], [], [['BobUser', true]]));
assert.deepEqual(g.getFriends('ALICE'), ['BobUser', 'Carol']);
assert.equal(g.snapshot('Alice').nodes.find((n) => n.id === 'bobuser').shining, true);
g.add(friends('Alice', ['BobUser'], [], [], [['BobUser', false]]));
assert.deepEqual(g.getFriends('ALICE'), ['BobUser']);
assert.equal(g.snapshot('Alice').nodes.find((n) => n.id === 'bobuser').shining, false);
assert.equal(g.snapshot('Alice').nodes.some((n) => n.id === 'carol'), false);
});
test('V3: взаимная связь сохраняет оба типа для красно-синего перехода', () => {
const g = createExplorerGraph();
g.add(friends('a', ['b']));
g.add(friends('b', [], ['a']));
const edge = find(g.snapshot('a', { depth: 0 }), 'b').edgeParents[0];
assert.equal(edge.relationType, 'friend');
assert.equal(edge.reverseRelationType, 'close_friend');
assert.equal(edge.mutual, true);
});
test('V3: сияние не стирает тип связи у красно-синего перехода', () => {
const g = createExplorerGraph();
g.add(friends('a', ['b'], [], [], [['a', true], ['b', true]]));
g.add(friends('b', [], ['a'], [], [['a', true], ['b', true]]));
const edge = find(g.snapshot('a', { depth: 0 }), 'b').edgeParents[0];
assert.equal(edge.relationType, 'friend');
assert.equal(edge.reverseRelationType, 'close_friend');
assert.equal(find(g.snapshot('a', { depth: 0 }), 'b').shining, true);
});
@@ -0,0 +1,118 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createExplorerGraph } from '../js/pages/network-explorer/graph-model.js';
import { PALETTES, edgeGradient, edgeCoreGradient, geometryFor } from '../js/pages/network-canvas-v4/graph-style.js';
import { readFileSync } from 'node:fs';
const capture = () => {
const stops = [];
return { stops, ctx: { createLinearGradient(x1, y1, x2, y2) {
assert.deepEqual([x1, y1, x2, y2], [10, 20, 100, 200]);
return { addColorStop(offset, value) { stops.push([offset, value]); } };
} } };
};
const geo = { x1: 10, y1: 20, x2: 100, y2: 200 };
test('V4: двусторонняя связь сохраняет разные цвета у начала и конца', () => {
const { ctx, stops } = capture();
edgeGradient(ctx, geo, { relationType: 'friend', reverseRelationType: 'close_friend', mutual: true }, PALETTES.dark);
assert.deepEqual(stops, [[0, 'rgba(120,179,255,0.98)'], [1, 'rgba(255,76,92,0.98)']]);
});
test('V4: односторонняя связь затухает в направлении адресата', () => {
const { ctx, stops } = capture();
edgeGradient(ctx, geo, { relationType: 'friend', mutual: false }, PALETTES.dark);
assert.deepEqual(stops, [[0, 'rgba(120,179,255,0.98)'], [1, 'rgba(120,179,255,0.035)']]);
});
test('V4: края рёбер касаются сферы, маленькая сфера имеет половину радиуса', () => {
const origin = { x: 0, y: 0 };
const parent = { id: 'a', x: 0, y: 0, visualSmall: false };
const child = { id: 'b', x: 100, y: 0, visualSmall: true };
const g = geometryFor(parent, child, 1, origin, origin);
assert.equal(g.x1, 29);
assert.equal(g.x2, 100 - 14.5);
const doubled = geometryFor(parent, child, 2, origin, origin);
assert.equal(doubled.x1, 58);
assert.equal(doubled.x2, 200 - 29);
});
test('V4: данные V3 с обратным отношением поступают в визуальную модель без потерь', () => {
const graph = createExplorerGraph();
graph.add({ login: 'alice', outFriends: ['bob'], allUsers: [{ login: 'bob', shine: true }] });
graph.add({ login: 'bob', outCloseFriends: ['alice'], allUsers: [{ login: 'alice', shine: true }] });
const model = graph.snapshot('alice', { depth: 1 });
const link = model.nodes.find((n) => n.id === 'bob').edgeParents[0];
assert.equal(link.relationType, 'friend');
assert.equal(link.reverseRelationType, 'close_friend');
assert.ok(model.nodes.every((n) => n.shining));
});
test('V4: статичная Canvas-архитектура не запускает постоянную анимацию', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /requestAnimationFrame\(\(\) =>/);
assert.doesNotMatch(js, /setInterval\(/);
assert.match(js, /MAX_SPRITES_PER_FRAME/);
assert.match(js, /for \(const node of nodes\)/);
assert.match(js, /const shining = Boolean\(node\.shining && parent\.shining\)/);
});
test('V4: стеклянная кромка восстановлена, фото сверху, цветных колец нет', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /glass_overlay_faithful\.png/);
assert.match(js, /const GLASS_SCALE = 1\.19/);
assert.match(js, /if \(glassReady && glass\?\.naturalWidth\)/);
assert.match(js, /g\.drawImage\(glass, 0, 0, side, side\);/);
assert.match(js, /g\.drawImage\(img,/);
assert.ok(js.indexOf('g.drawImage(glass, 0, 0, side, side);') < js.indexOf('g.drawImage(img,'),
'непрозрачная фотография должна рисоваться после стекла');
assert.doesNotMatch(js, /const ring = node\.shining/);
assert.match(js, /if \(!node\.shining\) continue;/);
});
test('V4: неон V3 — размытый flare и tube плюс чёткое светлое ядро', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /drawStroke\(flareCtx, path, 16 \* zoom/);
assert.match(js, /drawStroke\(tubeCtx, path, 6 \* zoom/);
assert.match(js, /blur\(\$\{\(6 \* zoom\)/);
assert.match(js, /blur\(\$\{\(2 \* zoom\)/);
assert.match(js, /globalCompositeOperation = 'screen'/);
assert.match(js, /edgeCoreGradient\(ectx, geo, ref, palette\)/);
assert.doesNotMatch(js, /shadowBlur/);
});
test('V4: светлая сердцевина сохраняет разные цвета и затухание', () => {
const { ctx, stops } = capture();
edgeCoreGradient(ctx, geo, { relationType: 'friend', reverseRelationType: 'close_friend', mutual: false }, PALETTES.dark);
assert.equal(stops.length, 2);
assert.ok(stops[0][1].startsWith('rgba(206,228,255,'), 'светлое голубое начало');
assert.ok(stops[1][1].startsWith('rgba(255,191,196,'), 'светло-красное окончание');
assert.ok(stops[1][1].endsWith(',0.035)'), 'затухание односторонней связи');
});
test('V4: подписи используют плашки V2, а не контур вокруг букв', () => {
const js = readFileSync(new URL('../js/pages/network-canvas-v4/graph-renderer.js', import.meta.url), 'utf8');
assert.match(js, /ctx\.roundRect\(x0, y0, w, h, h \/ 2\)/);
assert.match(js, /words\[1\]\[0\]/);
assert.match(js, /if \(collides\(bounds\)\)/);
assert.doesNotMatch(js, /ctx\.strokeText\(/);
});
test('V3/V4: вход через нижнюю кнопку очищает исследование; переключатель версий не очищает', () => {
const toolbar = readFileSync(new URL('../js/components/toolbar.js', import.meta.url), 'utf8');
const switcher = readFileSync(new URL('../js/pages/network-version-switcher.js', import.meta.url), 'utf8');
const view = readFileSync(new URL('../js/pages/network-explorer/network-view.js', import.meta.url), 'utf8');
assert.match(toolbar, /dispatchEvent\(new Event\('shine:network-tab-enter'\)\)/);
assert.match(switcher, /addEventListener\('shine:network-tab-enter', explorerNetworkView\.resetExplorerOnTabEntry\)/);
assert.match(view, /export function resetExplorerOnTabEntry\(\)/);
assert.match(view, /retained = null;/);
assert.match(view, /resetBarrier = resetBarrier\.catch\(\(\) => \{\}\)\.then\(\(\) => clearExplorerGraphCache\(\)\)/);
assert.match(view, /void resetBarrier\.then\(async \(\) =>/);
assert.doesNotMatch(switcher, /select\.addEventListener\('change',[\s\S]*resetExplorerOnTabEntry/);
});
test('V4 Canvas открывается по умолчанию, но ранее выбранная версия сохраняется', () => {
const switcher = readFileSync(new URL('../js/pages/network-version-switcher.js', import.meta.url), 'utf8');
assert.match(switcher, /const DEFAULT_MODE = 'explorer-canvas';/);
assert.match(switcher, /MODES\.has\(saved\) \? saved : DEFAULT_MODE/);
});
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const page = readFileSync(new URL('../js/pages/notifications-view.js', import.meta.url), 'utf8');
const css = readFileSync(new URL('../styles/features/notifications.css', import.meta.url), 'utf8');
test('уведомление показывает логин автора под отображаемым именем', () => {
assert.match(page, /notification-card__login/);
assert.match(page, /login\.textContent = item\.sourceLogin/);
assert.match(css, /\.notification-card__login/);
});
test('ответная связь повторяет тип входящей связи', () => {
assert.match(page, /CONNECTION_CLOSE_FRIEND[\s\S]*\? 'close_friend'[\s\S]*: 'friend'/);
assert.match(page, /kind, enabled: true/);
assert.match(page, /text_072/);
assert.match(page, /text_073/);
});
@@ -0,0 +1,68 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
const read = file => fs.readFileSync(new URL(file, import.meta.url), 'utf8');
const registration = read('../js/pages/register-view.js');
const login = read('../js/pages/login-password-view.js');
const field = read('../js/components/visible-password-field.js');
const overlay = read('../js/components/secret-generation-overlay.js');
const ru = JSON.parse(read('../js/i18n/locales/ru.json'));
const en = JSON.parse(read('../js/i18n/locales/en.json'));
test('регистрация: один символ разрешён, счётчик только здесь, максимум 256', () => {
assert.match(registration, /value\.length < 1/);
assert.doesNotMatch(registration, /value\.length < (?:10|12)/);
assert.match(registration, /screens\.register_view\.password_counter/);
assert.doesNotMatch(login, /password_counter/);
assert.match(read('../js/services/password-words.js'), /PASSWORD_MAX_LENGTH = 256/);
});
test('обе формы используют многострочное парольное поле с видимостью', () => {
assert.match(registration, /createExpandablePasswordTextarea\(\)/);
assert.match(login, /createExpandablePasswordTextarea\(\)/);
assert.match(field, /input\.rows = 1/);
assert.match(field, /3 \* lineHeight/);
assert.match(field, /auth-password-field--masked/);
assert.match(field, /input\.updatePasswordMask\(\)/);
});
test('одна заставка, без процента и прогресса в обоих сценариях', () => {
assert.match(login, /createSecretGenerationOverlay\(\)/);
assert.match(registration, /createSecretGenerationOverlay\(\)/);
assert.match(registration, /keyGeneration\.show\(\)/);
assert.match(login, /keyGeneration\.show\(\)/);
assert.doesNotMatch(login, /onProgress|percent|\.progress/);
assert.doesNotMatch(overlay, /percent|progress/);
assert.equal(ru.components.secret_generation_overlay.title, 'Генерируем ваши цифровые ключи…');
assert.match(ru.components.secret_generation_overlay.description, /логина и пароля/);
assert.ok(en.components.secret_generation_overlay.title);
});
test('32 символа на строку без реального перевода строки в пароле', () => {
assert.match(field, /input\.cols = 32/);
assert.match(field, /input\.wrap = 'soft'/);
assert.match(field, /auth-password-field--multiline/);
const css = read('../styles/features/preauth.css');
assert.match(css, /32ch \+ 64px/);
assert.match(css, /auth-password-field--multiline/);
});
test('после успеха очищается видимое поле, не рабочие ключи', () => {
assert.match(field, /input\.clearPasswordField = \(\) =>/);
assert.match(field, /input\.updatePasswordMask\?\.\(\)/);
assert.match(registration, /draft\.preGeneratedKeyBundle = bundle;[\s\S]*?input\.clearPasswordField\(\);[\s\S]*?navigate\(/);
assert.match(registration, /input\.value = ''/);
assert.doesNotMatch(registration, /input\.value = draft\.password/);
assert.match(login, /state\.loginDraft\.password = '';[\s\S]*?passwordInput\.clearPasswordField\(\)/);
assert.match(ru.components.secret_generation_overlay.description, /на этом устройстве/);
assert.match(en.components.secret_generation_overlay.description, /on this device/);
});
test('текст регистрации на двух языках и определённое предупреждение', () => {
assert.match(ru.screens.register_view.text_038, /будет утрачен навсегда/);
assert.doesNotMatch(ru.screens.register_view.text_038, /может быть утрачен/);
assert.match(ru.screens.register_view.text_036, /12–16/);
assert.match(ru.screens.register_view.text_035, /кошелькам/);
assert.match(en.screens.register_view.text_038, /lost forever/);
});
@@ -0,0 +1,212 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { validatePublicPiecesRoot } from '../js/services/public-pieces-root.js';
const source = await readFile(new URL('../js/services/attachment-format.js', import.meta.url), 'utf8');
class TestElement {
constructor(tagName) {
this.tagName = tagName.toUpperCase();
this.className = '';
this.children = [];
this.dataset = {};
this.listeners = {};
this.isConnected = true;
this.classList = {
add: (...values) => { this.className = [...new Set([...this.className.split(' '), ...values])].filter(Boolean).join(' '); },
remove: (...values) => { this.className = this.className.split(' ').filter((x) => !values.includes(x)).join(' '); },
toggle: (value, force) => {
const has = this.className.split(' ').includes(value);
const enabled = force ?? !has;
if (enabled) this.classList.add(value);
else this.classList.remove(value);
return enabled;
},
};
}
append(...nodes) {
for (const node of nodes) {
this.children.push(node);
if (node && typeof node === 'object') node.parentElement = this;
}
}
replaceChildren(...nodes) { this.children = []; this.append(...nodes); }
addEventListener(name, callback) { (this.listeners[name] ||= []).push(callback); }
setAttribute(name, value) { (this.attributes ||= {})[name] = String(value); }
fire(name, event = {}) {
for (const listener of this.listeners[name] || []) listener({ stopPropagation() {}, preventDefault() {}, ...event });
}
querySelectorAll(tag) {
const result = [];
for (const child of this.children) {
if (child.tagName?.toLowerCase() === tag) result.push(child);
result.push(...(child.querySelectorAll?.(tag) || []));
}
return result;
}
}
function loadRenderer() {
const viewerCalls = [];
const warningCalls = [];
const navigations = [];
let approveWarning = true;
const normalized = source
.replace(/^import .*;\s*$/gm, '')
.replace(/^export /gm, '');
const factory = new Function('t', 'th', 'formatNumber', 'openMediaViewer', 'buildArweaveDataUrl',
'validateArweaveTxId', 'validateSha256Hex', 'resolvePublicFileUrl', 'validatePublicPiecesRoot', 'confirmDialog', 'document', 'window', 'fetch',
`${normalized}\nreturn { getAttachmentKind, isPotentiallyActiveAttachment, createAttachmentCarouselElement, parseMessageAttachments };`);
const api = factory(
(key) => key,
() => '<span>FILE</span></div>',
(number) => String(number),
(...args) => viewerCalls.push(args),
({ txId }) => `https://arweave.net/${txId}`,
(id) => /^[A-Za-z0-9_-]{43}$/.test(id),
(id) => /^[a-f0-9]{64}$/.test(id),
async ({ pr, sha256 }) => pr ? `https://files.shineup.me/${pr}` : `https://old.example/files/${sha256}`,
validatePublicPiecesRoot,
async (options) => { warningCalls.push(options); return approveWarning; },
{ createElement: (tag) => new TestElement(tag) },
{ location: { origin: 'https://shineup.me', assign: (url) => navigations.push(url) }, open() {} },
async () => ({ ok: true }),
);
return { ...api, viewerCalls, warningCalls, navigations, setApproveWarning: (value) => { approveWarning = value; } };
}
const settle = () => new Promise((resolve) => setImmediate(resolve));
test('MIME имеет приоритет над расширением, старые файлы определяются по расширению', () => {
const { getAttachmentKind } = loadRenderer();
assert.equal(getAttachmentKind({ name: 'без расширения', mm: 'image/jpeg' }), 'image');
assert.equal(getAttachmentKind({ name: 'clip.bin', mm: 'video/mp4' }), 'video');
assert.equal(getAttachmentKind({ name: 'photo.jpg', mm: 'application/pdf' }), 'file');
assert.equal(getAttachmentKind({ name: 'legacy.webp' }), 'image');
assert.equal(getAttachmentKind({ name: 'legacy.mp4', mm: 'application/octet-stream' }), 'video');
assert.equal(getAttachmentKind({ name: 'archive.zip' }), 'file');
});
test('публичный R2: img/video отображаются в сообщении, PDF остаётся карточкой; просмотрщик открывается', async () => {
const { createAttachmentCarouselElement, viewerCalls } = loadRenderer();
const pr = 'A'.repeat(43);
const wrap = createAttachmentCarouselElement([
{ name: 'photo.jpg', size: 234, pr, mm: 'image/jpeg' },
{ name: 'clip.bin', size: 456, pr, mm: 'video/mp4' },
{ name: 'manual.pdf', size: 567, pr, mm: 'application/pdf' },
]);
assert.match(wrap.className, /message-attachment-list/);
await settle();
const [imageSlot, videoSlot, fileSlot] = wrap.children;
assert.equal(imageSlot.children[0].querySelectorAll('img').length, 1);
assert.equal(imageSlot.children[0].children[0].src, `https://files.shineup.me/${pr}`);
assert.equal(videoSlot.children[0].querySelectorAll('video').length, 1);
assert.equal(videoSlot.children[0].children[0].preload, 'metadata');
assert.match(fileSlot.children[0].className, /message-attachment-file-card/);
imageSlot.children[0].fire('click');
assert.equal(viewerCalls.length, 1);
assert.equal(viewerCalls[0][0].length, 2);
assert.equal(viewerCalls[0][1], 0);
videoSlot.children[0].fire('click');
assert.equal(viewerCalls[1][1], 1);
});
test('публичный Arweave и старые sha256-вложения тоже показывают изображения', async () => {
const { createAttachmentCarouselElement } = loadRenderer();
const wrap = createAttachmentCarouselElement([
{ name: 'arweave.png', size: 90, pr: 'A'.repeat(43), ar: 'B'.repeat(43), mm: 'image/png' },
{ name: 'old.jpeg', size: 91, sha256: 'a'.repeat(64) },
]);
await settle();
assert.equal(wrap.children[0].children[0].children[0].src, `https://arweave.net/${'B'.repeat(43)}`);
assert.equal(wrap.children[1].children[0].children[0].src, `https://old.example/files/${'a'.repeat(64)}`);
});
test('DM сохраняют отдельную карусель с переданным resolveUrl', async () => {
const { createAttachmentCarouselElement } = loadRenderer();
const wrap = createAttachmentCarouselElement([
{ name: 'secret.jpg', size: 123 },
], { resolveUrl: async () => ({ url: 'blob:test-secret', objectUrl: false }) });
assert.match(wrap.className, /message-attachment-carousel/);
await settle();
assert.equal(wrap.querySelectorAll('img').length, 1);
assert.equal(wrap.querySelectorAll('img')[0].src, 'blob:test-secret');
});
test('S:att pr/mm разбирается без изменения формата сообщения', () => {
const { parseMessageAttachments, getAttachmentKind } = loadRenderer();
const pr = 'A'.repeat(43);
const parsed = parseMessageAttachments(`<S:att;v=1;nm=photo.jpg;sz=123456;pr=${pr};mm=image/jpeg>\nКомментарий`);
assert.equal(parsed.attachments.length, 1);
assert.equal(parsed.attachments[0].pr, pr);
assert.equal(parsed.attachments[0].mm, 'image/jpeg');
assert.equal(getAttachmentKind(parsed.attachments[0]), 'image');
assert.equal(parsed.text, 'Комментарий');
});
test('если браузер не может декодировать медиа, остаётся карточка для скачивания', async () => {
const { createAttachmentCarouselElement } = loadRenderer();
const wrap = createAttachmentCarouselElement([{ name: 'bad.png', size: 100, pr: 'A'.repeat(43), mm: 'image/png' }]);
await settle();
wrap.querySelectorAll('img')[0].fire('error');
assert.match(wrap.children[0].children[0].className, /message-attachment-file-card/);
});
test('просмотрщик импортирует t для aria-label диалога', async () => {
const viewer = await readFile(new URL('../js/components/media-viewer.js', import.meta.url), 'utf8');
assert.match(viewer, /import \{ t, th \} from '\.\.\/i18n\/index\.js';/);
});
test('публичное видео не получает src до входа в область просмотра', async () => {
const previous = globalThis.IntersectionObserver;
const observers = [];
class FakeIntersectionObserver {
constructor(callback, options) { this.callback = callback; this.options = options; this.targets = new Set(); observers.push(this); }
observe(node) { this.targets.add(node); }
unobserve(node) { this.targets.delete(node); }
disconnect() { this.targets.clear(); }
reveal(node) { this.callback([{ target: node, isIntersecting: true }]); }
}
globalThis.IntersectionObserver = FakeIntersectionObserver;
try {
const { createAttachmentCarouselElement } = loadRenderer();
const root = createAttachmentCarouselElement([{ name: 'clip.mp4', size: 1000, pr: 'A'.repeat(43), mm: 'video/mp4' }]);
await settle();
const video = root.querySelectorAll('video')[0];
assert.equal(video.preload, 'none');
assert.equal(video.src, undefined);
assert.equal(observers.length, 1);
observers[0].reveal(video);
assert.equal(video.src, `https://files.shineup.me/${'A'.repeat(43)}`);
assert.equal(video.preload, 'metadata');
assert.equal(observers[0].targets.size, 0);
} finally {
if (previous === undefined) delete globalThis.IntersectionObserver;
else globalThis.IntersectionObserver = previous;
}
});
test('HTML/SVG открываются только после подтверждения, отказ не навигирует', async () => {
const api = loadRenderer();
const root = api.createAttachmentCarouselElement([
{ name: 'vector.svg', size: 500, pr: 'A'.repeat(43), mm: 'image/svg+xml' },
{ name: 'run.html', size: 400, pr: 'A'.repeat(43), mm: 'text/html' },
]);
await settle();
assert.equal(root.querySelectorAll('img').length, 0);
assert.equal(root.querySelectorAll('video').length, 0);
assert.match(root.children[0].children[0].className, /file-card/);
api.setApproveWarning(false);
root.children[0].children[0].fire('click');
await settle();
assert.equal(api.warningCalls.length, 1);
assert.equal(api.navigations.length, 0);
api.setApproveWarning(true);
root.children[1].children[0].fire('click');
await settle();
assert.equal(api.warningCalls.length, 2);
assert.deepEqual(api.navigations, [`https://files.shineup.me/${'A'.repeat(43)}`]);
});
@@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { encodePublicPiecesRoot, validatePublicPiecesRoot } from '../js/services/public-pieces-root.js';
import { preparePublicFile } from '../js/services/file-preparation-service.js';
import { publicR2Url } from '../js/services/public-file-service.js';
import { buildAttachmentBlock, parseMessageAttachments, normalizeAttachment } from '../js/services/attachment-format.js';
import { computeTorrentV2PieceRoot } from '../js/services/torrent-v2-service.js';
test('Base58-кодирование публичного PR: 32 байта, в том числе ведущие нули', () => {
const vectors = [
[0, '1'.repeat(32)],
[1, '4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi'],
[255, 'JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG'],
];
for (const [value, expected] of vectors) {
assert.equal(encodePublicPiecesRoot(new Uint8Array(32).fill(value)), expected);
assert.equal(validatePublicPiecesRoot(expected), true);
assert.equal(publicR2Url(expected), `https://files.shineup.me/${expected}`);
}
assert.throws(() => encodePublicPiecesRoot(new Uint8Array(31)));
});
test('не принимает старый Base64URL, некорректные символы, длину и ненормализованные значения', () => {
for (const invalid of [
'', 'A'.repeat(42) + '_', 'A'.repeat(42) + '-', 'A'.repeat(43) + '=',
'0'.repeat(44), 'O'.repeat(44), 'I'.repeat(44), 'l'.repeat(44),
'A'.repeat(31), 'A'.repeat(45), '1'.repeat(33), ` ${'1'.repeat(32)}`,
]) {
assert.equal(validatePublicPiecesRoot(invalid), false, invalid);
assert.throws(() => publicR2Url(invalid), invalid);
}
});
test('подготовка публичного файла создаёт BitTorrent v2 PR именно в Base58', async () => {
const bytes = Uint8Array.from([10, 20, 30, 40, 50, 60, 70]);
const file = new File([bytes], 'photo.png', { type: 'image/png' });
const prepared = await preparePublicFile(file);
const expectedMerkleRoot = await computeTorrentV2PieceRoot(bytes);
assert.equal(prepared.pr, encodePublicPiecesRoot(expectedMerkleRoot));
assert.equal(validatePublicPiecesRoot(prepared.pr), true);
assert.equal(prepared.mm, 'image/png');
assert.equal(prepared.size, bytes.length);
});
test('публичный S:att сохраняет PR в Base58 без перекодирования, включая Arweave', () => {
for (const value of [0, 1, 255]) {
const pr = encodePublicPiecesRoot(new Uint8Array(32).fill(value));
const attachment = { name: 'photo.jpg', size: 100, pr, mm: 'image/jpeg', ar: '' };
const encoded = buildAttachmentBlock(attachment);
assert.match(encoded, new RegExp(`;pr=${pr};mm=image/jpeg>`));
const decoded = parseMessageAttachments(`${encoded}\nТекст`);
assert.equal(decoded.attachments.length, 1);
assert.equal(decoded.attachments[0].pr, pr);
assert.equal(decoded.text, 'Текст');
assert.equal(normalizeAttachment({ ...attachment, ar: 'A'.repeat(43) }).ar, 'A'.repeat(43));
}
const legacyEncoded = `<S:att;v=1;nm=photo.jpg;sz=100;pr=${'A'.repeat(42)}_>`;
assert.equal(parseMessageAttachments(legacyEncoded).attachments.length, 0);
});
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { preventPagePinchZoom } from '../js/services/pwa-viewport-gestures.js';
const ui = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const source = (path) => readFileSync(resolve(ui, path), 'utf8');
test('PWA запрещает масштабирование, сохраняя прокрутку содержимого', () => {
const html = source('index.html');
assert.match(html, /initial-scale=1, maximum-scale=1, user-scalable=no/);
const shell = source('styles/app-shell.css');
assert.match(shell, /\.screen-content\s*\{[^}]*overflow-y:\s*auto/s);
assert.match(shell, /\.screen-content\s*\{[^}]*overflow-x:\s*hidden/s);
assert.match(source('styles/main.css'), /touch-action:\s*pan-x pan-y/);
});
test('pinch-zoom блокируется, но одно касание не блокируется', () => {
const handlers = new Map();
const target = { addEventListener(name, callback, options) {
handlers.set(name, { callback, options });
} };
preventPagePinchZoom(target);
for (const name of ['gesturestart', 'gesturechange', 'touchmove']) {
assert.equal(handlers.get(name).options.passive, false);
}
let prevented = 0;
const event = (count) => ({ touches: Array(count).fill({}), cancelable: true, preventDefault() { prevented++; } });
handlers.get('touchmove').callback(event(1));
assert.equal(prevented, 0);
handlers.get('touchmove').callback(event(2));
assert.equal(prevented, 1);
handlers.get('gesturestart').callback(event(2));
handlers.get('gesturechange').callback(event(2));
assert.equal(prevented, 3);
});
test('единый просмотр аватара подключён к обоим профилям и закрывается при cleanup', () => {
for (const page of ['profile-view.js', 'user-profile-view.js']) {
const js = source(`js/pages/${page}`);
assert.match(js, /attachProfileAvatarPreview\(body\.querySelector\('\.user-profile-avatar-slot'\), card\)/);
assert.match(js, /avatarPreview\?\.cleanup\(\)/);
}
const viewer = source('js/components/profile-avatar-preview.js');
assert.match(viewer, /largeButton\.append\(avatar\)/);
assert.match(viewer, /trigger\.append\(avatar\)/);
assert.match(viewer, /event\.key === 'Escape'/);
assert.match(viewer, /window\.addEventListener\('popstate', onPopState\)/);
});
@@ -0,0 +1,44 @@
import { expandRussian } from './i18n-source-helper.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const read = path => expandRussian(fs.readFileSync(`${root}/${path}`,'utf8'));
const registry=read('SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/JsonHandlerRegistry.java');
const api=read('shine-UI/js/services/registration-v2-api.js');
const ops=['GetNamespaces','CheckRegistrationLogin','CheckRegistrationEmail',
'StartFreeRegistration','ConfirmFreeRegistration','GetRegistrationStatus'];
test('в серверном реестре ровно согласованные шесть операций, каждый op имеет request type',()=>{
for(const op of ops) {
assert.ok(registry.includes(`Map.entry("${op}", new Net_Registration_Handler`));
assert.ok(registry.includes(`Map.entry("${op}", Net_Registration_Request.class`));
}
assert.doesNotMatch(registry,/Map\.entry\("CheckRegistrationAvailability"/);
});
test('проверки login и email независимы и не отправляют лишних данных',()=>{
assert.match(api,/checkRegistrationLogin = .*call\('CheckRegistrationLogin', \{ fullLogin:/);
assert.match(api,/checkRegistrationEmail = .*call\('CheckRegistrationEmail', \{ email \}/);
});
test('free-регистрация передаёт ровно три публичных ключа, не пароли и не секреты',()=>{
const request=api.match(/export const startFreeRegistration = \([\s\S]*?\n\}\);/);
assert.ok(request);
assert.match(request[0],/rootPublicKeyB64/);
assert.match(request[0],/blockchainPublicKeyB64/);
assert.match(request[0],/clientPublicKeyB64/);
assert.doesNotMatch(request[0],/password|masterSecret|privatePkcs8|seed32/);
});
test('free экран вводит код из письма и ждёт Turbo, платный upgrade проверяет ключи',()=>{
const email=read('shine-UI/js/pages/registration-email-view.js');
assert.match(email,/Введите код из письма/);assert.match(email,/confirmFreeRegistration/);
assert.doesNotMatch(email,/код 1111/);
assert.match(email,/completeRegistrationLogin/);
const upgrade=read('shine-UI/js/pages/registration-upgrade-view.js');
assert.match(upgrade,/keys\.rootPair/);assert.match(upgrade,/bytesToBase58/);
assert.match(upgrade,/upgradeFreeUserOnSolana/);
});
test('никто не выкладывает регистрационный email в debug log',()=>{
const processor=read('SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/JsonInboundProcessor.java');
assert.match(processor,/registration payload redacted/);
});
@@ -0,0 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
const schema = fs.readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql', import.meta.url), 'utf8');
const current = schema.slice(schema.lastIndexOf('CREATE OR REPLACE FUNCTION shine_blocks_connection_state_ai() RETURNS TRIGGER'));
test('социальные проекции нормализуют target, не изменяя блоки', () => {
assert.match(current, /VALUES\(lower\(NEW\.login\),1,lower\(NEW\.to_login\),/);
assert.match(current, /WHERE from_login=lower\(NEW\.login\)/);
assert.match(current, /INSERT INTO message_stats\(to_login,to_block_number,to_block_hash,replies_count\)[\s\S]*?VALUES\(lower\(NEW\.to_login\),/);
assert.match(current, /VALUES\(lower\(NEW\.login\),NEW\.msg_sub_type,lower\(NEW\.to_login\),/);
});
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const read = file => fs.readFileSync(new URL(file, import.meta.url), 'utf8');
const auth = read('../js/services/auth-service.js');
const register = read('../js/pages/register-view.js');
const termsPath = new URL('../js/pages/registration-terms-view.js', import.meta.url);
const hasRegistrationTerms = fs.existsSync(termsPath);
const terms = hasRegistrationTerms ? read('../js/pages/registration-terms-view.js') : '';
const router = read('../js/router.js');
const email = read('../js/pages/registration-email-view.js');
const paid = read('../js/pages/registration-payment-view.js');
// Исполняем именно production-сериализатор, а не дублируем алгоритм тестовым кодом.
const makeBytesFunction = auth.split('function makeHeaderBodyBytes(')[1]?.split('\nfunction makeUserParamBodyBytes(')[0];
assert.ok(makeBytesFunction);
const context = {
utf8Bytes: value => new TextEncoder().encode(value),
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
Uint8Array,
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
};
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('HEADER v2 places literal license:CC0-1.0 before the initial key', () => {
const key = Uint8Array.from({ length: 32 }, (_, n) => n + 1);
const result = makeHeaderBodyBytes({ login: 'Alice@shine', initialBlockchainKey32: key });
const login = new TextEncoder().encode('Alice@shine');
assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE');
assert.equal(result[5], login.length);
assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login));
assert.equal(new TextDecoder().decode(result.slice(6+login.length, 6+login.length+15)), 'license:CC0-1.0');
assert.deepEqual(Array.from(result.slice(6+login.length+15)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 15 + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
});
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {
assert.match(register, /navigate\('registration-terms-view'\)/);
assert.match(terms, /draft\.termsAccepted = true/);
assert.match(terms, /draft\.flowType === 'free' \? 'registration-email-view' : 'registration-payment-view'/);
assert.match(email, /if \(!state\.registrationDraft\.termsAccepted\)/);
assert.match(paid, /if \(!state\.registrationDraft\.termsAccepted\)/);
assert.match(router, /\['registration-terms-view', 'register\/terms'\]/);
assert.match(terms, /CC0_LEGAL_CODE_URL/);
assert.match(terms, /DOCUMENT_COUNT = 4/);
});
@@ -0,0 +1,14 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const contract = readFileSync(new URL('../../shine-solana/shine/programs/shine_users/src/lib.rs', import.meta.url), 'utf8');
test('контракт не берёт депозит PDA поверх цены namespace', () => {
const create = contract.split('fn process_create_user_pda')[1].split('fn process_update_user_pda')[0];
assert.match(create, /minimum_balance\(settings::USER_PDA_SPACE\)/);
assert.match(create, /namespace\.registration_fee >= required_rent/);
assert.match(create, /required_rent\.saturating_sub\(user_pda\.lamports\(\)\)/);
assert.match(create, /namespace\.registration_fee\s*\.checked_sub\(rent_paid_by_signer\)/);
assert.match(create, /transfer_lamports\(signer, inflow_vault, system_program_ai, vault_fee\)/);
assert.doesNotMatch(create, /namespace\.registration_fee\.checked_add\(limit_fee_lamports/);
});
@@ -0,0 +1,108 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
const paymentView = fs.readFileSync(new URL('../js/pages/registration-payment-view.js', import.meta.url), 'utf8');
const emailView = fs.readFileSync(new URL('../js/pages/registration-email-view.js', import.meta.url), 'utf8');
const authService = fs.readFileSync(new URL('../js/services/auth-service.js', import.meta.url), 'utf8');
const finish = paymentView.split('export async function completeRegistrationLogin')[1]?.split('\nexport function render(')[0] || '';
test('Solana и Arweave используют единое завершение регистрации', () => {
assert.match(paymentView, /await completeRegistrationLogin\(\{ navigate, keyBundle \}\)/);
assert.match(emailView, /await completeRegistrationLogin\(\{\s*navigate,\s*keyBundle:\s*draft\.preGeneratedKeyBundle\s*\}\)/);
assert.match(emailView, /if \(!draft\.dataItemId\) \{/);
assert.match(paymentView, /authService\.resetConnection\(state\.entrySettings\.shineServer, \{ clearSessionContext: true \}\)/);
assert.doesNotMatch(emailView, /const retry = document\.createElement\('button'\)/);
assert.match(emailView, /confirm\.textContent = t\('screens\.registration_email_view\.text_009'\)/);
});
test('после авторизации на завершении регистрации создаётся HEADER с актуальными логином и ключом', () => {
assert.match(finish, /authorizeSession\(\{[\s\S]*?login: resumedLogin,[\s\S]*?storagePwd: resumedStoragePwd,[\s\S]*?\}\);[\s\S]*?await authService\.ensureBlockchainHeader\(resumedLogin, resumedStoragePwd\)/);
assert.equal((finish.match(/ensureBlockchainHeader\(/g) || []).length, 1);
});
test('сбой HEADER не отменяет регистрацию; защита перед первым блоком сохранена', () => {
assert.match(finish, /try \{\s*await authService\.ensureBlockchainHeader\(resumedLogin, resumedStoragePwd\);\s*\} catch \(error\) \{[\s\S]*?console\.warn\(/);
assert.match(authService, /if \(!_skipHeaderEnsure && !isHeader\) \{\s*await this\.ensureBlockchainHeader\(cleanLogin, storagePwd\)/);
});
test('новый вход восстанавливается на новом WebSocket после ALREADY_AUTHED', () => {
assert.match(authService, /if \(this\.ws\.isSessionReady\(\)\) \{[\s\S]*?this\.resetConnection\(this\.serverUrl, \{ clearSessionContext: true \}\);/);
assert.match(authService, /for \(let attempt = 0; attempt < 2; attempt \+= 1\) \{[\s\S]*?challengeResp = await this\.ws\.request\('AuthChallenge'/);
assert.match(authService, /attempt === 0 && error\.code === 'ALREADY_AUTHED'/);
assert.match(authService, /this\.resetConnection\(this\.serverUrl, \{ clearSessionContext: true \}\);[\s\S]*?continue;/);
});
test('после CreateAuthSession регистрация не запускает второй handshake на том же сокете', () => {
assert.match(finish, /const resumedLogin = result\.login;[\s\S]*?authorizeSession\(\{[\s\S]*?storagePwd: resumedStoragePwd/);
assert.doesNotMatch(finish, /await authService\.resumeSession\(/);
});
test('локальное хранилище ключей имеет fallback при сбое IndexedDB', () => {
const vault = fs.readFileSync(new URL('../js/services/key-vault.js', import.meta.url), 'utf8');
assert.match(vault, /memorySecrets\.set\(normalizedLogin, row\)/);
assert.match(vault, /writeFallbackRow\(FALLBACK_SECRETS_KEY, normalizedLogin, row\)/);
assert.match(vault, /memorySessions\.set\(normalizedLogin, row\)/);
assert.match(vault, /writeFallbackRow\(FALLBACK_SESSIONS_KEY, normalizedLogin, row\)/);
});
// Проверяем выполнение настоящей функции с изолированными зависимостями:
// ошибка HEADER не должна прерывать завершение регистрации.
async function simulateCompletion({ headerFails = false } = {}) {
const vm = await import('node:vm');
const calls = [];
const state = {
entrySettings: { shineServer: 'wss://test.invalid' },
registrationDraft: { login: 'AlexSmith@shine', password: 'secret' },
loginDraft: {},
registrationPayment: {},
authReturnHash: '',
};
const authService = {
async reconnect() {},
resetConnection() {},
async createSessionForExistingUser() {
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session', sessionMaterial: {} };
},
async persistSelectedKeys() {},
async persistSessionMaterial() {},
async resumeSession() {
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session' };
},
async ensureBlockchainHeader(login, storagePwd) {
calls.push(['header', login, storagePwd]);
if (headerFails) throw new Error('temporary error');
},
};
const context = {
t: (key) => key,
authService,
state,
EMPTY_PASSWORD_WORDS: Array(12).fill(''),
clearStoredMessages: async () => {},
authorizeSession: ({ login }) => calls.push(['authorized', login]),
refreshSessions: async () => calls.push(['refreshed']),
setAuthInfo: () => calls.push(['info']),
resetRegistrationFlow: () => {
state.registrationDraft.password = '';
},
console: { warn: (...args) => calls.push(['warning', ...args]) },
};
const func = vm.runInNewContext(`async function completeRegistrationLogin${finish}\ncompleteRegistrationLogin`, context);
await func({ keyBundle: {}, navigate: target => calls.push(['navigate', target]) });
return { calls, state };
}
test('после регистрации HEADER отправляется до экрана поздравления', async () => {
const { calls } = await simulateCompletion();
assert.deepEqual(calls[0], ['authorized', 'AlexSmith@shine']);
assert.deepEqual(calls[1], ['header', 'AlexSmith@shine', 'stored']);
assert.deepEqual(calls.at(-1), ['navigate', 'registration-success-view']);
});
test('при ошибке HEADER регистрацию не откатываем и остаёмся в аккаунте', async () => {
const { calls, state } = await simulateCompletion({ headerFails: true });
assert.ok(calls.some(item => item[0] === 'warning'));
assert.deepEqual(calls.at(-1), ['navigate', 'registration-success-view']);
assert.equal(state.registrationDraft.password, '');
});
@@ -0,0 +1,69 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { resolve, dirname } from 'node:path';
import { encodeNamespacePda, decodeNamespacePda, normalizeFullLogin, userPdaSeed32,
namespacePdaSeed32, buildFreeCertificateInnerMessage } from '../js/services/shine-namespace-service.js';
import { serializeCreateUserPdaArgs } from '../js/services/shine-user-pda-service.js';
const dirnameHere = dirname(fileURLToPath(import.meta.url));
const props = Object.fromEntries(fs.readFileSync(resolve(dirnameHere, '../../shine-solana/shine/tests/fixtures/registration-v2.properties'), 'utf8')
.split(/\r?\n/).filter(x => x.includes('=')).map(line => [line.slice(0,line.indexOf('=')), line.slice(line.indexOf('=')+1)]));
const hex = x => Buffer.from(x).toString('hex');
const bh = x => Uint8Array.from(Buffer.from(x, 'hex'));
test('строгая нормализация полных логинов', () => {
assert.equal(normalizeFullLogin('alice@shine'), 'alice@shine');
assert.equal(normalizeFullLogin('ALICE@shine'), 'ALICE@shine');
assert.equal(normalizeFullLogin('AlIcE@shine'), 'AlIcE@shine');
for (const bad of ['alice','alice@Shine',' alice@shine','alice@@shine','alice.s@shine','a'.repeat(30)+'@a'])
assert.throws(() => normalizeFullLogin(bad));
assert.notEqual(normalizeFullLogin('a_b@shine'), normalizeFullLogin('ab@shine'));
});
test('namespace v1.0 совместим, а сериализация v1.1 добавляет код валюты', () => {
const raw = bh(props.namespace_free_bytes_hex);
const ns = decodeNamespacePda(raw);
assert.equal(ns.namespace, 'free'); assert.equal(ns.type, 2);
assert.equal(ns.serverLogin, 'registrar@shine');
assert.equal(ns.currencyCode, 1);
const modern = encodeNamespacePda(ns);
assert.equal(modern[1], 1);
assert.equal(modern.length, raw.length + 1);
assert.deepEqual(decodeNamespacePda(modern).registrationFeeLamports, ns.registrationFeeLamports);
assert.equal(decodeNamespacePda(modern).serverLogin, 'registrar@shine');
const malformed = new Uint8Array(modern);
malformed[5 + raw[4] + 8] = 2;
assert.throws(() => decodeNamespacePda(malformed), /не поддерживается/);
assert.throws(() => decodeNamespacePda(new Uint8Array([...raw, 0])));
assert.throws(() => decodeNamespacePda(raw.slice(0,-1)));
});
test('SHA256 PDA seeds stable and domain separated', async () => {
assert.equal(hex(await userPdaSeed32('bob@free')), props.user_bob_free_seed);
assert.equal(hex(await namespacePdaSeed32('free')), props.namespace_free_seed);
assert.notEqual(hex(await userPdaSeed32('bob@free')), hex(await namespacePdaSeed32('free')));
assert.equal(hex(await userPdaSeed32('BoB@free')), hex(await userPdaSeed32('bob@free')));
assert.equal(hex(await userPdaSeed32('BOB@free')), hex(await userPdaSeed32('bob@free')));
});
test('inner message is byte-for-byte fixture', () => {
const b = buildFreeCertificateInnerMessage('bob@free',
bh('03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8'),
bh('29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7'),
bh('2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d'));
assert.equal(hex(b), props.inner_message_hex);
const mixed = buildFreeCertificateInnerMessage('BoB@free',
bh('03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8'),
bh('29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7'),
bh('2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d'));
assert.notEqual(hex(mixed), hex(b)); // Подпись сертификата включает оригинальный регистр.
});
test('create instruction suffix encodes registrar signature, never promo', () => {
const common = {login:'bob@free', rootKey32: new Uint8Array(32), createdAtMs:1n,
clientKey32:new Uint8Array(32), blockchainKey32:new Uint8Array(32),
recordSignature64:new Uint8Array(64), accessServers:[], serverAddresses:[]};
const paid = serializeCreateUserPdaArgs(common);
const free = serializeCreateUserPdaArgs({...common, registrarSignature64: new Uint8Array(64).fill(7)});
assert.equal(paid[paid.length-1], 0);
assert.equal(free[paid.length-1], 1);
assert.deepEqual(free.slice(paid.length), new Uint8Array(64).fill(7));
assert.equal(free[0],3);
});
@@ -0,0 +1,42 @@
import { expandRussian } from './i18n-source-helper.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const read = (path) => expandRussian(readFileSync(new URL(path, import.meta.url), 'utf8'));
const upgrade = read('../js/pages/registration-upgrade-view.js');
const direct = read('../js/pages/registration-payment-view.js');
const styles = read('../styles/features/preauth.css');
test('новая регистрация и платный переход используют общую видимую панель кошелька', () => {
for (const source of [direct, upgrade]) {
assert.match(source, /registration-payment-card/);
assert.match(source, /Ваш Solana-кошелёк в Сиянии/);
assert.match(source, /Скопировать адрес/);
assert.match(source, /registration-payment-copy-btn/);
assert.match(source, /registration-payment-balance-value/);
assert.match(source, /registration-payment-refresh-btn/);
assert.match(source, /↻ Обновить/);
assert.match(source, /registration-payment-topup-btn/);
assert.match(source, /secondary-btn registration-payment-action/);
}
});
test('баланс и его обновление находятся в одной строке, а сумма визуально выделена', () => {
assert.match(styles, /\.registration-payment-balance\s*\{[^}]*display:\s*flex/s);
assert.match(styles, /\.registration-payment-balance-value\s*\{[^}]*font-size:\s*clamp\(/s);
assert.match(styles, /\.registration-payment-action\s*\{[^}]*border:\s*1px solid/s);
assert.match(upgrade, /balanceRow\.append\(balanceInfo, refreshButton\)/);
assert.match(direct, /balanceRow\.append\(balanceInfo, refreshButton\)/);
});
test('обе страницы используют стоимость namespace с депозитом внутри', () => {
assert.match(direct, /calculateRegistrationFunding\(/);
assert.match(direct, /loadFunding\(\)/);
assert.match(direct, /getMinimumBalanceForRentExemption\(USER_PDA_SPACE/);
assert.doesNotMatch(direct, /namespaceFeeSol \+ 0\.004/);
assert.match(upgrade, /calculateUpgradeFunding\(\{ namespaceFeeLamports: namespace\.registrationFeeLamports, rentLamports \}\)/);
assert.match(upgrade, /Депозит PDA уже включён/);
assert.match(upgrade, /if \(isDevnet\) payment\.append\(topupButton, testHint\)/);
assert.match(direct, /if \(isTestContour\) \{/);
});
@@ -0,0 +1,52 @@
import { expandRussian } from './i18n-source-helper.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
const read = relative => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8'));
test('выбор аккаунта перед шагом 1, всего три шага', () => {
const choice = read('../js/pages/registration-choice-view.js');
const login = read('../js/pages/register-view.js');
const email = read('../js/pages/registration-email-view.js');
const payment = read('../js/pages/registration-payment-view.js');
assert.doesNotMatch(choice, /createRegistrationStepper\(/);
assert.match(login, /createRegistrationStepper\(1\)/);
assert.match(login, /createRegistrationStepper\(2\)/);
assert.match(email, /createRegistrationStepper\(3\)/);
assert.match(payment, /createRegistrationStepper\(3\)/);
});
test('реальная почта и 256-символьный лимит сохранены', () => {
const email = read('../js/pages/registration-email-view.js');
const passwords = read('../js/services/password-words.js');
assert.match(email, /startFreeRegistration\(/);
assert.match(email, /confirmFreeRegistration\(/);
assert.match(passwords, /PASSWORD_MAX_LENGTH = 256/);
});
test('пароль допускает один символ, а email можно изменить без устаревшего запроса', () => {
const registration = read('../js/pages/register-view.js');
const email = read('../js/pages/registration-email-view.js');
assert.match(registration, /value\.length < 1/);
assert.doesNotMatch(registration, /value\.length < 12/);
assert.match(registration, /createExpandablePasswordTextarea\(\)/);
const passwordField = read('../js/components/visible-password-field.js');
assert.match(passwordField, /createExpandablePasswordTextarea/);
assert.match(passwordField, /input\.tagName === 'TEXTAREA'/);
assert.match(email, /let emailRequestId = 0/);
assert.match(email, /requestId !== emailRequestId/);
assert.match(email, /emailRequestId \+= 1/);
});
test('старт регистрации использует иллюстрацию и русское название', () => {
const intro = read('../js/pages/registration-intro-view.js');
assert.match(intro, /registration-sunrise-space\.png/);
assert.match(intro, /Добро пожаловать в Сияние/);
assert.match(intro, /Ваши публикации, сообщения и лайки хранятся вечно/);
assert.doesNotMatch(intro, /SHiNE\//);
});
test('экран поздравления объясняет различие статусов', () => {
const finish = read('../js/pages/registration-success-view.js');
assert.match(finish, /registrationSuccess\?\.flowType === 'paid'/);
assert.match(finish, /Arweave/);
assert.match(finish, /PDA/);
assert.match(finish, /не является полностью децентрализованным/);
assert.match(finish, /не можем восстановить пароль/);
assert.match(finish, /Войти в Сияние/);
});
@@ -0,0 +1,68 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import {
USER_PDA_SPACE, calculateUpgradeFunding, isUpgradeComplete, solFromLamports,
} from '../js/services/registration-upgrade-helpers.js';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const read = file => readFileSync(resolve(root, file), 'utf8');
test('обе регистрации оплачивают цену namespace с включённым депозитом PDA', () => {
assert.equal(USER_PDA_SPACE, 768);
const result = calculateUpgradeFunding({ namespaceFeeLamports: 20_000_000n, rentLamports: 6_000_000n });
assert.equal(result.namespaceFee, 20_000_000n);
assert.equal(result.rent, 6_000_000n);
assert.equal(result.projectFee, 14_000_000n);
assert.equal(result.networkReserve, 100_000n);
assert.equal(result.requiredLamports, 20_100_000n);
assert.equal(solFromLamports(result.requiredLamports), '0.020100');
assert.throws(() => calculateUpgradeFunding({ namespaceFeeLamports: 5_000_000n, rentLamports: 6_000_000n }), /меньше депозита|remaining\.registration_upgrade\.price_below_rent/);
assert.throws(() => calculateUpgradeFunding({ namespaceFeeLamports: -1, rentLamports: 0 }), /Некорректная|remaining\.registration_upgrade\.invalid_registration_price/);
});
test('после синхронизации Solana оба типа платных аккаунтов имеют статус PAID', () => {
assert.equal(isUpgradeComplete('PAID'), true);
assert.equal(isUpgradeComplete('FREE_CERT'), false);
assert.equal(isUpgradeComplete('NOT_FOUND'), false);
// Совместимость с предыдущим сервером при поэтапном обновлении.
assert.equal(isUpgradeComplete('PAID_UPGRADED'), true);
assert.equal(isUpgradeComplete('PAID_DIRECT'), true);
});
test('в настройках только бесплатным предлагается платный переход', () => {
const settings = read('shine-UI/js/pages/settings-view.js');
assert.match(settings, /info.registrationStatus !== 'FREE_CERT'/);
assert.match(settings, /id="settings-account-tier" hidden/);
assert.match(settings, /t\('dialogs\.modals\.settings_view\.label_004'\)/);
const ru = JSON.parse(read('shine-UI/js/i18n/locales/ru.json'));
assert.match(ru.dialogs.modals.settings_view.label_004, /Бесплатный аккаунт с ограниченными возможностями/);
assert.doesNotMatch(settings, /settings-solana-registered/);
});
test('миграция БД делает статусы действительно едиными', () => {
const migration = read('SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v35.sql');
assert.match(migration, /WHERE registration_status IN \('PAID_DIRECT', 'PAID_UPGRADED'\)/);
assert.match(migration, /CHECK \(registration_status IN \('FREE_CERT', 'PAID'\)\)/);
assert.match(migration, /'SOLANA', 'PAID',/);
assert.match(migration, /free_data_item_id=EXCLUDED|old_user.free_data_item_id/);
assert.doesNotMatch(migration, /DELETE FROM user_identity_current/);
const dbInit = read('SHiNE-server/shine-server-db/src/main/java/shine/db/DatabaseInitializer.java');
assert.match(dbInit, /POSTGRES_MIGRATION_V35_RESOURCE/);
});
test('роут settings/solana-upgrade действительно обслуживается', () => {
const router = read('shine-UI/js/router.js');
assert.match(router, /sub === 'solana-upgrade'\) return \{ pageId: 'registration-upgrade-view'/);
});
test('переход не переименовывает пользователя и не использует черновик обычной регистрации', () => {
const upgrade = read('shine-UI/js/pages/registration-upgrade-view.js');
assert.match(upgrade, /upgradeFreeUserOnSolana\(/);
assert.match(upgrade, /checkLoginExistsOnSolana\(/);
assert.match(upgrade, /getRegistrationStatus\(/);
assert.match(upgrade, /isUpgradeComplete\(current.registrationStatus\)/);
assert.match(upgrade, /namespace\.type !== 2|loadedNamespace\.type !== 2/);
assert.match(upgrade, /getSolanaCluster\(\) === 'devnet'/);
assert.match(upgrade, /fundDevnetRegistrationWallet\(/);
assert.match(upgrade, /screen\.cleanup =/);
assert.doesNotMatch(upgrade, /state\.registrationDraft|resetRegistrationFlow|createSessionForExistingUser/);
const originalPayment = read('shine-UI/js/pages/registration-payment-view.js');
assert.match(originalPayment, /export async function fundDevnetRegistrationWallet\(/);
});
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { validateLoginOrThrow } from '../server-ui/js/server-ui-shared.js';
const read = p => readFileSync(new URL(p, import.meta.url), 'utf8');
test('server UI принимает полные логины и legacy при обновлении', () => {
assert.equal(validateLoginOrThrow('server@shine'), 'server@shine');
assert.equal(validateLoginOrThrow('old_server'), 'old_server');
assert.throws(() => validateLoginOrThrow('x'.repeat(26)+'@shine'));
assert.throws(() => validateLoginOrThrow('server@@shine'));
assert.throws(() => validateLoginOrThrow('server.name@shine'));
});
test('форма создания требует namespace type1 и правильный fee payer', () => {
const page = read('../server-ui/js/create-server-pda-page.js');
const service = read('../js/services/shine-user-pda-service.js');
const html = read('../server-ui/create-server-pda.html');
assert.match(page, /namespace\.type !== 1/);
assert.match(page, /getNamespace\(/);
assert.match(html, /maxlength="30"/);
assert.match(service, /feePayerPrivatePkcs8B64: keyBundle\.clientPair\.privatePkcs8B64/);
});
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { resolveShineTextLink, tokenizeShineMessageLinks } from '../js/services/shine-message-links.js';
import { makeSolanaExplorerTxUrl, setSolanaCluster } from '../js/services/solana-rpc-gateway.js';
function links(text, viewMode = 'thread') {
return tokenizeShineMessageLinks(text, { viewMode }).filter((item) => item.type !== 'text');
}
test('обычная ссылка на публикацию сохраняет режим просмотра', () => {
const source = 'SHiNE/aidar/news/34';
assert.equal(resolveShineTextLink(source).route, 'SHiNE/aidar/news/34');
assert.equal(resolveShineTextLink(source, { viewMode: 'feed' }).route, 'SHiNE/aidar/news/s/34');
assert.equal(resolveShineTextLink('/' + source, { viewMode: 'feed' }).href, '/SHiNE/aidar/news/s/34');
});
test('явная /s/34 всегда открывает ленту', () => {
for (const viewMode of ['thread', 'feed']) {
assert.equal(resolveShineTextLink('SHiNE/aidar/news/s/34', { viewMode }).route, 'SHiNE/aidar/news/s/34');
}
});
test('канал и профиль не меняются в ленте', () => {
assert.equal(resolveShineTextLink('SHiNE/aidar/news', { viewMode: 'feed' }).route, 'SHiNE/aidar/news');
assert.equal(resolveShineTextLink('SHiNE/aidar', { viewMode: 'feed' }).route, 'SHiNE/aidar');
assert.equal(resolveShineTextLink('SHiNE/aidar@home/news/34', { viewMode: 'feed' }).route, 'SHiNE/aidar@home/news/s/34');
});
test('несколько ссылок в тексте с пунктуацией сохраняют текст', () => {
const message = 'Смотри (SHiNE/aidar/news/34), потом SHiNE/aidar/news/s/6!';
const tokens = tokenizeShineMessageLinks(message, { viewMode: 'feed' });
assert.equal(tokens.map((t) => t.value).join(''), message);
assert.deepEqual(tokens.filter((t) => t.type === 'internal').map((t) => t.route), [
'SHiNE/aidar/news/s/34', 'SHiNE/aidar/news/s/6',
]);
});
test('внешние ссылки открываются отдельно и не преобразуются во внутренние', () => {
const items = links('https://example.org/SHiNE/aidar/news/34 и www.example.com/path?q=1');
assert.equal(items.length, 2);
assert.equal(items[0].type, 'external');
assert.equal(items[0].href, 'https://example.org/SHiNE/aidar/news/34');
assert.equal(items[1].href, 'https://www.example.com/path?q=1');
assert.equal(links('http://localhost:8080/test')[0].href, 'http://localhost:8080/test');
});
test('ссылка транзакции учитывает кластер Solana', () => {
setSolanaCluster('devnet');
assert.equal(
makeSolanaExplorerTxUrl('sig-devnet', 'https://t2.shineup.me/solana-rpc'),
'https://explorer.solana.com/tx/sig-devnet?cluster=devnet',
);
setSolanaCluster('mainnet-beta');
assert.equal(
makeSolanaExplorerTxUrl('sig-mainnet', 'https://shineup.me/solana-rpc'),
'https://explorer.solana.com/tx/sig-mainnet',
);
});
test('опасные протоколы, пустые и встроенные подстроки не становятся ссылками', () => {
assert.equal(links('javascript:alert(1) file:///etc/passwd fooSHiNE/aidar/news/34').length, 0);
assert.equal(links('https:// www. SHiNE/').length, 0);
assert.equal(resolveShineTextLink('SHiNE/aidar/news/34?redirect=evil'), null);
});
test('скобки в URL сохраняются, лишняя закрывающая скобка остаётся текстом', () => {
const message = 'Документ https://example.org/(archive).';
const tokens = tokenizeShineMessageLinks(message);
assert.equal(tokens.map((t) => t.value).join(''), message);
assert.equal(links(message)[0].href, 'https://example.org/(archive)');
});
test('DOM не интерпретирует текст как HTML, а навигация вызывается при обычном клике', async () => {
const { appendShineMessageLinks } = await import('../js/services/shine-message-links.js');
class FakeNode {
constructor(tag = '') { this.tag = tag; this.children = []; this.handlers = {}; }
append(...children) { this.children.push(...children); }
addEventListener(type, handler) { this.handlers[type] = handler; }
set textContent(value) { this.text = value; }
}
const before = globalThis.document;
globalThis.document = {
createTextNode: (value) => ({ value }),
createElement: (tag) => new FakeNode(tag),
};
try {
const root = new FakeNode();
const routes = [];
appendShineMessageLinks(root, '<script> SHiNE/aidar/news/34', {
viewMode: 'feed', navigate: (route) => routes.push(route),
});
assert.equal(root.children[0].value, '<script> ');
const anchor = root.children[1];
assert.equal(anchor.tag, 'a');
assert.equal(anchor.href, '/SHiNE/aidar/news/s/34');
let prevented = false;
anchor.handlers.click({ button: 0, preventDefault() { prevented = true; }, stopPropagation() {} });
assert.equal(prevented, true);
assert.deepEqual(routes, ['SHiNE/aidar/news/s/34']);
} finally {
globalThis.document = before;
}
});
test('сформированные текстовые ссылки открывают существующие страницы роутера', async () => {
const previousWindow = globalThis.window;
globalThis.window = { location: { pathname: '/' } };
try {
const { parseRouteFromPath } = await import('../js/router.js');
const fromFeed = resolveShineTextLink('SHiNE/aidar/news/34', { viewMode: 'feed' });
const inFeed = parseRouteFromPath(fromFeed.href);
assert.equal(inFeed.pageId, 'channel-view');
assert.equal(inFeed.params.scrollToMessageOrdinal, '34');
const fromThread = resolveShineTextLink('SHiNE/aidar/news/34');
const inThread = parseRouteFromPath(fromThread.href);
assert.equal(inThread.pageId, 'channel-thread-view');
assert.equal(inThread.params.messageOrdinal, '34');
assert.equal(parseRouteFromPath('/SHiNE/aidar/news/s/34').pageId, 'channel-view');
assert.equal(parseRouteFromPath('/SHiNE/aidar/news').pageId, 'channel-view');
assert.equal(parseRouteFromPath('/SHiNE/aidar').pageId, 'user');
} finally {
globalThis.window = previousWindow;
}
});
@@ -0,0 +1,85 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import {
deriveStarsPythOracleAccounts,
getStarsQuoteFromRpc,
parseVerifiedPythPriceAccount,
PYTH_SOL_USD_FEED_ID,
PYTH_USDT_USD_FEED_ID,
PYTH_RECEIVER_PROGRAM_ID,
} from '../js/services/shine-stars-pyth.js';
const validOwner = { toBase58: () => PYTH_RECEIVER_PROGRAM_ID };
const now = 1_800_000_000;
const discr = [34,241,35,99,157,126,244,205];
function fakePrice(feed, value, { publish = now - 15, confidence = 20_000_000n, verified = true, owner = validOwner, exponent = -8 } = {}) {
const bytes = new Uint8Array(133);
bytes.set(discr);
bytes[40] = verified ? 1 : 0;
bytes.set(Uint8Array.from(feed.match(/../g), (hex) => parseInt(hex, 16)), 41);
const v = new DataView(bytes.buffer);
v.setBigInt64(73, BigInt(value), true);
v.setBigUint64(81, confidence, true);
v.setInt32(89, exponent, true);
v.setBigInt64(93, BigInt(publish), true);
return { owner, data: bytes };
}
const solPrice = fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n); // $150.00
const usdtPrice = fakePrice(PYTH_USDT_USD_FEED_ID, 100_000_000n, {confidence: 1000n}); // $1.00
// Browser-vendored Solana web3.js; no network required, same code as production.
const context = { Buffer, Uint8Array, TextEncoder, TextDecoder, console, setTimeout, crypto: globalThis.crypto };
vm.createContext(context);
vm.runInContext(readFileSync(new URL('../js/vendor/solana-web3.iife.min.js', import.meta.url), 'utf8'), context);
const solana = context.solanaWeb3;
test('derive shard-0 Pyth Core oracle PDAs (official mainnet examples)', () => {
assert.deepEqual(deriveStarsPythOracleAccounts(solana), {
solUsd: '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE',
usdtUsd: 'HT2PLQBcG5EiCcNSaMHAjSgd9F98ecpATbk4Sk5oYuM',
});
});
test('read raw Anchor PriceUpdateV2 without precision loss', () => {
assert.equal(parseVerifiedPythPriceAccount(solPrice, PYTH_SOL_USD_FEED_ID, now).priceE8, 15_000_000_000n);
assert.equal(parseVerifiedPythPriceAccount(usdtPrice, PYTH_USDT_USD_FEED_ID, now).priceE8, 100_000_000n);
});
test('fail closed for stale/future/unverified/malformed/foreign price accounts', () => {
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {publish: now - 3_601}), PYTH_SOL_USD_FEED_ID, now), /устарела/);
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {publish: now + 16}), PYTH_SOL_USD_FEED_ID, now), /время/);
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {verified:false}), PYTH_SOL_USD_FEED_ID, now), /проверку/);
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n), PYTH_USDT_USD_FEED_ID, now), /другую/);
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {owner:{toBase58:()=> 'Bad'}}), PYTH_SOL_USD_FEED_ID, now), /владельца/);
assert.throws(() => parseVerifiedPythPriceAccount(fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n, {confidence: 150_000_001n}), PYTH_SOL_USD_FEED_ID, now), /интервал/);
const invalid = fakePrice(PYTH_SOL_USD_FEED_ID, 15_000_000_000n);
invalid.data[0] ^= 1;
assert.throws(() => parseVerifiedPythPriceAccount(invalid, PYTH_SOL_USD_FEED_ID, now), /формат/);
});
test('request both accounts once from authenticated Solana RPC, no Hermes', async () => {
let invoked = 0;
const connection = { getMultipleAccountsInfo: async (keys, commitment) => {
invoked++;
assert.equal(keys.length, 2);
assert.equal(commitment, 'confirmed');
assert.equal(keys[0].toBase58(), '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE');
return [solPrice, usdtPrice];
} };
const quote = await getStarsQuoteFromRpc({ solanaEndpoint: 'https://test.shineup.me/solana-rpc', solana, connection, nowSeconds: now });
assert.equal(quote.solUsdE8, '15000000000');
assert.equal(quote.usdtUsdE8, '100000000');
assert.equal(invoked, 1);
await assert.rejects(() => getStarsQuoteFromRpc({ solanaEndpoint: 'https://test.shineup.me/solana-rpc', solana,
connection: { getMultipleAccountsInfo: async () => [solPrice, null] }, nowSeconds: now }), /отсутствует/);
});
test('no server GetStarsQuote in active WS registry or UI', () => {
const reg = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/JsonHandlerRegistry.java', import.meta.url), 'utf8');
const auth = readFileSync(new URL('../js/services/auth-service.js', import.meta.url), 'utf8');
assert.doesNotMatch(reg, /GetStarsQuote/);
assert.doesNotMatch(auth, /GetStarsQuote/);
for (const p of ['../js/components/shine-support-dialog.js', '../js/pages/channel-donate-view.js']) {
const s = readFileSync(new URL(p, import.meta.url), 'utf8');
assert.match(s, /getStarsQuoteFromRpc/);
assert.doesNotMatch(s, /authService\.getStarsQuote/);
}
});
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { parseStarCents, formatStars, splitStarCents, starCentsToLamports } from '../js/services/shine-support-amount.js';
test('strictly two fractional digits, minimum 0.10 Stars', () => {
assert.equal(parseStarCents('0,10'), 10n);
assert.equal(parseStarCents('0.75'), 75n);
assert.equal(formatStars(75n), '0.75 ⭐');
assert.throws(() => parseStarCents('0.09'));
assert.throws(() => parseStarCents('0.001'));
});
test('DAO star share rounds UP to cents', () => {
assert.deepEqual(splitStarCents(10n), {author: 9n, dao: 1n});
assert.deepEqual(splitStarCents(15n), {author: 13n, dao: 2n});
assert.deepEqual(splitStarCents(75n), {author: 67n, dao: 8n});
});
test('quote works in integer lamports without floats', () => {
assert.equal(starCentsToLamports(75n, 150n * 100_000_000n, 100_000_000n), 5_000_000n);
assert.equal(starCentsToLamports(10n, 150n * 100_000_000n, 100_000_000n), 666_667n);
});
@@ -0,0 +1,30 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { parseSolLamports, formatLamportsSol, hexHash32 } from '../js/services/shine-support-amount.js';
const source = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
test('десятичная сумма SOL обрабатывается точно без Number', () => {
assert.equal(parseSolLamports('0.000000010'), 10n);
assert.equal(parseSolLamports('1,25'), 1250000000n);
assert.equal(formatLamportsSol(1250000001n), '1.250000001');
assert.equal(parseSolLamports('0.000000001'), 1n);
for (const value of ['0', '-1', '1.1234567890', '1e3', 'NaN', '']) {
assert.throws(() => parseSolLamports(value), undefined, value);
}
});
test('идентификаторы канала требуют ровно 32 байта hex', () => {
assert.equal(hexHash32('ab'.repeat(32)).length, 32);
assert.equal(hexHash32('ab'.repeat(32))[0], 171);
assert.throws(() => hexHash32('0'));
assert.throws(() => hexHash32('x'.repeat(64)));
});
test('страница канала использует контракт 90/10 и прямой перевод с подтверждением', () => {
const page = source('../js/pages/channel-donate-view.js');
assert.match(page, /supportShineUserOnSolana\(/);
assert.match(page, /transferSolLamports\(/);
assert.match(page, /window\.confirm\(t\('screens\.support_flow\.direct_warning'\)\)/);
assert.match(page, /target: \{ type: 1, channelBlockNumber:/);
assert.match(page, /readShineUserPda\(/);
assert.match(source('../js/services/solana-wallet-service.js'), /export async function transferSolLamports/);
});
@@ -0,0 +1,54 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { supportStatsValues } from '../js/components/support-stats.js';
function file(path) { return readFileSync(new URL(path, import.meta.url), 'utf8'); }
test('three displayed counters: sent, received, direct DAO in star cents', () => {
assert.deepEqual(supportStatsValues({ supportSent: 1_000_000_000n, supportReceived: 900_000_000n, daoDirect: 200_000_000n }), [1_000_000_000n, 900_000_000n, 200_000_000n]);
assert.deepEqual(supportStatsValues({}), [0n, 0n, 0n]);
assert.deepEqual(supportStatsValues({ supportSent: '10000000000000000000', supportReceived: '9000000000000000000', daoDirect: '250000000000000000' }), [10000000000000000000n, 9000000000000000000n, 250000000000000000n]);
});
test('profile views attach counters from server cache and support user action', () => {
assert.match(file('../js/pages/profile-view.js'), /attachSupportStats\(body/);
const other = file('../js/pages/user-profile-view.js');
assert.match(other, /attachSupportStats\(body/);
assert.match(other, /data-profile-action=\\?"support/);
assert.match(other, /openShineSupportDialog\(\{ recipientLogin: card\.login/);
});
test('wallet offers SHiNE economy donation through the menu, not the Solana wallet', () => {
const wallet = file('../js/pages/wallet-view.js');
const menu = wallet.split('function renderWalletChoice()')[1].split('async function renderShineBlockchainWallet()')[0];
assert.match(menu, /openShineSupportDialog\(\)/);
assert.doesNotMatch(wallet, /id="donate-shine"/);
});
test('message buttons pass checked block hashes, not message text', () => {
for (const page of ['channel-view.js', 'channel-thread-view.js']) {
const src = file(`../js/pages/${page}`);
assert.match(src, /hexHash32\(rootHash\)/);
assert.match(src, /hexHash32\(msgHash\)|hexHash32\(messageHash\)/);
assert.match(src, /type: 2/);
}
});
test('shared modal requires Stars and oracle quote', () => {
const src = file('../js/components/shine-support-dialog.js');
assert.match(src, /supportShineUserOnSolana/);
assert.match(src, /supportShineDaoOnSolana/);
assert.match(src, /starCentsToLamports/);
assert.match(src, /getStarsQuoteFromRpc/);
assert.match(src, /parseStarCents/);
});
test('profile statistics use server API without Solana RPC', () => {
const component = file('../js/components/support-stats.js');
const auth = file('../js/services/auth-service.js');
assert.match(component, /authService\.getSupportStats\(login\)/);
assert.doesNotMatch(component, /readShineUserPda/);
assert.match(component, /if \(!stats\.ready\)/);
assert.match(auth, /this\.ws\.request\('GetSupportStats'/);
});
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
PALETTE_PRESETS, PALETTE_ROLES, resolvePalette,
} from '../js/services/theme-service.js';
const settings = (preset) => ({ preset, custom: { dark: {}, light: {} } });
test('новая палитра доступна в настройках, а стандартная сохранена', () => {
assert.equal(PALETTE_PRESETS.tg_midnight.label, 'TG · Midnight');
assert.equal(PALETTE_PRESETS.aurora.label, 'remaining.theme.shine'); // i18n ещё не инициализирован в Node
});
test('каждая роль в тёмном и светлом TG содержит корректный HEX', () => {
for (const mode of ['dark', 'light']) {
const result = resolvePalette(mode, settings('tg_midnight'));
for (const { id } of PALETTE_ROLES) {
assert.match(result[id], /^#[0-9a-f]{6}$/i, `${mode}/${id}`);
}
}
});
test('у тёмной темы синий акцент и отдельный цвет исходящего сообщения', () => {
const c = resolvePalette('dark', settings('tg_midnight'));
assert.equal(c.background, '#151e27');
assert.equal(c.accent, '#2596e8');
assert.equal(c['bubble-out'], '#456f69');
});
@@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const file = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
const ui = file('../js/pages/wallet-view.js');
const ru = JSON.parse(file('../js/i18n/locales/ru.json'));
const en = JSON.parse(file('../js/i18n/locales/en.json'));
for (const [locale, dict] of [['ru', ru], ['en', en]]) {
test(`${locale}: distinct menu descriptions for donations, obsolete storage and ticket flow`, () => {
const names = dict.screens.wallet_view;
assert.match(names.support_project_label, /SHiNE/i);
assert.ok(names.support_project_hint.length >= 20);
assert.match(names.text_122, locale === 'ru' ? /больше не используется/ : /no longer used/);
assert.notEqual(names.text_124, names.support_project_label);
assert.notEqual(names.text_189, names.support_project_label);
assert.ok(names.text_125);
});
}
test('menu opens existing DAO donation dialog without navigating to the Solana balance', () => {
const menu = ui.split('function renderWalletChoice()')[1].split('async function renderShineBlockchainWallet()')[0];
assert.match(menu, /support_project_label/);
assert.doesNotMatch(ui, /id="donate-shine"/, 'Solana wallet must not duplicate the donation button');
const order = ['renderSolanaWallet()', 'renderArweaveWallet()', 'renderTurboWallet()',
'openShineSupportDialog()', 'renderShineBlockchainWallet()', 'renderSupportHub()']
.map((entry) => menu.indexOf(entry));
assert.ok(order.every((position) => position >= 0));
assert.deepEqual(order, [...order].sort((a, b) => a - b));
assert.match(menu, /\(\) => openShineSupportDialog\(\)/);
assert.match(ui, /import \{ openShineSupportDialog \} from/);
assert.match(file('../js/components/shine-support-dialog.js'), /supportShineDaoOnSolana/);
});
@@ -0,0 +1,135 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import { readFileSync } from 'node:fs';
import { setSolanaCluster } from '../js/services/solana-rpc-gateway.js';
globalThis.window = { location: { pathname: '/wallet' } };
const { parseRouteFromPath, toPrettyPath } = await import('../js/router.js');
import { USDT_MAINNET_MINT, ASSOCIATED_TOKEN_PROGRAM_ID, associatedTokenAddress } from '../js/services/solana-usdt-service.js';
import {
WSOL_MINT, JUPITER_ROUTER_PROGRAM, swapPair, validateSwapInput,
validateSwapBuildResponse, validateSwapInstructions, SWAP_BETA_MAX_SOL_LAMPORTS,
SWAP_BETA_MAX_USDT_ATOMIC, requestSwapBuild,
} from '../js/services/jupiter-swap-service.js';
const code = (rel) => readFileSync(new URL(rel, import.meta.url), 'utf8');
const ctx = { Buffer, Uint8Array, TextEncoder, TextDecoder, console, setTimeout, crypto: globalThis.crypto };
vm.createContext(ctx);
vm.runInContext(code('../js/vendor/solana-web3.iife.min.js'), ctx);
const solana = ctx.solanaWeb3;
const wallet = solana.Keypair.generate().publicKey.toBase58();
const usdtAta = associatedTokenAddress(solana, wallet, USDT_MAINNET_MINT).toBase58();
const wsolAta = associatedTokenAddress(solana, wallet, WSOL_MINT).toBase58();
const fake = (inputCurrency = 'SOL', amount = 1000000n) => {
const pair = swapPair(inputCurrency);
return {
pair,
amount,
build: {
inputMint: pair.inputMint, outputMint: pair.outputMint, inAmount: amount.toString(),
outAmount: '5000000', otherAmountThreshold: '4975000',
swapMode: 'ExactIn', slippageBps: 50, transactionVersion: '0',
routePlan: [{ swapInfo: { label: 'test' }, percent: 100 }],
setupInstructions: [], cleanupInstruction: null, otherInstructions: [], computeBudgetInstructions: [],
tipInstruction: null, addressesByLookupTableAddress: {},
swapInstruction: { programId: JUPITER_ROUTER_PROGRAM,
accounts: [{ pubkey: wallet, isSigner: true, isWritable: true }], data: 'AA==' },
},
};
};
test('swap page wired from wallet, no external Jupiter wallet', () => {
assert.deepEqual(parseRouteFromPath('/wallet/swap'), { pageId: 'wallet-swap-view', params: {} });
assert.equal(toPrettyPath('wallet-swap-view'), 'wallet/swap');
assert.match(code('../js/pages/wallet-view.js'), /navigate\('wallet\/swap'\)/);
assert.match(code('../js/app.js'), /'wallet-swap-view': walletSwapView/);
const page = code('../js/pages/wallet-swap-view.js');
assert.match(page, /executeJupiterSwap/);
assert.match(page, /data-consent/);
assert.match(page, /window\.confirm/);
assert.doesNotMatch(page, /jup\.ag\/swap\/SOL/);
});
test('only Mainnet swaps allowed, with conservative small beta limits', async () => {
setSolanaCluster('devnet');
await assert.rejects(requestSwapBuild({ inputCurrency: 'SOL', amountAtomic: 1000000n, walletAddress: wallet }), /Mainnet/);
setSolanaCluster('mainnet-beta');
assert.equal(swapPair('SOL').outputMint, USDT_MAINNET_MINT);
assert.equal(swapPair('USDT').outputMint, WSOL_MINT);
assert.throws(() => swapPair('FAKE'), /SOL и USDT/);
assert.equal(SWAP_BETA_MAX_SOL_LAMPORTS, 20_000_000n);
assert.equal(SWAP_BETA_MAX_USDT_ATOMIC, 5_000_000n);
assert.throws(() => validateSwapInput('SOL', '0.020000001', { solLamports: 200_000_000n }), /Бета-лимит/);
assert.throws(() => validateSwapInput('USDT', '5.000001', { solLamports: 200_000_000n }), /Бета-лимит/);
assert.throws(() => validateSwapInput('USDT', '0.1', { solLamports: 0n }), /0,01 SOL/);
assert.equal(validateSwapInput('SOL', '0.01', { solLamports: 100_000_000n }).amount, 10_000_000n);
});
test('Jupiter response must match exact currency, input, slippage and expected minimum', () => {
const { pair, amount, build } = fake();
assert.equal(validateSwapBuildResponse(build, pair, amount).minimum, 4975000n);
assert.throws(() => validateSwapBuildResponse({ ...build, inAmount: '9999999' }, pair, amount), /неожиданные/);
assert.throws(() => validateSwapBuildResponse({ ...build, inputMint: USDT_MAINNET_MINT }, pair, amount), /неожиданные/);
assert.throws(() => validateSwapBuildResponse({ ...build, slippageBps: 150 }, pair, amount), /неожиданные/);
assert.throws(() => validateSwapBuildResponse({ ...build, otherAmountThreshold: '100000' }, pair, amount), /минимум/);
assert.throws(() => validateSwapBuildResponse({ ...build, tipInstruction: {} }, pair, amount), /Неподдерживаемый/);
});
test('only Jupiter router can swap; unsigned extra signer and malicious setup rejected', () => {
const { pair, amount, build } = fake();
assert.equal(validateSwapInstructions(build, pair, amount, wallet, solana).setupIxs.length, 0);
const attacker = solana.Keypair.generate().publicKey.toBase58();
assert.throws(() => validateSwapInstructions({ ...build, swapInstruction: { ...build.swapInstruction, programId: attacker } }, pair, amount, wallet, solana), /router/);
assert.throws(() => validateSwapInstructions({ ...build, swapInstruction: { ...build.swapInstruction,
accounts: [{ pubkey: attacker, isSigner: true, isWritable: true }] } }, pair, amount, wallet, solana), /неизвестного подписанта/);
const badSystem = { programId: '11111111111111111111111111111111', accounts: [
{ pubkey: wallet, isSigner: true, isWritable: true },
{ pubkey: attacker, isSigner: false, isWritable: true },
], data: Buffer.from([2,0,0,0,1,0,0,0,0,0,0,0]).toString('base64') };
assert.throws(() => validateSwapInstructions({ ...build, setupInstructions: [badSystem] }, pair, amount, wallet, solana), /Недопустимый системный перевод/);
});
test('canonical WSOL wrapping allowed up to input, not to arbitrary accounts', () => {
const { pair, amount, build } = fake('SOL', 1_000_000n);
const data = Buffer.alloc(12); data.writeUInt32LE(2, 0); data.writeBigUInt64LE(1_000_000n, 4);
const instruction = { programId: '11111111111111111111111111111111',
accounts: [{ pubkey: wallet, isSigner: true, isWritable: true }, { pubkey: wsolAta, isSigner: false, isWritable: true }],
data: data.toString('base64') };
assert.equal(validateSwapInstructions({ ...build, setupInstructions: [instruction] }, pair, amount, wallet, solana).setupIxs.length, 1);
const tooMuch = Buffer.alloc(12); tooMuch.writeUInt32LE(2, 0); tooMuch.writeBigUInt64LE(1_000_001n, 4);
assert.throws(() => validateSwapInstructions({ ...build, setupInstructions: [{ ...instruction, data: tooMuch.toString('base64') }] }, pair, amount, wallet, solana), /лишние SOL/);
const initAta = { programId: ASSOCIATED_TOKEN_PROGRAM_ID,
accounts: [
{ pubkey: wallet, isSigner: true, isWritable: true },
{ pubkey: usdtAta, isSigner: false, isWritable: true },
{ pubkey: wallet, isSigner: false, isWritable: false },
{ pubkey: USDT_MAINNET_MINT, isSigner: false, isWritable: false },
{ pubkey: '11111111111111111111111111111111', isSigner: false, isWritable: false },
{ pubkey: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', isSigner: false, isWritable: false },
], data: Buffer.from([1]).toString('base64') };
assert.equal(validateSwapInstructions({ ...build, setupInstructions: [initAta] }, pair, amount, wallet, solana).setupIxs.length, 1);
});
test('compiled Jupiter v0 route can be signed locally without external wallet', () => {
const keypair = solana.Keypair.generate();
const sender = keypair.publicKey.toBase58();
const sample = fake();
sample.build.swapInstruction.accounts = [{ pubkey: sender, isSigner: true, isWritable: true }];
const checked = validateSwapInstructions(sample.build, sample.pair, sample.amount, sender, solana);
const tx = new solana.VersionedTransaction(new solana.TransactionMessage({
payerKey: keypair.publicKey,
recentBlockhash: solana.Keypair.generate().publicKey.toBase58(),
instructions: [solana.ComputeBudgetProgram.setComputeUnitLimit({units: 200000}), checked.swapIx],
}).compileToV0Message());
tx.sign([keypair]);
assert.ok(tx.serialize().length > 100);
assert.equal(tx.signatures[0].length, 64);
});
test('i18n warnings clarify beta, risk and non-custodial key handling', () => {
for (const lang of ['ru', 'en']) {
const json = JSON.parse(code(`../js/i18n/locales/${lang}.json`));
assert.ok(json.wallet_swap.warning.length > 100);
assert.ok(json.wallet_swap.accept_risk.length > 30);
assert.ok(json.wallet_swap.wallet_button.includes('Jupiter'));
}
});
@@ -0,0 +1,102 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import { setSolanaCluster } from '../js/services/solana-rpc-gateway.js';
import {
USDT_MAINNET_MINT, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
getUsdtAsset, associatedTokenAddress, toAtomicAmount, formatAtomicAmount, encodeTransferChecked,
} from '../js/services/solana-usdt-service.js';
globalThis.window = { location: { pathname: '/wallet' } };
const { parseRouteFromPath, toPrettyPath } = await import('../js/router.js');
const code = (rel) => readFileSync(new URL(rel, import.meta.url), 'utf8');
const ctx = { Buffer, Uint8Array, TextEncoder, TextDecoder, console, setTimeout, crypto: globalThis.crypto };
vm.createContext(ctx);
vm.runInContext(code('../js/vendor/solana-web3.iife.min.js'), ctx);
const solana = ctx.solanaWeb3;
test('mainnet pins Tether official mint, devnet is explicitly separate', () => {
setSolanaCluster('mainnet-beta');
assert.deepEqual(getUsdtAsset(), { mint: USDT_MAINNET_MINT, label: 'USDT', test: false });
setSolanaCluster('devnet');
assert.equal(getUsdtAsset().test, true);
assert.equal(getUsdtAsset().mint, '');
});
test('atomic amount parsing avoids floating point rounding and enforces decimals', () => {
assert.equal(toAtomicAmount('0.000001'), 1n);
assert.equal(toAtomicAmount('0,75'), 750_000n);
assert.equal(toAtomicAmount('10.25'), 10_250_000n);
assert.equal(formatAtomicAmount(10_250_000n), '10.25');
assert.equal(toAtomicAmount('0.000000001', 9), 1n);
assert.throws(() => toAtomicAmount('0.0000001'), /6/);
assert.throws(() => toAtomicAmount('-1'), /сумму/);
assert.throws(() => toAtomicAmount('0'), /диапазона/);
assert.throws(() => toAtomicAmount('1e6'), /сумму/);
});
test('token ATA uses legacy Token Program, not Token-2022 or arbitrary mint', () => {
const owner = solana.Keypair.generate().publicKey.toBase58();
const mint = new solana.PublicKey(USDT_MAINNET_MINT);
const tokenProgram = new solana.PublicKey(TOKEN_PROGRAM_ID);
const associatedProgram = new solana.PublicKey(ASSOCIATED_TOKEN_PROGRAM_ID);
const actual = associatedTokenAddress(solana, owner, mint);
const expected = solana.PublicKey.findProgramAddressSync([
new solana.PublicKey(owner).toBytes(), tokenProgram.toBytes(), mint.toBytes(),
], associatedProgram)[0];
assert.equal(actual.toBase58(), expected.toBase58());
assert.equal(solana.PublicKey.isOnCurve(new solana.PublicKey(owner).toBytes()), true);
});
test('wallet transfer route preserves selected SHiNE login', () => {
globalThis.window = { location: { pathname: '/wallet/transfer/a%40example' } };
assert.deepEqual(parseRouteFromPath('/wallet/transfer/a%40example'), {
pageId: 'wallet-transfer-view', params: { recipientLogin: 'a@example' },
});
assert.equal(toPrettyPath('wallet-transfer-view'), 'wallet/transfer');
assert.deepEqual(parseRouteFromPath('/wallet'), { pageId: 'wallet-view', params: {} });
});
test('chat route has direct transfer action, wallet no longer prompts for address', () => {
const chat = code('../js/pages/chat-view.js');
const wallet = code('../js/pages/wallet-view.js');
const transfer = code('../js/pages/wallet-transfer-view.js');
assert.match(chat, /createOverflowDots\(\{ className: 'app-overflow-dots--vertical' \}\)/);
assert.match(chat, /navigate\(`wallet\/transfer\/\$\{encodeURIComponent\(chatId\)\}`\)/);
assert.match(wallet, /navigate\('wallet\/transfer'\)/);
assert.doesNotMatch(wallet, /window\.prompt\(t\('dialogs\.pages\.wallet_view\.prompt_002'/);
assert.match(transfer, /resolveContactBlockchainAddress/);
assert.match(transfer, /authService\.sendDirectMessage/);
assert.match(transfer, /transferUsdt/);
});
test('SPL TransferChecked instruction uses exact u64 little-endian amount and 6 decimals', () => {
const bytes = encodeTransferChecked(123_456_789n);
assert.equal(bytes.length, 10);
assert.equal(bytes[0], 12);
assert.equal(bytes[9], 6);
assert.equal(new DataView(bytes.buffer).getBigUint64(1, true), 123_456_789n);
});
test('chat transfer fixes recipient; wallet transfer has only free-address entry', () => {
const transfer = code('../js/pages/wallet-transfer-view.js');
assert.match(transfer, /const recipientLogin = recipientFromRoute;/);
assert.match(transfer, /q\('recipient'\)\.readOnly = true;/);
assert.match(transfer, /q\('notify-row'\)\.hidden = !recipientFromRoute;/);
assert.match(transfer, /if \(recipientLogin\) \{/);
assert.match(transfer, /toAddress = await resolveContactBlockchainAddress\(recipientLogin, endpoint\);/);
assert.doesNotMatch(transfer, /data-clear-contact|data-search|data-contacts|wallet-transfer-contact-picker|authService\.listContacts/);
});
test('chat transfer action is directly before destructive-actions divider', () => {
const chat = code('../js/pages/chat-view.js');
const menu = chat.slice(chat.indexOf("items: () => [", chat.indexOf('chat-header-menu-btn')));
const addToContacts = menu.indexOf("label: t('screens.chat_view.text_019')");
const transfer = menu.indexOf("label: t('wallet_multi.transfer_to_contact')");
const divider = menu.indexOf('{ divider: true }');
const clearHistory = menu.indexOf("label: t('screens.chat_view.text_020')");
assert.ok(addToContacts >= 0 && addToContacts < transfer && transfer < divider && divider < clearHistory);
assert.equal(menu.slice(0, divider).match(/wallet_multi\.transfer_to_contact/g)?.length, 1);
});