Разделить среды и закрепить лицензии в 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
+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);