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
+155 -544
View File
@@ -39,9 +39,9 @@ import {
saveEncryptedUserSecrets,
saveSessionMaterial,
} from './key-vault.js';
import { createAns104DataItem, parseAns104DataItem } from './ans104-data-item.js';
import { coreHashBytes, coreHex, signCoreContentPair, splitEventBody } from './core-content.js';
import { defaultServerWs } from '../deploy-config.js';
import { SHINE_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_CHANNEL_TAG_NAME, SHINE_TYPE_TAG_NAME } from './protocol-tags.js';
import { SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from './protocol-tags.js';
const BCH_SUFFIX = '001';
const ZERO64 = '0'.repeat(64);
@@ -94,8 +94,6 @@ const SESSION_TYPE_WALLET = 50;
const SESSION_TYPE_HOMESERVER = 100;
const SIGNAL_TARGET_SINGLE = 'single_session';
const SIGNAL_TARGET_ALL = 'all_sessions';
const SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST = 'remote_addblock_request';
const SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT = 'remote_addblock_result';
const CONNECTION_SUBTYPES = Object.freeze({
close_friend: { on: 10, off: 11 },
@@ -151,10 +149,6 @@ function opError(op, response) {
return error;
}
function createSignalRequestId(prefix = 'signal') {
return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function makeClientInfo() {
const ua = navigator.userAgent || 'unknown';
return ua.slice(0, 50);
@@ -224,13 +218,6 @@ function int8Byte(value) {
return new Uint8Array([n & 0xff]);
}
function int64Bytes(value) {
const bytes = new Uint8Array(8);
const view = new DataView(bytes.buffer);
view.setBigInt64(0, BigInt(value), false);
return bytes;
}
function uint16Bytes(value) {
const bytes = new Uint8Array(2);
const view = new DataView(bytes.buffer);
@@ -541,9 +528,7 @@ function extractContactsFromDialogs(dialogs) {
return out;
}
export const HEADER_LICENSE_CC0 = 'CC0-1.0';
export const HEADER_LICENSE_FIELD_CC0 = `license:${HEADER_LICENSE_CC0}`;
export const HEADER_VERSION_CC0 = 2;
export const HEADER_CONTENT_VERSION = 1;
function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
const cleanLogin = String(login || '').trim();
@@ -559,7 +544,6 @@ function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
utf8Bytes('SHiNE'),
int8Byte(loginBytes.length),
loginBytes,
utf8Bytes(HEADER_LICENSE_FIELD_CC0),
keyBytes,
);
}
@@ -892,81 +876,17 @@ function resolveLatestLineStep(message) {
return null;
}
function bytesToHexLower(bytes) {
return Array.from(bytes || [], (value) => Number(value).toString(16).padStart(2, '0')).join('');
}
function parseStoredLineMeta(blockBytesB64, { fixedLine = false } = {}) {
const raw = base64ToBytes(String(blockBytesB64 || ''));
const frame = parseAns104DataItem(raw).data;
const bodyOffset = 88;
const minLength = fixedLine ? bodyOffset + 40 : bodyOffset + 44;
if (!(frame instanceof Uint8Array) || frame.length < minLength) throw new Error('Некорректный line-блок');
const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
if (fixedLine) {
return {
lineCode: 0,
prevLineNumber: view.getInt32(bodyOffset, false),
prevLineHashHex: bytesToHexLower(frame.slice(bodyOffset + 4, bodyOffset + 36)),
lineSequence: view.getInt32(bodyOffset + 36, false),
};
}
return {
lineCode: view.getInt32(bodyOffset, false),
prevLineNumber: view.getInt32(bodyOffset + 4, false),
prevLineHashHex: bytesToHexLower(frame.slice(bodyOffset + 8, bodyOffset + 40)),
lineSequence: view.getInt32(bodyOffset + 40, false),
};
}
function typeIndexTagValue(msgType) {
switch (Number(msgType)) {
case MSG_TYPE_TECH: return 'tech';
case MSG_TYPE_CONNECTION: return 'conn';
case MSG_TYPE_USER_PROFILE: return 'prof';
default: return '';
}
}
function isLineConflictError(error) {
return new Set([
'BAD_PREV_LINE_NUMBER',
'BAD_PREV_LINE_HASH',
'BAD_LINE_SEQUENCE',
'BAD_LINE_STATE',
'LINE_HEAD_CONFLICT',
'GLOBAL_HEAD_CONFLICT',
]).has(String(error?.code || '').toUpperCase());
}
function buildBlockPreimage({ prevBlockHashHex, back32HashHex, blockNumber, msgType, msgSubType, msgVersion = 1, bodyBytes }) {
const prevHashBytes = hexToBytes(normalizeHex32(prevBlockHashHex));
const back32HashBytes = hexToBytes(normalizeHex32(back32HashHex, ZERO64));
const body = bodyBytes || new Uint8Array(0);
const blockSize = 2 + 32 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + body.length;
return concatBytes(
int16Bytes(1),
prevHashBytes,
back32HashBytes,
int32Bytes(blockSize),
int32Bytes(blockNumber),
int64Bytes(Math.floor(Date.now() / 1000)),
int16Bytes(msgType),
int16Bytes(msgSubType),
int16Bytes(msgVersion),
body
);
}
function buildRemoteBlockBodyBytes({ msgType, msgSubType, msgVersion = 1, bodyBytes }) {
const body = bodyBytes || new Uint8Array(0);
return concatBytes(
int16Bytes(msgType),
int16Bytes(msgSubType),
int16Bytes(msgVersion),
body,
);
}
export class AuthService {
constructor(serverUrl) {
this.serverUrl = normalizeServerUrl(serverUrl);
@@ -974,7 +894,6 @@ export class AuthService {
this.eventListeners = new Map();
this.wsEventUnsubscribers = new Map();
this.headerHashCache = new Map();
this.lineTailCache = new Map();
this.lineWriteQueues = new Map();
this.writeLocks = new Map();
this.passwordKeyBundleCache = new Map();
@@ -1010,7 +929,6 @@ export class AuthService {
this.ws = new WsJsonClient(this.serverUrl);
this.ws.setRequestGuard(requestGuard);
this.headerHashCache = new Map();
this.lineTailCache = new Map();
this.lineWriteQueues = new Map();
this.writeLocks.clear();
this.bindRegisteredEventsToCurrentWs();
@@ -1589,6 +1507,16 @@ export class AuthService {
return response.payload || {};
}
// Public channel lookup is not a request for another user's private feed.
async listOwnedChannelSummaries(login, limit = 500) {
const result = await this.listUserProfileChannels(login, 'owned', limit, 0, false);
return (Array.isArray(result?.channels) ? result.channels : []).map(row => ({ channel: {
ownerLogin: row.ownerLogin, ownerBlockchainName: row.ownerBlockchainName,
channelName: row.slug, displayName: row.displayName, avaAr: row.avatarAr, avaPr: row.avatarPr,
deleted: !!row.deleted, channelRoot: { blockNumber: row.rootBlockNumber, blockHash: row.rootBlockHashHex },
} }));
}
async getChannelMessages(channel, limit = null, sort = 'asc', login = '') {
const normalizedChannel = {
ownerBlockchainName: String(channel?.ownerBlockchainName || '').trim(),
@@ -1661,266 +1589,105 @@ export class AuthService {
return response.payload || {};
}
async resolveFreshBlockchainCursor(login) {
const cleanLogin = String(login || '').trim();
const user = await this.getUser(cleanLogin);
const blockchainName = String(user?.blockchainName || `${cleanLogin}-${BCH_SUFFIX}`).trim();
const freshNum = Number(user?.serverLastGlobalNumber);
const freshHash = normalizeHex32(user?.serverLastGlobalHash, ZERO64);
return {
blockchainName,
cursor: {
serverLastGlobalNumber: Number.isFinite(freshNum) ? freshNum : -1,
serverLastGlobalHash: freshHash,
},
};
}
async submitPreparedAddBlock({ login, storagePwd, blockchainName, blockNumber, prevBlockHash, preimage, ansTags }) {
const cleanLogin = String(login || '').trim();
const cleanBlockchainName = String(blockchainName || '').trim();
const cleanPrevBlockHash = normalizeHex32(prevBlockHash, ZERO_HASH_HEX);
if (!cleanLogin || !cleanBlockchainName) throw new Error('submitPreparedAddBlock: missing login/blockchainName');
if (!(preimage instanceof Uint8Array) || preimage.length === 0) {
throw new Error('submitPreparedAddBlock: bad preimage');
}
const savedKeys = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const blockchainPrivatePkcs8 = String(savedKeys?.blockchainKey || '').trim();
if (blockchainPrivatePkcs8) {
const privateKey = await importPkcs8Ed25519(blockchainPrivatePkcs8);
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(blockchainPrivatePkcs8));
const dataItemBytes = await createAns104DataItem({
owner32,
privateKey,
data: preimage,
tags: Array.isArray(ansTags) && ansTags.length ? ansTags : [{ name: SHINE_APP_TAG_NAME, value: SHINE_APP_TAG_VALUE }],
});
return this.ws.request('AddBlock', {
blockchainName: cleanBlockchainName,
blockNumber: Number(blockNumber),
prevBlockHash: cleanPrevBlockHash,
blockBytesB64: bytesToBase64(dataItemBytes),
});
}
const remoteSessionId = String(this.remoteAddBlockSessionId || '').trim();
if (!remoteSessionId) {
throw new Error('На устройстве нет blockchain key и не выбрана homeserver-сессия для remote AddBlock');
}
const signalRequestId = createSignalRequestId('remote-addblock');
const responseWait = this.waitForSignal({
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT,
signalRequestId,
timeoutMs: 20000,
});
const signalData = {
operation: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
login: cleanLogin,
blockchainName: cleanBlockchainName,
blockNumber: Number(blockNumber),
prevBlockHash: cleanPrevBlockHash,
blockPreimageB64: bytesToBase64(preimage),
};
await this.sendSignal({
toLogin: cleanLogin,
targetMode: SIGNAL_TARGET_SINGLE,
targetSessionId: remoteSessionId,
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
data: JSON.stringify(signalData),
storagePwd,
includeClientSignature: true,
});
const signalPayload = await responseWait;
let result = {};
try {
result = JSON.parse(String(signalPayload?.data || '{}'));
} catch {
throw new Error('Некорректный ответ remote AddBlock от homeserver');
}
if (!result?.ok) {
throw new Error(String(result?.errorMessage || result?.error || 'remote_addblock_failed'));
}
return {
status: 200,
payload: {
serverLastGlobalNumber: Number(result?.serverLastGlobalNumber ?? blockNumber),
serverLastGlobalHash: String(result?.serverLastGlobalHash || ZERO_HASH_HEX),
remote: true,
},
};
}
async submitRemoteAddBlockBody({ login, storagePwd, blockchainName, blockBodyBytes }) {
const cleanLogin = String(login || '').trim();
const cleanBlockchainName = String(blockchainName || '').trim();
if (!cleanLogin || !cleanBlockchainName) throw new Error('submitRemoteAddBlockBody: missing login/blockchainName');
if (!(blockBodyBytes instanceof Uint8Array) || blockBodyBytes.length < 6) {
throw new Error('submitRemoteAddBlockBody: bad blockBodyBytes');
}
const remoteSessionId = String(this.remoteAddBlockSessionId || '').trim();
if (!remoteSessionId) {
throw new Error('На устройстве нет blockchain key и не выбрана homeserver-сессия для remote AddBlock');
}
const signalRequestId = createSignalRequestId('remote-addblock');
const responseWait = this.waitForSignal({
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT,
signalRequestId,
timeoutMs: 20000,
});
const signalData = {
operation: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
blockchainName: cleanBlockchainName,
blockBodyB64: bytesToBase64(blockBodyBytes),
};
await this.sendSignal({
toLogin: cleanLogin,
targetMode: SIGNAL_TARGET_SINGLE,
targetSessionId: remoteSessionId,
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
signalRequestId,
data: JSON.stringify(signalData),
storagePwd,
includeClientSignature: true,
});
const signalPayload = await responseWait;
let result = {};
try {
result = JSON.parse(String(signalPayload?.data || '{}'));
} catch {
throw new Error('Некорректный ответ remote AddBlock от homeserver');
}
if (!result?.ok) {
throw new Error(String(result?.errorMessage || result?.error || 'remote_addblock_failed'));
}
return {
status: 200,
payload: {
serverLastGlobalNumber: Number(result?.serverLastGlobalNumber ?? -1),
serverLastGlobalHash: String(result?.serverLastGlobalHash || ZERO_HASH_HEX),
remote: true,
},
};
}
async runAddBlockWithRetry({ login, storagePwd, resolveFreshState, buildPreimage, ansTags }) {
let freshState = await resolveFreshState();
let blockchainName = String(freshState?.blockchainName || '').trim();
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
const tryAdd = async (cursor) => {
const blockNumber = Number(cursor?.serverLastGlobalNumber ?? -1) + 1;
const prevBlockHash = normalizeHex32(cursor?.serverLastGlobalHash, ZERO64);
const back32Hash = blockNumber < 32
? ZERO64
: normalizeHex32(await this.getBlockHashByNumber(blockchainName, blockNumber - 32), ZERO64);
if (blockNumber >= 32 && back32Hash === ZERO64) {
throw new Error(`Не удалось получить hash блока #${blockNumber - 32} для back32Hash`);
}
const preimage = await buildPreimage({ blockNumber, prevBlockHash, back32Hash, blockchainName });
return this.submitPreparedAddBlock({
login,
storagePwd,
blockchainName,
blockNumber,
prevBlockHash,
preimage,
ansTags,
});
};
let cursor = freshState.cursor;
let response = await tryAdd(cursor);
if (response.status !== 200) {
const knownNum = Number(response?.payload?.serverLastGlobalNumber);
const knownHash = String(response?.payload?.serverLastGlobalHash || '');
if (Number.isFinite(knownNum) && /^[0-9a-fA-F]{64}$/.test(knownHash)) {
cursor = { serverLastGlobalNumber: knownNum, serverLastGlobalHash: knownHash.toLowerCase() };
response = await tryAdd(cursor);
} else {
freshState = await resolveFreshState();
blockchainName = String(freshState?.blockchainName || blockchainName).trim() || blockchainName;
cursor = freshState.cursor;
response = await tryAdd(cursor);
async getCoreHeads(lineCode = null) {
const response = await this.ws.request('GetMyCoreHeads', lineCode === null ? {} : { lineCode });
if (response.status !== 200) throw opError('GetMyCoreHeads', response);
const heads = response.payload?.result;
if (!heads || typeof heads.blockchainName !== 'string' || !heads.blockchainName) throw new Error('Invalid CORE heads response');
for (const head of [heads.global, heads.line]) {
if (head != null) {
if (!Number.isInteger(head.blockNumber) || head.blockNumber < 0) throw new Error('Invalid CORE head number');
coreHashBytes(head.coreHash);
}
}
if (response.status !== 200) throw opError('AddBlock', response);
return {
response,
blockchainName,
};
return heads;
}
async addBlockSigned({ login, storagePwd, msgType, msgSubType, msgVersion = 1, bodyBytes, channelSlug = '', _skipHeaderEnsure = false }) {
const cleanLogin = (login || '').trim();
if (!cleanLogin) throw new Error('Missing login for AddBlock');
if (!storagePwd) throw new Error('Missing storagePwd for AddBlock signing');
if (!cleanLogin || !storagePwd) throw new Error('Missing login/storagePwd for AddBlock');
const requestServer = this.serverUrl;
const requestLogin = this.currentLogin;
const requestSession = this.currentSessionId;
const sameContext = () => this.serverUrl === requestServer && this.currentLogin === requestLogin && this.currentSessionId === requestSession;
const isHeader = Number(msgType) === MSG_TYPE_TECH && Number(msgSubType) === MSG_SUBTYPE_TECH_HEADER;
const keyBundle = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const blockchainPrivatePkcs8 = String(keyBundle?.blockchainKey || '').trim();
// Old homeserver/ESP32 signs Frame. Never send it a CORE write or silently fall back.
if (!blockchainPrivatePkcs8) throw new Error('CORE AddBlock requires a local blockchain key; remote signing is not migrated yet');
if (!_skipHeaderEnsure && !isHeader) {
await this.ensureBlockchainHeader(cleanLogin, storagePwd);
}
const keyBundle = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
const blockchainPrivatePkcs8 = String(keyBundle?.blockchainKey || '').trim();
if (!blockchainPrivatePkcs8) {
const user = await this.getUser(cleanLogin);
const blockchainName = String(user?.blockchainName || `${cleanLogin}-${BCH_SUFFIX}`).trim();
if (!blockchainName) throw new Error('Не удалось определить blockchainName для remote AddBlock');
const response = await this.submitRemoteAddBlockBody({
login: cleanLogin,
storagePwd,
blockchainName,
blockBodyBytes: buildRemoteBlockBodyBytes({ msgType, msgSubType, msgVersion, bodyBytes }),
});
return response.payload || {};
const { content, line } = splitEventBody({ msgType: Number(msgType), msgSubType: Number(msgSubType), msgVersion: Number(msgVersion), bodyBytes });
const privateKey = await importPkcs8Ed25519(blockchainPrivatePkcs8);
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(blockchainPrivatePkcs8));
const heads = await this.getCoreHeads(line?.lineCode ?? null);
const blockchainName = heads.blockchainName;
if (loginFromBlockchainNameValue(blockchainName).toLowerCase() !== cleanLogin.toLowerCase()) throw new Error('CORE heads belong to another user');
if (!sameContext()) throw new Error('CORE write context changed');
if (isHeader && heads.global != null) return { serverLastGlobalNumber: heads.global.blockNumber, serverLastGlobalHash: heads.global.coreHash };
if (!isHeader && heads.global == null) throw new Error('CORE HEADER missing');
const op = isHeader ? 'CreateGenesis' : 'AddBlock';
const send = async current => {
if (current.blockchainName.toLowerCase() !== blockchainName.toLowerCase()) throw new Error('CORE fork changed; refresh before writing');
if (line && (!current.line || current.line.blockNumber !== line.prevLineBlockNumber || current.line.coreHash.toLowerCase() !== coreHex(line.prevLineCoreHash32))) {
const error = new Error('CORE line changed; rebuild event'); error.code = 'LINE_HEAD_CONFLICT'; throw error;
}
const blockNumber = current.global == null ? 0 : current.global.blockNumber + 1;
if (isHeader !== (blockNumber === 0)) throw new Error('CORE genesis state changed');
const prevBlockHash = current.global?.coreHash.toLowerCase() ?? ZERO64;
const pair = await signCoreContentPair({ owner32, privateKey, content, line, blockNumber, prevCoreHash32: coreHashBytes(prevBlockHash), timestamp: Math.floor(Date.now() / 1000) });
const payload = { blockchainName, blockNumber, prevBlockHash: isHeader ? '' : prevBlockHash,
coreDataItemB64: bytesToBase64(pair.coreDataItem), contentDataItemB64: bytesToBase64(pair.contentDataItem) };
const blockHash = coreHex(pair.coreHash32);
const accepted = response => ({ ...response, payload: { ...response.payload, submittedBlockNumber: blockNumber, submittedBlockHash: blockHash } });
const request = () => {
if (!sameContext()) throw new Error('CORE write context changed');
return this.ws.request(op, payload);
};
let response, firstError;
try { response = await request(); } catch (error) { firstError = error; }
if (!firstError && response && Number(response.status) >= 200 && Number(response.status) < 500) {
return response.status === 200 ? accepted(response) : response;
}
// A lost response (or server 5xx) is NOT an explicit head conflict. The
// first attempt may have committed. Retry exactly the same signed items.
try {
response = await request();
if (response?.status === 200) return accepted(response);
} catch {}
// If exact retry did not confirm success, check the actual signed bytes
// in the currently active fork, not just the latest global head.
if (sameContext()) {
try {
const active = await this.getCoreHeads();
if (sameContext() && active.blockchainName.toLowerCase() === blockchainName.toLowerCase()) {
const found = await this.ws.request('GetBlockchainBlock', { blockchainName, blockNumber });
const row = found?.payload;
if (sameContext() && found?.status === 200 && row?.blockNumber === blockNumber && row?.coreHash === blockHash
&& row?.contentStatus === 'VALID' && row.coreDataItemB64 === payload.coreDataItemB64 && row.contentDataItemB64 === payload.contentDataItemB64) {
return accepted({ status: 200, payload: { serverLastGlobalNumber: active.global.blockNumber, serverLastGlobalHash: active.global.coreHash } });
}
}
} catch {}
}
// Never let the existing line retry rebuild an event after an uncertain
// outcome. The caller must inspect history before manually submitting again.
const error = new Error('Результат записи неизвестен. Проверьте историю блокчейна перед повторной отправкой (CORE_WRITE_OUTCOME_UNKNOWN)', { cause: firstError });
error.code = 'CORE_WRITE_OUTCOME_UNKNOWN';
error.blockchainName = blockchainName;
error.blockNumber = blockNumber;
error.coreHash = blockHash;
throw error;
};
let response = await send(heads);
// A fresh signature is allowed only after a definite rejection, never after an ambiguous attempt.
if (!isHeader && response.status === 409 && opError('AddBlock', response).code === 'GLOBAL_HEAD_CONFLICT') {
response = await send(await this.getCoreHeads(line?.lineCode ?? null));
}
const ansTags = [{ name: SHINE_APP_TAG_NAME, value: SHINE_APP_TAG_VALUE }];
const typeIndexTag = typeIndexTagValue(msgType);
if (typeIndexTag) ansTags.push({ name: SHINE_TYPE_TAG_NAME, value: typeIndexTag });
const cleanChannelSlug = String(channelSlug || '').trim();
if (cleanChannelSlug) ansTags.push({ name: SHINE_CHANNEL_TAG_NAME, value: cleanChannelSlug });
const { response, blockchainName } = await this.runAddBlockWithRetry({
login: cleanLogin,
storagePwd,
resolveFreshState: () => this.resolveFreshBlockchainCursor(cleanLogin),
ansTags,
buildPreimage: async ({ blockNumber, prevBlockHash, back32Hash }) => buildBlockPreimage({
prevBlockHashHex: prevBlockHash,
back32HashHex: back32Hash,
blockNumber,
msgType,
msgSubType,
msgVersion,
bodyBytes,
}),
});
if (response.status !== 200) throw opError(op, response);
const payload = response.payload || {};
const acceptedNum = Number(payload?.serverLastGlobalNumber);
const acceptedHash = normalizeHex32(payload?.serverLastGlobalHash, ZERO64);
if (Number.isFinite(acceptedNum) && acceptedNum === 0 && acceptedHash !== ZERO64) {
this.headerHashCache.set(blockchainName, acceptedHash);
}
if (payload.submittedBlockNumber === 0 && payload.submittedBlockHash) this.headerHashCache.set(blockchainName, payload.submittedBlockHash);
return payload;
}
@@ -1952,7 +1719,7 @@ export class AuthService {
storagePwd,
msgType: MSG_TYPE_TECH,
msgSubType: MSG_SUBTYPE_TECH_HEADER,
msgVersion: HEADER_VERSION_CC0,
msgVersion: HEADER_CONTENT_VERSION,
// HEADER хранит исходный регистр неизменяемого имени из Solana/Arweave.
// Нормализация нужна только для уникальности и имени самой цепочки.
bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32 }),
@@ -2143,7 +1910,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return payload;
});
}
@@ -2198,7 +1964,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return payload;
});
}
@@ -2323,97 +2088,14 @@ export class AuthService {
return response.payload || {};
}
async findLatestOwnLineBlock({
blockchainName,
msgType,
subTypes = null,
lineCode = null,
fixedLine = false,
stopAtBlock = 0,
}) {
const cleanBch = String(blockchainName || '').trim();
if (!cleanBch) throw new Error('Missing blockchainName for line lookup');
const subtypeSet = subTypes == null ? null : new Set(Array.from(subTypes, (value) => Number(value)));
const minBlock = Math.max(0, Number(stopAtBlock) || 0);
let beforeBlock = null;
for (;;) {
const page = await this.getMyBlockchainPage({ beforeBlock, limit: 100, includeBlockBytes: true });
const pageBch = String(page?.blockchainName || '').trim();
if (pageBch && pageBch !== cleanBch) throw new Error('GetMyBlockchain returned another blockchain');
const blocks = Array.isArray(page?.blocks) ? page.blocks : [];
for (const block of blocks) {
const blockNumber = Number(block?.blockNumber);
if (!Number.isInteger(blockNumber) || blockNumber <= minBlock) continue;
if (Number(block?.msgType) !== Number(msgType)) continue;
if (subtypeSet && !subtypeSet.has(Number(block?.msgSubType))) continue;
if (!block?.blockBytesB64) continue;
const meta = parseStoredLineMeta(block.blockBytesB64, { fixedLine });
if (lineCode != null && Number(meta.lineCode) !== Number(lineCode)) continue;
return {
blockNumber,
blockHash: normalizeHex32(block?.blockHash, ZERO64),
lineSequence: Number(meta.lineSequence),
lineCode: Number(meta.lineCode),
};
}
const next = page?.nextBeforeBlock;
if (next == null || !Number.isInteger(Number(next)) || Number(next) <= minBlock) return null;
beforeBlock = Number(next);
}
}
async resolveFixedLineTail({ blockchainName, kind }) {
const cleanBch = String(blockchainName || '').trim();
const kindKey = String(kind || '').trim().toLowerCase();
const config = kindKey === 'profile'
? { msgType: MSG_TYPE_USER_PROFILE, tag: 'prof' }
: kindKey === 'connections'
? { msgType: MSG_TYPE_CONNECTION, tag: 'conn' }
: kindKey === 'tech'
? { msgType: MSG_TYPE_TECH, tag: 'tech', subTypes: [MSG_SUBTYPE_TECH_CREATE_CHANNEL, MSG_SUBTYPE_TECH_FORK] }
: null;
if (!config) throw new Error(`Unknown fixed line kind: ${kind}`);
const cacheKey = `${cleanBch}|${kindKey}`;
const cached = this.lineTailCache.get(cacheKey);
if (cached) return { ...cached };
const latest = await this.findLatestOwnLineBlock({
blockchainName: cleanBch,
msgType: config.msgType,
subTypes: config.subTypes || null,
lineCode: kindKey === 'tech' ? 0 : null,
fixedLine: kindKey !== 'tech',
stopAtBlock: 0,
});
if (latest) {
const result = {
prevLineNumber: latest.blockNumber,
prevLineHashHex: latest.blockHash,
thisLineNumber: latest.lineSequence + 1,
};
this.lineTailCache.set(cacheKey, result);
return { ...result };
}
const headerHash = await this.resolveHeaderHashForBlockchain(cleanBch);
if (headerHash === ZERO64) throw new Error('HEADER блокчейна не найден');
const result = { prevLineNumber: 0, prevLineHashHex: headerHash, thisLineNumber: 1 };
this.lineTailCache.set(cacheKey, result);
return { ...result };
}
rememberLineTail(blockchainName, kind, payload, currentSequence) {
const cleanBch = String(blockchainName || '').trim();
const acceptedNumber = Number(payload?.serverLastGlobalNumber);
const acceptedHash = normalizeHex32(payload?.serverLastGlobalHash, ZERO64);
if (!cleanBch || !Number.isInteger(acceptedNumber) || acceptedNumber < 0 || acceptedHash === ZERO64) return;
this.lineTailCache.set(`${cleanBch}|${String(kind || '').trim().toLowerCase()}`, {
prevLineNumber: acceptedNumber,
prevLineHashHex: acceptedHash,
thisLineNumber: Number(currentSequence) + 1,
});
const code = { profile: SHINE_CORE_LINE_PROFILE, connections: SHINE_CORE_LINE_CONNECTION, tech: SHINE_CORE_LINE_TECH }[String(kind || '').toLowerCase()];
if (code === undefined) throw new Error(`Unknown fixed line kind: ${kind}`);
const heads = await this.getCoreHeads(code);
if (heads.blockchainName.toLowerCase() !== blockchainName.toLowerCase() || !heads.line) throw new Error('CORE fixed line not found');
// Sequence is only an in-memory compatibility argument to existing body factories.
// It is not part of signed CORE or CONTENT and is never sent.
return { prevLineNumber: heads.line.blockNumber, prevLineHashHex: heads.line.coreHash, thisLineNumber: 1 };
}
async runLineWriteLocked(lockKey, buildAndSend) {
@@ -2424,7 +2106,6 @@ export class AuthService {
return await buildAndSend();
} catch (error) {
if (!isLineConflictError(error)) throw error;
this.lineTailCache.clear();
return buildAndSend();
}
});
@@ -2504,12 +2185,11 @@ export class AuthService {
channelTypeVersion: typeVersion,
}),
});
this.rememberLineTail(blockchainName, 'tech', payload, tail.thisLineNumber);
const selector = {
ownerBlockchainName: blockchainName,
channelRootBlockNumber: Number(payload?.serverLastGlobalNumber),
channelRootBlockHash: normalizeHex32(payload?.serverLastGlobalHash, ZERO64),
channelRootBlockNumber: Number(payload?.submittedBlockNumber ?? payload?.serverLastGlobalNumber),
channelRootBlockHash: normalizeHex32(payload?.submittedBlockHash ?? payload?.serverLastGlobalHash, ZERO64),
};
return {
@@ -2546,67 +2226,12 @@ export class AuthService {
if (!channelSlug) throw new Error('Cannot resolve canonical channel slug');
if (rootHashHex === ZERO64) throw new Error('Cannot resolve channel root hash');
const cacheKey = `${blockchainName}|channel:${lineCode}`;
const cached = this.lineTailCache.get(cacheKey);
if (cached) {
return {
ownerBlockchainName,
lineCode,
rootHashHex,
channelSlug,
...cached,
};
}
const latest = await this.findLatestOwnLineBlock({
blockchainName,
msgType: MSG_TYPE_TEXT,
subTypes: [
MSG_SUBTYPE_TEXT_POST,
MSG_SUBTYPE_TEXT_EDIT_POST,
MSG_SUBTYPE_TEXT_REPOST,
MSG_SUBTYPE_TEXT_CHANNEL_META,
MSG_SUBTYPE_TEXT_CHANNEL_DELETE,
MSG_SUBTYPE_TEXT_ENTRYPOINT,
MSG_SUBTYPE_TEXT_EXERCISE,
MSG_SUBTYPE_TEXT_SERVICE,
MSG_SUBTYPE_TEXT_COURSE,
],
lineCode,
fixedLine: false,
stopAtBlock: lineCode,
});
const lineTail = latest
? {
prevLineNumber: latest.blockNumber,
prevLineHashHex: latest.blockHash,
thisLineNumber: latest.lineSequence + 1,
}
: {
prevLineNumber: lineCode,
prevLineHashHex: rootHashHex,
thisLineNumber: 0,
};
this.lineTailCache.set(cacheKey, lineTail);
return {
ownerBlockchainName,
lineCode,
rootHashHex,
channelSlug,
...lineTail,
};
}
rememberChannelLineTail(blockchainName, lineCode, payload, currentSequence) {
const acceptedNumber = Number(payload?.serverLastGlobalNumber);
const acceptedHash = normalizeHex32(payload?.serverLastGlobalHash, ZERO64);
if (!Number.isInteger(acceptedNumber) || acceptedNumber < 0 || acceptedHash === ZERO64) return;
this.lineTailCache.set(`${String(blockchainName || '').trim()}|channel:${Number(lineCode)}`, {
prevLineNumber: acceptedNumber,
prevLineHashHex: acceptedHash,
thisLineNumber: Number(currentSequence) + 1,
});
const heads = await this.getCoreHeads(lineCode);
if (heads.blockchainName.toLowerCase() !== blockchainName.toLowerCase() || !heads.line) throw new Error('CORE channel line not found');
const canonicalRootHash = await this.getBlockHashByNumber(blockchainName, lineCode);
if (canonicalRootHash !== rootHashHex) throw new Error('Channel root changed; refresh channel');
return { ownerBlockchainName, lineCode, rootHashHex, channelSlug,
prevLineNumber: heads.line.blockNumber, prevLineHashHex: heads.line.coreHash, thisLineNumber: 0 };
}
async addBlockTextPost({ login, channel, text, storagePwd, msgSubType = MSG_SUBTYPE_TEXT_POST }) {
@@ -2652,7 +2277,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return {
...payload,
@@ -2695,7 +2319,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return {
...payload,
@@ -2737,7 +2360,6 @@ export class AuthService {
bodyBytes,
channelSlug: tail.channelSlug,
});
this.rememberChannelLineTail(blockchainName, tail.lineCode, payload, tail.thisLineNumber);
return { ...payload, channel: { ownerBlockchainName: tail.ownerBlockchainName, channelRootBlockNumber: tail.lineCode, channelRootBlockHash: tail.rootHashHex } };
});
}
@@ -3316,9 +2938,30 @@ export class AuthService {
const cleanLogin = (login || '').trim();
if (!cleanLogin) throw new Error('Не передан login');
const response = await this.ws.request('ListUserParams', { login: cleanLogin });
if (response.status !== 200) throw opError('ListUserParams', response);
return response.payload || {};
// Profile writes are CORE events now. Do not read the Frame-era
// user_params projection: it is intentionally not updated by CORE.
const params = [];
let afterKey = '';
for (let page = 0; page < 100; page += 1) {
const response = await this.ws.request('GetCoreProfile', { login: cleanLogin, afterKey, limit: 20 });
if (response.status !== 200) throw opError('GetCoreProfile', response);
const result = response.payload?.result || {};
for (const row of Array.isArray(result.values) ? result.values : []) {
const param = String(row?.key || '').trim();
if (!param) continue;
const timestampSeconds = Number(row?.timestampSeconds);
params.push({
param,
value: String(row?.value || ''),
time_ms: Number.isSafeInteger(timestampSeconds) && timestampSeconds >= 0 ? timestampSeconds * 1000 : 0,
});
}
const nextAfterKey = String(result.nextAfterKey || '').trim();
if (!nextAfterKey) return { params };
if (nextAfterKey <= afterKey) throw new Error('Некорректная пагинация CORE-профиля');
afterKey = nextAfterKey;
}
throw new Error('Превышен лимит страниц CORE-профиля');
}
async listUserSettings(login) {
@@ -3330,53 +2973,23 @@ export class AuthService {
return response.payload || {};
}
async setChannelReadState({
login,
ownerBlockchainName,
channelName,
readCount,
timeMs,
storagePwd,
}) {
const cleanLogin = String(login || '').trim();
const cleanOwnerBch = String(ownerBlockchainName || '').trim();
const cleanChannelName = String(channelName || '').trim();
const cleanReadCount = Math.max(0, Math.trunc(Number(readCount || 0)));
const cleanTimeMs = Math.trunc(Number(timeMs));
if (!cleanLogin || !cleanOwnerBch || !cleanChannelName) {
throw new Error('Не переданы login/ownerBlockchainName/channelName');
}
if (!Number.isFinite(cleanTimeMs) || cleanTimeMs <= 0) {
throw new Error('Не передан корректный timeMs');
}
if (!storagePwd) throw new Error('Не передан storagePwd для подписи SetChannelReadState.');
const secrets = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
async setChannelReadState({ login, owner, root, rootHash, followHash, anchor, anchorHash, timeMs, storagePwd }) {
const viewer = String(login || '').trim();
const validLogin = value => typeof value === 'string' && value.length > 0 && value.length <= 128 && value === value.trim() && !/[|\x00-\x1f\x7f-\x9f]/u.test(value);
const validHash = value => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
if (!validLogin(viewer) || !validLogin(owner) || viewer.toLowerCase() === owner.toLowerCase()
|| !Number.isInteger(root) || root < 0 || !Number.isInteger(anchor) || anchor < root || anchor > 2147482623
|| ![rootHash, followHash, anchorHash].every(validHash) || !Number.isSafeInteger(timeMs) || timeMs < 0
|| !storagePwd) throw new Error('BAD_READ_STATE');
const secrets = await loadEncryptedUserSecrets(viewer, storagePwd);
const clientPrivPkcs8 = String(secrets?.clientKey || '').trim();
if (!clientPrivPkcs8) throw new Error('Не найден приватный clientKey');
const privateKey = await importPkcs8Ed25519(clientPrivPkcs8);
const clientKey = await publicKeyB64FromPkcs8Ed25519(clientPrivPkcs8);
const preimage = 'SHiNe/ChannelReadState:' + [
escapeUserSettingPart(cleanLogin),
escapeUserSettingPart(cleanOwnerBch),
escapeUserSettingPart(cleanChannelName),
String(cleanTimeMs),
String(cleanReadCount),
].join('|');
const signature = await signBase64(privateKey, preimage);
const response = await this.ws.request('SetChannelReadState', {
login: cleanLogin,
owner_bch_name: cleanOwnerBch,
channel_name: cleanChannelName,
read_count: cleanReadCount,
time_ms: cleanTimeMs,
client_key: clientKey,
signature,
});
const preimage = ['SHiNE_CORE_READ_V1', 'test5593', viewer, owner, root, rootHash, followHash, anchor, anchorHash, timeMs].join('|');
const signatureB64 = await signBase64(privateKey, preimage);
const response = await this.ws.request('SetChannelReadState', { owner, root, rootHash, followHash, anchor, anchorHash, timeMs, signatureB64 });
if (response.status !== 200) throw opError('SetChannelReadState', response);
return response.payload || {};
return response.payload?.result || {};
}
async upsertUserSetting({
@@ -3466,7 +3079,6 @@ export class AuthService {
msgVersion: 1,
bodyBytes,
});
this.rememberLineTail(blockchainName, 'profile', payload, tail.thisLineNumber);
return payload;
});
}
@@ -3503,7 +3115,6 @@ export class AuthService {
msgVersion: 1,
bodyBytes,
});
this.rememberLineTail(blockchainName, 'connections', payload, tail.thisLineNumber);
return payload;
});
}