Разделить среды и закрепить лицензии в HEADER 1.0

This commit is contained in:
AidarKC
2026-12-05 11:42:20 +03:00
parent a64168a748
commit 77c7021aed
89 changed files with 4204 additions and 211 deletions
+5 -7
View File
@@ -64,7 +64,6 @@ import {
setContacts,
} from './state.js';
import { setSolanaCluster } from './services/solana-rpc-gateway.js';
import * as startView from './pages/start-view.js?v=20261104';
import * as entrySettingsView from './pages/entry-settings-view.js?v=202609260900';
@@ -730,7 +729,7 @@ async function notifyHiddenIncomingMessage(fromLogin, toLogin, unreadCount, mess
}
function ensureConnectionIndicatorEl() {
return document.getElementById('toolbar-connection-indicator');
return document.getElementById('toolbar-test-indicator');
}
function ensureConnectionRetryBannerEl() {
@@ -765,8 +764,7 @@ function refreshConnectionUi() {
const indicatorEl = ensureConnectionIndicatorEl();
if (indicatorEl) {
indicatorEl.classList.remove('is-connected', 'is-disconnected', 'is-connecting', 'is-updating', 'is-unknown');
indicatorEl.classList.add(`is-${state || 'unknown'}`);
indicatorEl.hidden = authService.serverEnvironment?.testMode !== true;
}
const bannerEl = ensureConnectionRetryBannerEl();
@@ -1134,6 +1132,7 @@ async function checkConnectionHealth() {
return;
}
}
if (authService.environmentGeneration !== authService.ws.connectionGeneration || !authService.serverEnvironment) await authService.getServerEnvironment();
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
const remoteUiBuildHash = pingResp?.payload?.uiBuildHash || pingResp?.uiBuildHash || '';
void checkAndReloadIfUiUpdated(remoteUiBuildHash);
@@ -2090,8 +2089,7 @@ async function init() {
// Public server info: one UI build for both devnet and mainnet.
try {
await authService.reconnect(state.entrySettings.shineServer);
const info = await authService.ws.request('GetServerInfo', {}, 9000);
setSolanaCluster(info?.payload?.solanaCluster ?? info?.solanaCluster);
await authService.getServerEnvironment();
} catch (error) {
console.warn('Failed to read SHiNE Solana cluster', error);
}
@@ -2142,7 +2140,7 @@ const SESSION_HANDSHAKE_OPS = new Set([
]);
authService.ws.setRequestGuard(async (op) => {
if (op === 'ClientErrorLog' || SESSION_HANDSHAKE_OPS.has(op)) return;
if (op === 'ClientErrorLog' || op === 'GetServerInfo' || SESSION_HANDSHAKE_OPS.has(op)) return;
if (!state.session.isAuthorized || authService.ws.isSessionReady()) return;
await ensureSessionAfterWsReconnect();
});
+4 -3
View File
@@ -70,6 +70,9 @@ function applyCountersToMountedToolbars() {
});
}
if (typeof window !== 'undefined') window.addEventListener('shine:server-environment', () => {
document.querySelectorAll('.toolbar-test-indicator').forEach(el => { el.hidden = state.serverEnvironment?.testMode !== true; });
});
let countersPushBound = false;
function ensureCountersPushBound() {
if (countersPushBound) return;
@@ -138,9 +141,7 @@ export function renderToolbar(currentPageId, navigate) {
btn.className = `toolbar-btn${item.pageId === active ? ' active' : ''}${isProfile ? ' toolbar-btn-profile' : ''}${isMessages ? ' toolbar-btn-messages' : ''}${isNetwork ? ' toolbar-btn-network' : ''}${item.hero ? ' toolbar-btn-hero' : ''}`;
if (isProfile) {
btn.innerHTML = `
${iconHtml(item, `<span id="toolbar-connection-indicator" class="toolbar-connection-indicator is-unknown">
<span class="toolbar-connection-dot" aria-hidden="true"></span>
</span>`)}
${iconHtml(item, `<span id="toolbar-test-indicator" class="toolbar-test-indicator"${state.serverEnvironment?.testMode === true ? '' : ' hidden'}>Test</span>`)}
<span class="sr-only">${item.label}</span>
`;
} else if (isNetwork) {
+2
View File
@@ -167,6 +167,7 @@
"confirm_001": "If you have already added funds to this wallet, do not change your username or password: doing so changes its address. Return to the password step?"
},
"server_settings_view": {
"test_mode": "Test server",
"alert_001": "Text for developers: A server account login is entered for SHiNE. The client reads its PDA, takes server address, shows the exact https address and checks the availability of the WS channel automatically."
},
"wallet_view": {
@@ -1809,6 +1810,7 @@
"text_199": "reader"
},
"server_settings_view": {
"test_mode": "Test server",
"text_001": "Blockchain Servers",
"text_002": "Server Solana Address",
"text_003": "SHiNE server-PDA login",
+2
View File
@@ -162,6 +162,7 @@
"confirm_001": "Если вы уже пополнили этот кошелёк, не меняйте логин и пароль: это изменит адрес кошелька. Вернуться к паролю?"
},
"server_settings_view": {
"test_mode": "Тестовый сервер",
"alert_001": "Текст для разработчиков: для Сияния вводится логин серверного аккаунта. Клиент читает его PDA, берёт server_address, показывает точный https-адрес и проверяет доступность WS-канала автоматически."
},
"settings_view": {
@@ -1809,6 +1810,7 @@
"text_210": "сияющий"
},
"server_settings_view": {
"test_mode": "Тестовый сервер",
"text_001": "Серверы блокчейнов",
"text_002": "Адрес Solana сервера",
"text_003": "Логин server-PDA Сияния",
@@ -37,6 +37,15 @@ export function render({navigate, chrome}) {
const body = document.createElement('div');
body.className = 'card stack';
const testModeLabel = document.createElement('label');
testModeLabel.className = 'row field-label';
const testModeCheckbox = document.createElement('input');
testModeCheckbox.type = 'checkbox';
testModeCheckbox.disabled = true;
testModeCheckbox.checked = state.serverEnvironment?.testMode === true;
testModeCheckbox.indeterminate = state.serverEnvironment == null;
testModeLabel.append(testModeCheckbox, document.createTextNode(t('screens.server_settings_view.test_mode')));
body.append(testModeLabel);
SERVER_FIELDS.forEach((field) => {
const block = document.createElement('div');
+36 -6
View File
@@ -1,6 +1,7 @@
import { dmPreviewLockName } from './dm-preview-settings.js';
import { buildAvatarReference } from './avatar-reference.js';
import { WsJsonClient } from './ws-client.js';
import { parseServerEnvironment } from './server-environment.js';
import { invalidateConnectionsGraphCache } from './connections-graph-cache.js';
import {
base64ToBytes,
@@ -544,10 +545,10 @@ function extractContactsFromDialogs(dialogs) {
return out;
}
export const HEADER_VERSION = 2;
export const HEADER_DEFAULT_LICENSE = 'CC0-1.0';
export const HEADER_VERSION = 1;
export const HEADER_DEFAULT_LICENSE = 'licenses:CC-BY-NC-4.0/sha256:41003d4a74749c0220e33dd415042164b5a1093ed401f36277234f772d22d3d0/arweave:Xtym3vUAyt7OgFBINBh1ene-5360Ah76c6D-O9ywxVE;SCDL-1.0/sha256:696454cb26c7ecb9e8b66812996b37733dc532307a3584718edd442b291870af/arweave:NPckIo-nQUP2-ZM6PIoDYnx-6wwLeErH39jXCddOxPE';
function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = 'CC0-1.0', accountType = 1, previousAccounts = [] }) {
function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = HEADER_DEFAULT_LICENSE, accountType = 1, previousAccounts = [] }) {
const cleanLogin = String(login || '').trim();
const loginBytes = utf8Bytes(cleanLogin);
const licenseBytes = utf8Bytes(license);
@@ -961,10 +962,35 @@ export class AuthService {
});
}
async getServerEnvironment() {
const ws = this.ws;
let generation;
let environment;
try {
await ws.open();
generation = ws.connectionGeneration;
const response = await ws.request('GetServerInfo', {}, 9000);
if (this.ws !== ws || ws.connectionGeneration !== generation || !ws.ws) throw new Error('Server connection changed');
environment = parseServerEnvironment(response);
} catch (error) {
if (this.ws === ws && (generation == null || ws.connectionGeneration === generation)) {
this.serverEnvironment = null; this.environmentGeneration = null; this.onEnvironmentChange?.(null);
}
throw error;
}
this.serverEnvironment = environment;
this.environmentGeneration = generation;
this.onEnvironmentChange?.(environment);
return environment;
}
resetConnection(serverUrl = this.serverUrl, { clearSessionContext = true } = {}) {
const normalized = normalizeServerUrl(serverUrl);
const requestGuard = this.ws?.requestGuard;
try { this.ws?.close(); } catch {}
try { if (this.ws) this.ws.retired = true; this.ws?.close(); } catch {}
this.serverEnvironment = null;
this.environmentGeneration = null;
this.onEnvironmentChange?.(null);
this.serverUrl = normalized;
this.ws = new WsJsonClient(this.serverUrl);
this.ws.setRequestGuard(requestGuard);
@@ -1667,14 +1693,18 @@ export class AuthService {
}
async submitPreparedAddBlock({ login, storagePwd, blockchainName, blockNumber, prevBlockHash, event }) {
const ws = this.ws;
const { arweaveAppTag } = await this.getServerEnvironment();
const generation = ws.connectionGeneration;
const savedKeys = await loadEncryptedUserSecrets(login, storagePwd);
const pkcs8 = String(savedKeys?.blockchainKey || '').trim();
if (!pkcs8) throw new Error('Blockchain key unavailable for local signing');
const privateKey = await importPkcs8Ed25519(pkcs8);
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(pkcs8));
const signed = await signEventContainer({ ...event, owner32, privateKey, blockNumber,
const signed = await signEventContainer({ ...event, owner32, privateKey, blockNumber, arweaveAppTag,
prevBlockHash, timestamp: Math.floor(Date.now() / 1000) });
return submitSignedEvent(this.ws, { blockchainName, blockNumber, prevBlockHash }, signed);
if (this.ws !== ws || ws.connectionGeneration !== generation || !ws.ws) throw new Error('Server connection changed');
return submitSignedEvent(ws, { blockchainName, blockNumber, prevBlockHash }, signed);
}
async submitRemoteAddBlockBody({ login, storagePwd, blockchainName, blockBodyBytes }) {
@@ -1,5 +1,7 @@
import { base64ToBytes } from './crypto-utils.js';
import { unpackCoreContent } from './core-content.js';
import { unpackCoreContent, verifyCoreContentPair } from './core-content.js';
import { parseAns104DataItem } from './ans104-data-item.js';
import { parseServerEnvironment } from './server-environment.js';
import { uploadSignedBlockDataItem } from './turbo-upload-service.js';
import { showToast } from './channels-ux.js';
import { t } from '../i18n/index.js';
@@ -10,10 +12,14 @@ const lastNotice = new Map();
/** После перезапуска браузер повторно получает подписанные bytes с сервера. */
export async function publishPendingBlocks({ ws, login, storagePwd, blockchainName }) {
if (!ws || !login || !storagePwd || !blockchainName || running.has(blockchainName)) return;
running.add(blockchainName);
if (!ws || ws.retired || !login || !storagePwd || !blockchainName) return;
const key = `${ws.url}|${blockchainName}`;
if (running.has(key)) return;
running.add(key);
let keepPolling = false;
try {
const env = parseServerEnvironment(await ws.request('GetServerInfo', {}, 9000));
const generation = ws.connectionGeneration;
const response = await ws.request('BlockPublication', { action: 'list', blockchainName });
if (response.status !== 200) return;
keepPolling = true;
@@ -23,14 +29,17 @@ export async function publishPendingBlocks({ ws, login, storagePwd, blockchainNa
throw new Error('Pending block bytes unavailable or changed');
}
const { contentDataItem, coreDataItem } = unpackCoreContent(base64ToBytes(read.payload.blockBytesB64));
await verifyCoreContentPair(coreDataItem, contentDataItem, parseAns104DataItem(coreDataItem).owner32, env.arweaveAppTag);
if (ws.retired || ws.connectionGeneration !== generation) return;
let uploadError = '';
try {
if (!block.contentConfirmed) await uploadSignedBlockDataItem({ login, storagePwd, bytes: contentDataItem, expectedId: block.contentId });
if (ws.retired || ws.connectionGeneration !== generation) return;
if (!block.coreConfirmed) await uploadSignedBlockDataItem({ login, storagePwd, bytes: coreDataItem, expectedId: block.coreId });
} catch (error) {
uploadError = String(error?.message || error);
const insufficientCredits = /(?:\b402\b|insufficient (?:balance|funds|credits)|not enough (?:balance|funds|credits)|payment required|недостаточно (?:средств|кредитов))/i.test(uploadError);
const noticeKey = `${blockchainName}:${block.blockNumber}`;
const noticeKey = `${key}:${block.blockNumber}`;
if (Date.now() - (lastNotice.get(noticeKey) || 0) >= 30 * 60_000) {
showToast(t(insufficientCredits ? 'block_publication.insufficient_credits' : 'block_publication.upload_failed',
{ number: block.blockNumber }), { kind: 'error', timeoutMs: 7000 });
@@ -47,13 +56,13 @@ export async function publishPendingBlocks({ ws, login, storagePwd, blockchainNa
} catch (error) {
console.warn('Block publication queue unavailable', error);
} finally {
running.delete(blockchainName);
if (keepPolling && !scheduled.has(blockchainName)) {
running.delete(key);
if (!ws.retired && keepPolling && !scheduled.has(key)) {
const timer = globalThis.setTimeout(() => {
scheduled.delete(blockchainName);
scheduled.delete(key);
void publishPendingBlocks({ ws, login, storagePwd, blockchainName });
}, 30_000);
scheduled.set(blockchainName, timer);
scheduled.set(key, timer);
}
}
}
@@ -137,7 +137,7 @@ function parseTechBody(subType, body, frame) {
seen.add(previous.toLowerCase());
}
}
const license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(frame.version === 2 ? reader.u16('HEADER license length') : reader.u8('HEADER license length'), 'HEADER license'));
const license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u16('HEADER license length'), 'HEADER license'));
const initialBlockchainKey = bytesToBase64Url(reader.raw(32, 'initialBlockchainKey32'));
if (reader.remaining() !== 0) throw new Error('Неожиданные данные после HEADER');
return { kind: 'header', magic, login, license, accountType, previousAccounts, initialBlockchainKey };
@@ -247,7 +247,7 @@ function parseStatusBody(subType, body) {
}
function parseBody(type, subType, version, body, frame) {
if (version !== 1 && !(type === 0 && subType === 0 && version === 2)) {
if (version !== 1) {
return { kind: 'unsupported_version', rawBodyLength: body.length };
}
if (type === 0) return parseTechBody(subType, body, frame);
+14 -10
View File
@@ -1,7 +1,7 @@
// CORE v2 / CONTENT v1. Uses the existing ANS-104 signer; no new key store or transport.
import { bytesToBase64, base64ToBytes } from './crypto-utils.js';
import { createAns104DataItem, parseAns104DataItem, verifyAns104DataItem, serializeAns104Tags } from './ans104-data-item.js';
import { SHINE_CORE_NAMESPACE, SHINE_CORE_MAX_BLOCK_NUMBER, SHINE_CORE_LINE_PROFILE,
import { SHINE_CORE_NAMESPACE, SHINE_TEST_CORE_NAMESPACE, isArweaveAppTag, SHINE_CORE_MAX_BLOCK_NUMBER, SHINE_CORE_LINE_PROFILE,
SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from './protocol-tags.js';
export const CORE_MAX_ITEM_BYTES = 8 * 1024 * 1024;
@@ -67,8 +67,9 @@ export function decodeCore(bytes) {
encodeCore(result); // identical structural validation on read and write
return result;
}
export function coreTags(core) {
const tags = [{ name: 'App', value: SHINE_CORE_NAMESPACE }, { name: 'n', value: String(core.blockNumber) }];
export function coreTags(core, arweaveAppTag) {
if (!isArweaveAppTag(arweaveAppTag)) throw new Error('Server environment unavailable');
const tags = [{ name: 'App', value: arweaveAppTag }, { name: 'n', value: String(core.blockNumber) }];
if (core.line) {
const code = core.line.lineCode;
const special = { [SHINE_CORE_LINE_PROFILE]: 'P', [SHINE_CORE_LINE_CONNECTION]: 'C', [SHINE_CORE_LINE_TECH]: 'T' };
@@ -80,7 +81,7 @@ export function coreTags(core) {
function checkEventLine(content, core) {
const { type, subType, version } = content;
const header = type === 0 && subType === 0;
if (version !== 1 && !(header && version === 2)) throw new Error('Unsupported CONTENT version for creation');
if (version !== 1) throw new Error('Unsupported CONTENT version for creation');
if (header !== (core.blockNumber === 0)) throw new Error('HEADER must be CORE #0');
const code = core.line?.lineCode;
if (type === 0 && !header) { if (code !== SHINE_CORE_LINE_TECH) throw new Error('Wrong TECH line'); }
@@ -107,7 +108,8 @@ export function splitEventBody({ msgType, msgSubType, msgVersion = 1, bodyBytes
}
return { content: { type: msgType, subType: msgSubType, version: msgVersion, body: bodyBytes.slice(prefix) }, line };
}
export async function signCoreContentPair({ owner32, privateKey, content, prevCoreHash32, blockNumber, timestamp, line = null }) {
export async function signCoreContentPair({ owner32, privateKey, content, prevCoreHash32, blockNumber, timestamp, line = null, arweaveAppTag }) {
if (!isArweaveAppTag(arweaveAppTag)) throw new Error('Server environment unavailable');
bytes32(owner32);
checkEventLine(content, { blockNumber, line });
const contentBytes = encodeContent(content);
@@ -117,18 +119,20 @@ export async function signCoreContentPair({ owner32, privateKey, content, prevCo
const contentDataItemId32 = await sha256(parseAns104DataItem(contentDataItem).signature);
const core = { prevCoreHash32, blockNumber, timestamp, contentHash32, contentDataItemId32, line };
const coreBytes = encodeCore(core);
const coreDataItem = await createAns104DataItem({ owner32, privateKey, data: coreBytes, tags: coreTags(core) });
const coreDataItem = await createAns104DataItem({ owner32, privateKey, data: coreBytes, tags: coreTags(core, arweaveAppTag) });
return { coreBytes, contentBytes, coreDataItem, contentDataItem, coreHash32: await sha256(coreBytes), contentHash32, contentDataItemId32 };
}
/** Verifies signed pair and owner binding, not history, semantics or authorization of the owner. */
export async function verifyCoreContentPair(coreItem, contentItem, expectedOwner32) {
export async function verifyCoreContentPair(coreItem, contentItem, expectedOwner32, arweaveAppTag = null) {
bytes32(expectedOwner32);
for (const item of [coreItem, contentItem]) if (!(item instanceof Uint8Array) || item.length > CORE_MAX_ITEM_BYTES) throw new Error('Invalid ANS-104 size');
const [c, p] = await Promise.all([verifyAns104DataItem(coreItem), verifyAns104DataItem(contentItem)]);
if (!c.signatureValid || !p.signatureValid || !equal(c.owner32, expectedOwner32) || !equal(p.owner32, expectedOwner32)) throw new Error('Invalid pair signature or owner');
const core = decodeCore(c.data), content = decodeContent(p.data);
// This is the canonical encoding produced by the UI. General Arweave import validation is D.
if (c.target.length || c.anchor.length || p.target.length || p.anchor.length || c.tagsCount !== coreTags(core).length || p.tagsCount !== 0 || !(equal(c.rawTags, serializeAns104Tags(coreTags(core))) || equal(c.rawTags, serializeAns104Tags(coreTags(core).map(t => t.name === 'App' ? { ...t, value: 'test5599' } : t)))) || !equal(p.rawTags, serializeAns104Tags([]))) throw new Error('Invalid pair tags');
// Offline proofs may identify either current network; server-bound callers can require one.
const allowedApps = arweaveAppTag == null ? [SHINE_CORE_NAMESPACE, SHINE_TEST_CORE_NAMESPACE] : [arweaveAppTag];
if (c.target.length || c.anchor.length || p.target.length || p.anchor.length || p.tagsCount !== 0 || !allowedApps.some(app => equal(c.rawTags, serializeAns104Tags(coreTags(core, app)))) || !equal(p.rawTags, serializeAns104Tags([]))) throw new Error('Invalid pair tags');
if (!equal(core.contentHash32, p.frameHashBytes) || !equal(core.contentDataItemId32, p.dataItemIdBytes)) throw new Error('CONTENT does not match CORE');
return { core, content, coreHash32: c.frameHashBytes, coreDataItemId32: c.dataItemIdBytes };
}
@@ -155,9 +159,9 @@ export function unpackCoreContent(bytes) {
}
/** Adapter from existing semantic body factories to the wire format. */
export async function signEventContainer({ owner32, privateKey, blockNumber, prevBlockHash, timestamp, ...event }) {
export async function signEventContainer({ owner32, privateKey, blockNumber, prevBlockHash, timestamp, arweaveAppTag, ...event }) {
const { content, line } = splitEventBody(event);
const pair = await signCoreContentPair({ owner32, privateKey, blockNumber, prevCoreHash32: coreHashBytes(prevBlockHash), timestamp, content, line });
const pair = await signCoreContentPair({ owner32, privateKey, blockNumber, prevCoreHash32: coreHashBytes(prevBlockHash), timestamp, content, line, arweaveAppTag });
return { bytes: packCoreContent(pair.coreDataItem, pair.contentDataItem), hash: coreHex(pair.coreHash32) };
}
+5 -1
View File
@@ -104,11 +104,15 @@ export class KeyRotationClient {
});
const techTimestampMs=Number(rotation.createdAtMs)||timestampMs(tipParsed)+1000;
const techBlockNumber=cutoff+1;
const pair=await signCoreContentPair({owner32,privateKey,blockNumber:techBlockNumber,
const ws = this.auth.ws;
const { arweaveAppTag } = await this.auth.getServerEnvironment();
const generation = ws.connectionGeneration;
const pair=await signCoreContentPair({owner32,privateKey,arweaveAppTag,blockNumber:techBlockNumber,
timestamp:Math.floor(techTimestampMs/1000),prevCoreHash32:hexToBytes(rotation.forkFromHash),
content:{type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody},
line:{lineCode:SHINE_CORE_LINE_TECH,prevLineBlockNumber:techTail.prevLineNumber,prevLineCoreHash32:hexToBytes(techTail.prevLineHash)}});
const techRaw=packCoreContent(pair.coreDataItem,pair.contentDataItem);
if (this.auth.ws !== ws || ws.connectionGeneration !== generation || !ws.ws) throw new Error('Server connection changed');
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,blockBytesB64:bytesToBase64(techRaw)});
onProgress({phase:'copy',current:1,total:1});
}
+2
View File
@@ -8,6 +8,8 @@ export const SHINE_TYPE_TAG_NAME = 't';
// Активная эпоха CORE/CONTENT.
export const SHINE_CORE_NAMESPACE = 'SHiNE';
export const SHINE_TEST_CORE_NAMESPACE = 'test5570';
export function isArweaveAppTag(value) { return value === SHINE_CORE_NAMESPACE || value === SHINE_TEST_CORE_NAMESPACE; }
export const SHINE_CORE_NUMBER_TAG_NAME = 'n';
export const SHINE_CORE_LINE_TAG_NAME = 'l';
export const SHINE_CORE_LINE_PROFILE = 2147483645;
@@ -0,0 +1,15 @@
import { SHINE_CORE_NAMESPACE, SHINE_TEST_CORE_NAMESPACE } from './protocol-tags.js';
// Никаких предположений о production при отсутствии ответа сервера.
export function parseServerEnvironment(response) {
const p = response?.payload ?? response;
if (response?.status !== 200 || typeof p?.testMode !== 'boolean') throw new Error('Server environment unavailable');
const tag = p.testMode ? SHINE_TEST_CORE_NAMESPACE : SHINE_CORE_NAMESPACE;
const cluster = p.testMode ? 'devnet' : 'mainnet-beta';
if (p.arweaveAppTag !== tag || p.solanaCluster !== cluster) throw new Error('Inconsistent server environment');
return Object.freeze({ testMode: p.testMode, arweaveAppTag: tag, solanaCluster: cluster });
}
let storageEnvironment = null;
export function setStorageEnvironment(environment) { storageEnvironment = environment?.arweaveAppTag ?? null; }
export function getStorageEnvironment() { return storageEnvironment ?? "unconfirmed"; }
@@ -1,3 +1,4 @@
import { getStorageEnvironment } from "./server-environment.js";
import { unpackCoreContent } from './core-content.js';
import { t } from '../i18n/index.js';
const SNAPSHOT_STORAGE_KEY = 'shine-ui-blockchain-snapshot-v1';
@@ -7,7 +8,7 @@ function normalizeLogin(login) {
}
function storageBucketKey(login) {
return normalizeLogin(login) || 'anonymous';
return `${getStorageEnvironment()}|${normalizeLogin(login) || "anonymous"}`;
}
function decodeBase64ToBytes(base64) {
@@ -3,6 +3,7 @@ export const DEVNET_FAUCET_RPC = 'https://api.devnet.solana.com';
let cluster = '';
export function setSolanaCluster(value) {
const next = String(value || '').toLowerCase();
if (!next) { cluster = ''; return; }
if (next !== 'devnet' && next !== 'mainnet-beta' && next !== 'testnet') throw new Error(`Unsupported server Solana cluster: ${value}`);
cluster = next;
}
+3 -1
View File
@@ -83,6 +83,7 @@ export class WsJsonClient {
}
async open() {
if (this.retired) throw new Error('Server connection retired');
if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
if (this.openPromise) return this.openPromise;
if (isMixedContentWs(this.url)) {
@@ -102,6 +103,7 @@ export class WsJsonClient {
this.connectionGeneration += 1;
ws.addEventListener('open', () => {
if (this.retired) { ws.close(); reject(new Error('Server connection retired')); return; }
resolve();
}, { once: true });
@@ -138,7 +140,7 @@ export class WsJsonClient {
if (this.requestGuard) await this.requestGuard(op);
if (this.ws && this.ws.readyState === WebSocket.OPEN) break;
}
if (!this.ws || this.ws.readyState !== WebSocket.OPEN || (existingOnly && !this.isSessionReady())) {
if (this.retired || !this.ws || this.ws.readyState !== WebSocket.OPEN || (existingOnly && !this.isSessionReady())) {
throw new Error(t('remaining.websocket.websocket_connection_closed'));
}
const requestId = createRequestId(op);
+9 -2
View File
@@ -1,3 +1,4 @@
import { setStorageEnvironment } from "./services/server-environment.js";
import { setDmPreviewSession } from './services/dm-preview-settings.js';
import { AuthService } from './services/auth-service.js';
import { getLanguage, setLanguage } from './i18n/index.js';
@@ -517,6 +518,13 @@ function createInitialState({ withStoredSession = true } = {}) {
export const state = createInitialState();
export const authService = new AuthService(state.entrySettings.shineServer);
state.serverEnvironment = null;
authService.onEnvironmentChange = (environment) => {
state.serverEnvironment = environment;
setStorageEnvironment(environment);
setSolanaCluster(environment?.solanaCluster ?? '');
window.dispatchEvent(new Event('shine:server-environment'));
};
authService.setRemoteAddBlockSessionId(state.entrySettings.remoteAddBlockSessionId);
authService.setActiveSessionContext({
login: state.session.login,
@@ -1105,8 +1113,7 @@ export async function saveEntrySettings(nextSettings) {
authService.setRemoteAddBlockSessionId(state.entrySettings.remoteAddBlockSessionId);
await authService.reconnect(state.entrySettings.shineServer);
try {
const info = await authService.ws.request('GetServerInfo', {}, 9000);
setSolanaCluster(info?.payload?.solanaCluster ?? info?.solanaCluster);
await authService.getServerEnvironment();
} catch (error) {
console.warn('Unable to refresh Solana network from the selected server', error);
}
@@ -1099,7 +1099,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
const BLOCK_TYPE_ARCHIVE_HEAD = 80;
const CORE_MAX_NUMBER = 2147482623;
// Transport namespace актуального standalone Viewer.
const SHINE_PROTOCOL_NAMESPACE = 'SHiNE';
const SHINE_PROTOCOL_NAMESPACE = new URLSearchParams(location.search).get('network') === 'test' ? 'test5570' : 'SHiNE';
const SHINE_ARWEAVE_APP_TAG = SHINE_PROTOCOL_NAMESPACE;
const SHINE_ARWEAVE_CHANNEL_TAG = 'c';
const BCH_TYPE_TECH = 0;
@@ -1950,7 +1950,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
seen.add(previous.toLowerCase());
}
}
const license = strict(reader.readBytes(version === 2 ? reader.readU16() : reader.readU8()));
const license = strict(reader.readBytes(reader.readU16()));
const initialBlockchainKey = base64Url(reader.readBytes(32));
reader.ensureDone();
return { kind: 'header', login, tag, initialBlockchainKey, accountType, previousAccounts, license };
@@ -2040,7 +2040,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
}
function parseBlockchainBody(type, subType, version, bodyBytes, line) {
if (version !== 1 && !(type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER && version === 2)) {
if (version !== 1) {
return { kind: 'unsupported', reason: `Неподдерживаемая версия body ${version}` };
}
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER) {
@@ -2095,7 +2095,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
const tags=node.tags||[];
const expected={App:SHINE_PROTOCOL_NAMESPACE,n:String(core.blockNumber)};
if(core.line) expected.l=({2147483645:'P',2147483646:'C',2147483647:'T'})[core.line.lineCode]??String(core.line.lineCode);
if(tags.length!==Object.keys(expected).length || Object.entries(expected).some(([name,value])=>tags.filter(t=>t.name===name&&(t.value===value || (name==='App' && t.value==='test5599'))).length!==1)) throw new Error('CORE index tags mismatch');
if(tags.length!==Object.keys(expected).length || Object.entries(expected).some(([name,value])=>tags.filter(t=>t.name===name&&t.value===value).length!==1)) throw new Error('CORE index tags mismatch');
}
function refKey(blockchainName, blockNumber, blockHashHex) {
@@ -2437,7 +2437,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
const gateway = baseUrl(gatewayBaseUrl);
const ownerAddress = await arweaveOwnerAddressFromBlockchainKey(blockchainKey);
// Author-first: channel is a local view filter, never an Arweave query filter.
const tags = [{ name: 'App', values: [SHINE_ARWEAVE_APP_TAG, 'test5599'] }];
const tags = [{ name: 'App', values: [SHINE_ARWEAVE_APP_TAG] }];
const query = `query($owners:[String!],$tags:[TagFilter!],$after:String){transactions(first:100,after:$after,owners:$owners,tags:$tags,sort:HEIGHT_DESC){pageInfo{hasNextPage}edges{cursor node{id owner{address key} block{height timestamp} bundledIn{id} tags{name value}}}}}`;
let after = null;
let page = 0;
@@ -3354,7 +3354,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
function v3RenderBlocks(){ const host=document.getElementById('v3-block-view'); if(!host)return; host.innerHTML=''; const wrap=document.createElement('div'); wrap.className='v3-blocks'; const blocks=(currentBlockchainView?.rawBlocks||V3.blocks||[]).slice().sort((a,b)=>b.blockNumber-a.blockNumber); blocks.forEach(b=>{ const d=document.createElement('details'); d.className='v3-block'; const sm=document.createElement('summary'); sm.textContent=`#${b.blockNumber} · type ${b.type}/${b.subType} · ${formatTimestamp(Number(b.timestampSec)*1000)}`; const pre=document.createElement('pre'); pre.textContent=JSON.stringify({blockNumber:b.blockNumber,type:b.type,subType:b.subType,version:b.version,hash:b.hashHex,prevHash:b.prevHashHex,contentHash:b.contentHashHex,contentDataItemId:b.contentDataItemId,line:b.line,arweaveId:b.arweaveId,body:b.body},(k,v)=>typeof v==='bigint'?String(v):v,2); d.append(sm,pre); wrap.appendChild(d); }); if(!blocks.length)wrap.textContent='Блоки ещё не загружены.'; host.appendChild(wrap); }
function v3SetView(mode){ const bv=document.getElementById('v3-block-view'), cb=document.getElementById('content-browser'); document.getElementById('v3-channel-tab').classList.toggle('is-active',mode==='channel'); document.getElementById('v3-blocks-tab').classList.toggle('is-active',mode==='blocks'); if(bv)bv.hidden=mode!=='blocks'; if(cb)cb.hidden=mode==='blocks'; if(mode==='blocks')v3RenderBlocks(); }
async function v3ClearCache(){ try{ const keys=Object.keys(localStorage).filter(k=>k.startsWith('shine.viewer.data.')||k.startsWith('shine.viewer.author-chain.')); keys.forEach(k=>localStorage.removeItem(k)); if('caches' in window){ for(const k of await caches.keys()) if(k.startsWith('shine-viewer-')) await caches.delete(k); } v3Log('Кэш данных очищен'); }catch(e){v3Log('Ошибка очистки кэша: '+e.message);} }
function v3CacheKey(key,channel){return 'shine.viewer.author-chain.test5599.'+String(key);}
function v3CacheKey(key,channel){return 'shine.viewer.author-chain.'+SHINE_ARWEAVE_APP_TAG+'.'+String(key);}
function v3SaveCache(key,channel,blocks){ if(!V3.cacheEnabled)return; try{ localStorage.setItem(v3CacheKey(key,channel),JSON.stringify(blocks,(k,v)=>typeof v==='bigint'?{__bigint:String(v)}:v)); }catch(e){v3Log('Кэш переполнен: '+e.message);} }
function v3LoadCache(key,channel){ if(!V3.cacheEnabled)return null; try{return JSON.parse(localStorage.getItem(v3CacheKey(key,channel))||'null',(k,v)=>v&&typeof v==='object'&&v.__bigint!==undefined?BigInt(v.__bigint):v);}catch{return null;} }
async function v3RestoreCached(key, channel) {
+2 -4
View File
@@ -14,10 +14,8 @@
.toolbar-mandala { display: block; width: 38px; height: 38px; object-fit: contain; transition: transform var(--duration-fast) ease; }
.toolbar-btn.active .toolbar-mandala { transform: scale(1.06); }
.toolbar-icon .toolbar-connection-indicator { position: absolute; right: 8px; bottom: 0; display: block; }
.toolbar-connection-dot { display: block; width: 9px; height: 9px; border-radius: 50%; background: var(--text-secondary); box-shadow: 0 0 0 2px var(--background); }
.toolbar-connection-indicator.is-connected .toolbar-connection-dot { background: var(--success); }
.toolbar-connection-indicator.is-disconnected .toolbar-connection-dot { background: var(--danger); }
.toolbar-icon .toolbar-test-indicator { position: absolute; right: 0; bottom: -2px; color: var(--warning, #d97706); background: var(--background); font-size: 10px; font-weight: 700; line-height: 12px; padding: 0 2px; border-radius: 3px; }
.toolbar-test-indicator[hidden] { display: none; }
.toolbar-unread-badge { position: absolute; top: -5px; right: 2px; min-width: 18px; padding: 0 5px; border-radius: 12px; color: var(--on-accent); background: var(--accent); box-shadow: 0 0 0 2px var(--background); font-size: .6875rem; font-weight: 600; line-height: 18px; text-align: center; }
+21 -17
View File
@@ -1,21 +1,25 @@
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('CORE эпоха одинакова в UI, Server, discovery и сертификате; 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');
const archive = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlocksConfig.java');
assert.match(ui, /SHINE_CORE_NAMESPACE\s*=\s*'SHiNE'/);
assert.match(archive, /TEST_TAG_VALUE\s*=\s*ShineProtocolTags\.CORE_NAMESPACE/);
assert.match(server, /CORE_NAMESPACE\s*=\s*"SHiNE"/);
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'SHiNE'/);
assert.match(reg, /ShineProtocolTags\.CORE_REGISTRATION_TAGS/);
for (const txt of [ui, server, viewer, reg]) assert.doesNotMatch(txt, /test5591/);
import { parseServerEnvironment } from '../js/services/server-environment.js';
import { coreTags } from '../js/services/core-content.js';
const read = p => fs.readFileSync(new URL('../../'+p, import.meta.url), 'utf8');
test('GetServerInfo: strict environment tuple; absent or inconsistent mode cannot sign', () => {
for (const [testMode,arweaveAppTag,solanaCluster] of [[true,'test5570','devnet'],[false,'SHiNE','mainnet-beta']]) {
const env = parseServerEnvironment({status:200,payload:{testMode,arweaveAppTag,solanaCluster}});
assert.equal(coreTags({blockNumber:0},env.arweaveAppTag)[0].value, arweaveAppTag);
assert.throws(()=>parseServerEnvironment({status:200,payload:{testMode,arweaveAppTag:'test5599',solanaCluster}}));
assert.throws(()=>parseServerEnvironment({status:200,payload:{testMode:!testMode,arweaveAppTag,solanaCluster}}));
}
assert.throws(()=>parseServerEnvironment({status:200,payload:{solanaCluster:'mainnet-beta'}}));
assert.throws(()=>coreTags({blockNumber:0}));
assert.throws(()=>coreTags({blockNumber:0},'test5599'));
});
test('Server/Viewer/ESP32 use the current independent namespaces', () => {
const server=read('SHiNE-server/shine-server-config/src/main/java/utils/config/ServerEnvironment.java');
const viewer=read('shine-UI/static-sites/arweave-viewer/index.html');
const esp=read('ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/shine_registration_signer/certificate_v1.h');
assert.match(server,/PRODUCTION_APP = "SHiNE"/); assert.match(server,/TEST_APP = "test5570"/);
assert.match(viewer,/\[SHINE_ARWEAVE_APP_TAG\]/); assert.doesNotMatch(viewer,/test5599/);
assert.match(esp,/avroString\(a,"SHiNE"\)/);
});
+7 -7
View File
@@ -16,7 +16,7 @@ const special = new Map([[SHINE_CORE_LINE_PROFILE,'P'],[SHINE_CORE_LINE_CONNECTI
test('CORE v2 namespace и числовые линии согласованы в Java и UI', () => {
const server=fs.readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java',import.meta.url),'utf8');
assert.equal(SHINE_CORE_NAMESPACE,'SHiNE');
assert.match(server,/CORE_NAMESPACE\s*=\s*"SHiNE"/);
assert.match(server,/CORE_NAMESPACE\s*=\s*utils.config.ServerEnvironment.ARWEAVE_APP_TAG/);
assert.equal(SHINE_CORE_MAX_BLOCK_NUMBER,2147482623);
assert.deepEqual([...special.keys()],[2147483645,2147483646,2147483647]);
});
@@ -41,7 +41,7 @@ test('CORE/CONTENT fixtures: BigEndian, hash, ANS-104 Ed25519 и подписи
newCore.writeInt32BE(history.length,33);
newCore.writeBigInt64BE(core.readBigInt64BE(37),37);
unhex(contentHash).copy(newCore,45); unhex(contentId).copy(newCore,77);
const tags=[{name:'App',value:'test5599'},{name:'n',value:String(history.length)}];
const tags=[{name:'App',value:'test5570'},{name:'n',value:String(history.length)}];
if(core.length===149) {
const line=core.readInt32BE(109), prev=core.readInt32BE(113);
newCore.writeInt32BE(line,109); newCore.writeInt32BE(prev,113); unhex(history[prev]).copy(newCore,117);
@@ -70,7 +70,7 @@ test('Minimal pair codec and container: exact vectors, tampering, unsigned lengt
for (const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
const core=decodeCore(unhex(coreHex)), content=decodeContent(unhex(contentHex)), owner=unhex(ownerHex);
assert.equal(hex(encodeCore(core)),coreHex); assert.equal(hex(encodeContent(content)),contentHex);
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content, ...core});
const signed=await signCoreContentPair({arweaveAppTag:"SHiNE",owner32:owner,privateKey:key,content, ...core});
assert.notEqual(hex(signed.coreDataItem),coreItemHex,name); assert.equal(hex(signed.contentDataItem),contentItemHex,name);
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
assert.equal(Buffer.from(raw).readUInt32BE(),signed.coreDataItem.length);
@@ -97,15 +97,15 @@ test('HEADER 1.0 signed CORE/CONTENT and inspector accept arbitrary UTF-8 licens
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
const owner=unhex(rows[0][1]);
const login=Buffer.from('Alice@shine');
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', '\ufeffx', 'x'.repeat(255)]) {
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', '\ufeffx', 'x'.repeat(300)]) {
const bytes=Buffer.from(license);
const body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(1, 0, 0, bytes.length),bytes,owner]);
const body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(1, 0, 0, bytes.length >> 8, bytes.length & 255),bytes,owner]);
const content={type:0,subType:0,version:1,body};
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content,prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null});
const signed=await signCoreContentPair({arweaveAppTag:"SHiNE",owner32:owner,privateKey:key,content,prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null});
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
const result=await inspectBlockchainDataItem(Buffer.from(raw).toString('base64'));
assert.equal(result.frame.body.license,license);
assert.equal(result.frame.version,1);
await assert.rejects(signCoreContentPair({owner32:owner,privateKey:key,content:{...content,version:4},prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null}));
await assert.rejects(signCoreContentPair({arweaveAppTag:"SHiNE",owner32:owner,privateKey:key,content:{...content,version:4},prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null}));
}
});
+6 -5
View File
@@ -10,6 +10,7 @@ const source = auth.split('function makeHeaderBodyBytes(')[1]?.split('\nfunction
assert.ok(source, 'production makeHeaderBodyBytes must exist');
const utf8 = value => new TextEncoder().encode(value);
const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeHeaderBodyBytes`, {
HEADER_DEFAULT_LICENSE: auth.match(/export const HEADER_DEFAULT_LICENSE = '([^']+)'/)[1],
utf8Bytes: utf8,
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
@@ -38,7 +39,7 @@ function headerFrame(body, version = 1) {
return frame;
}
test('client writes only HEADER 2: identity, arbitrary license, then initial key', () => {
test('client writes only HEADER 1: identity, arbitrary license, then initial key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine';
const license = 'Лицензия 🌞';
@@ -49,19 +50,19 @@ test('client writes only HEADER 2: identity, arbitrary license, then initial key
1, 0, utf8(previous).length, ...utf8(previous), 0, utf8(license).length, ...utf8(license), ...key,
]);
assert.deepEqual(Array.from(body), Array.from(expected));
assert.match(auth, /export const HEADER_VERSION = 2/);
assert.match(auth, /export const HEADER_VERSION = 1/);
});
test('inspector accepts only HEADER 2 and validates its identity and license', () => {
test('inspector accepts only HEADER 1 and validates its identity and license', () => {
const inspect = inspectorParser();
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', 'x'.repeat(300)]) {
const body = encode({ login: 'Alice@shine', initialBlockchainKey32: key, accountType: 1, previousAccounts: ['Bob@free'], license });
const parsed = inspect(headerFrame(body, 2)).body;
const parsed = inspect(headerFrame(body, 1)).body;
assert.equal(parsed.accountType, 1);
assert.deepEqual(Array.from(parsed.previousAccounts), ['Bob@free']);
assert.equal(parsed.license, license);
assert.throws(() => inspect(headerFrame(body.slice(0, -1), 2)));
assert.throws(() => inspect(headerFrame(body.slice(0, -1), 1)));
assert.equal(inspect(headerFrame(body, 3)).body.kind, 'unsupported_version');
}
assert.throws(() => encode({ login: 'Alice@shine', initialBlockchainKey32: key, license: 'x'.repeat(65536) }));
@@ -45,7 +45,8 @@ test('переводы согласий вычисляются при откры
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.match(likes, /confirmPublicHistoryAction\(\{ text: warning\.textContent \}\)/);
assert.match(likes, /warning\.textContent = t\('dialogs\.modals\.like_action_sheet\.label_002'\)/);
assert.doesNotMatch(likes, /PUBLIC_HISTORY_REMEMBER_LABEL/);
assert.match(profile, /function shiningSteps\(\)/);
assert.match(profile, /steps:\s*shiningSteps\(\)/);
+1 -1
View File
@@ -11,7 +11,7 @@ const owner=Buffer.from((await crypto.subtle.exportKey('jwk',key)).x,'base64url'
const stored=rows.map(r=>({blockHash:r[3],blockBytesB64:b64(packCoreContent(h(r[6]),h(r[8])))}));
for (const cutoff of [0,2,7]) test(`M5 FORK at #${cutoff}: new owner, retained TECH tail, deterministic retry`,async()=>{
const calls=[];
const client=new KeyRotationClient({ws:{async request(op,p){
const client=new KeyRotationClient({getServerEnvironment:async()=>({arweaveAppTag:"test5570"}),ws:{ws:{},connectionGeneration:1,async request(op,p){
if(op==='GetBlockchainBlock'){assert.equal(p.blockchainName,'Alice-001');return {status:200,payload:stored[p.blockNumber]};}
assert.equal(op,'KeyRotationAddBlock');calls.push(p);return {status:200,payload:{}};
}}});
+9 -13
View File
@@ -10,7 +10,7 @@ const funcs=html.slice(html.indexOf(' async function digestSha256'),html.indexO
const b64=html.slice(html.indexOf(' function base64Url('),html.indexOf(' async function arweaveOwnerAddressFromBlockchainKey'));
const loader=html.slice(html.indexOf(' async function loadArweavePairs('),html.indexOf(' async function checkSolanaEndpoint('));
const checks=html.slice(html.indexOf(' function v3ZeroHash('),html.indexOf(' function v3MetricText('));
const ctx=vm.createContext({crypto:webcrypto,Uint8Array,DataView,TextDecoder,TextEncoder,btoa, MAGIC:'SHiNE',bytesToHex:b=>Buffer.from(b).toString('hex'),baseUrl:s=>s,fetch:()=>{throw Error('unexpected fetch')}});
const ctx=vm.createContext({URLSearchParams,location:{search:"?network=test"},crypto:webcrypto,Uint8Array,DataView,TextDecoder,TextEncoder,btoa, MAGIC:'SHiNE',bytesToHex:b=>Buffer.from(b).toString('hex'),baseUrl:s=>s,fetch:()=>{throw Error('unexpected fetch')}});
vm.runInContext(source+funcs+b64+loader+checks+';globalThis.viewer={parseCorePayload,parseBlockchainBlock,checkIndexedCoreTags,loadArweavePairs,v3Verification}',ctx);
const v=ctx.viewer,bytes=s=>Uint8Array.from(Buffer.from(s,'hex'));
const itemid=x=>Buffer.from(x,'hex').toString('base64url');
@@ -29,20 +29,16 @@ test('viewer: rejects tampered CONTENT, invalid CORE and wrong indexed tags',asy
test('viewer: requests CORE then CONTENT by ID and never claims signature verification',async()=>{
const f=find('post'),id=itemid(f.coreItemId),cid=itemid(f.contentItemId),calls=[];
ctx.fetch=async url=>{calls.push(url);const raw=url.endsWith(cid)?f.content:f.core;return {ok:true,arrayBuffer:async()=>bytes(raw).buffer};};
const r=await v.loadArweavePairs('https://mock.invalid',[{id,owner:{address:'indexed'},tags:[{name:'App',value:'test5599'},{name:'n',value:'2'},{name:'l',value:'1'}]}]);
const r=await v.loadArweavePairs('https://mock.invalid',[{id,owner:{address:'indexed'},tags:[{name:'App',value:'test5570'},{name:'n',value:'2'},{name:'l',value:'1'}]}]);
assert.deepEqual(calls,[`https://mock.invalid/${id}`,`https://mock.invalid/${cid}`]);assert.equal(r.blocks[0].hashHex,f.coreHash);
const checks=v.v3Verification(r.blocks);assert.equal(checks.signature.ok,0);assert.equal(checks.signature.na,1);assert.equal(checks.global.na,1);
ctx.fetch=async url=>url.endsWith(cid)?{ok:false,status:404}:{ok:true,arrayBuffer:async()=>bytes(f.core).buffer};
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5599'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5570'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
});
test('viewer: parses historical v2 and v3 primary declaration',async()=>{
const f=find('header'), old=bytes(f.content), key=old.slice(-32), prefix=old.slice(7,-32);
const csv=new TextEncoder().encode('Bob@free,Older');
for(const [version,body,role] of [[2,[...prefix,0,...key],1]]){
const content=Uint8Array.from([1,0,0,0,0,0,version,...body]),core=bytes(f.core);
core.set(new Uint8Array(await webcrypto.subtle.digest('SHA-256',content)),45);
const result=await v.parseBlockchainBlock(core,content);
assert.equal(result.body.accountType,role);if (role !== null) assert.equal(result.body.license,'');
if (role !== null) assert.deepEqual(Array.from(result.body.previousAccounts),[]);
}
test('viewer: rejects HEADER body version 2',async()=>{
const f=find('header'), content=bytes(f.content), core=bytes(f.core);
content[6]=2;
core.set(new Uint8Array(await webcrypto.subtle.digest('SHA-256',content)),45);
const result=await v.parseBlockchainBlock(core,content);
assert.equal(result.body.kind,'unsupported');
});
+2 -2
View File
@@ -25,7 +25,7 @@ test('existing body factories produce exact independent signed pair; ordinal is
const key=await crypto.subtle.importKey('pkcs8',Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]),{name:'Ed25519'},false,['sign']);
for(const r of rows){
const core=decodeCore(unhex(r[2])),content=decodeContent(unhex(r[4]));
const args={owner32:unhex(r[1]),privateKey:key,blockNumber:core.blockNumber,prevBlockHash:Buffer.from(core.prevCoreHash32).toString('hex'),timestamp:core.timestamp,msgType:content.type,msgSubType:content.subType,msgVersion:content.version};
const args={arweaveAppTag:"SHiNE",owner32:unhex(r[1]),privateKey:key,blockNumber:core.blockNumber,prevBlockHash:Buffer.from(core.prevCoreHash32).toString('hex'),timestamp:core.timestamp,msgType:content.type,msgSubType:content.subType,msgVersion:content.version};
const result=await signEventContainer({...args,bodyBytes:oldFactoryBody(core,content)});
assert.notDeepEqual(result.bytes,fixture(r),r[0]);assert.equal(result.hash,r[3]);
if(core.line){
@@ -39,7 +39,7 @@ test('existing body factories produce exact independent signed pair; ordinal is
assert.equal(inspection.frame.blockNumber,core.blockNumber);assert.equal(inspection.frame.type,content.type);
assert.deepEqual(Buffer.from(inspection.frame.bodyBytes),Buffer.from(content.body));
if(core.line) assert.equal(inspection.frame.body.line.lineSequence,42);
if(core.blockNumber===0) assert.equal(inspection.frame.body.license,'');
if(core.blockNumber===0) assert.match(inspection.frame.body.license,/^licenses:CC-BY-NC-4\.0\/sha256:/);
}
});
test('lost response: retransmit the identical signed container, then confirm canonical bytes',async()=>{
@@ -5,18 +5,12 @@ 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 = {
HEADER_DEFAULT_LICENSE: auth.match(/export const HEADER_DEFAULT_LICENSE = '([^']+)'/)[1],
utf8Bytes: value => new TextEncoder().encode(value),
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
@@ -24,7 +18,7 @@ const context = {
};
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('CORE/CONTENT HEADER 2 contains identity, arbitrary license and initial key', () => {
test('CORE/CONTENT HEADER 1 contains identity, arbitrary license and 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');
@@ -34,21 +28,12 @@ test('CORE/CONTENT HEADER 2 contains identity, arbitrary license and initial key
const identityOffset = 6 + login.length;
assert.equal(result[identityOffset], 1);
assert.deepEqual(Array.from(result.slice(identityOffset + 1, identityOffset + 3)), [0, 0]);
assert.deepEqual(Array.from(result.slice(identityOffset + 3, identityOffset + 5)), [0, 7]);
assert.equal(new TextDecoder().decode(result.slice(identityOffset + 5, identityOffset + 12)), 'CC0-1.0');
assert.deepEqual(Array.from(result.slice(identityOffset + 12)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 1 + 2 + 2 + 7 + 32);
const license = context.HEADER_DEFAULT_LICENSE;
const licenseBytes = new TextEncoder().encode(license);
assert.deepEqual(Array.from(result.slice(identityOffset + 3, identityOffset + 5)), [licenseBytes.length >> 8, licenseBytes.length & 255]);
assert.equal(new TextDecoder().decode(result.slice(identityOffset + 5, identityOffset + 5 + licenseBytes.length)), license);
assert.deepEqual(Array.from(result.slice(identityOffset + 5 + licenseBytes.length)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 1 + 2 + 2 + licenseBytes.length + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 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/);
assert.match(auth, /export const HEADER_VERSION = 1/);
});