SHA256
Проверить вложения и блоки в каналах
This commit is contained in:
@@ -201,3 +201,14 @@ export async function createAns104DataItemWithRawParts({
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** Проверка исходной подписи ANS-104 локально, без доверия к серверному статусу. */
|
||||
export async function verifyAns104DataItem(rawBytes) {
|
||||
const item = parseAns104DataItem(rawBytes);
|
||||
const signedMessage = await ans104SigningMessageRaw(item);
|
||||
const key = await crypto.subtle.importKey('raw', item.owner32, { name: 'Ed25519' }, false, ['verify']);
|
||||
const signatureValid = await crypto.subtle.verify('Ed25519', key, item.signature, signedMessage);
|
||||
const idHash = await digest('SHA-256', item.signature);
|
||||
const frameHash = await digest('SHA-256', item.data);
|
||||
return { ...item, signatureValid, dataItemIdBytes: idHash, frameHashBytes: frameHash };
|
||||
}
|
||||
|
||||
@@ -7,7 +7,11 @@ import { resolvePublicFileUrl } from './public-file-service.js';
|
||||
import { updatedUserFileUrlAfterError } from './user-file-server-service.js';
|
||||
import { validatePublicPiecesRoot } from './public-pieces-root.js';
|
||||
|
||||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>]*)>\n?/u;
|
||||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>\n]{1,2048})>\n?/u;
|
||||
// В v=2 ASCII-разделители и управляющие синтаксисом символы экранируются, UTF-8 остаётся как есть.
|
||||
const V2_RESERVED = /[%<>=;\r\n]/g;
|
||||
const V2_ESCAPE = { '%': '%25', '<': '%3C', '>': '%3E', '=': '%3D', ';': '%3B', '\r': '%0D', '\n': '%0A' };
|
||||
const ATTACH_ALLOWED_FIELDS = new Set(['v', 'nm', 'sz', 'pr', 'sha256', 'mm', 'ar']);
|
||||
export const MAX_MESSAGE_ATTACHMENTS = 10;
|
||||
const RECENT_UNAVAILABLE_MS = 20 * 60 * 1000;
|
||||
const IMAGE_EXTENSIONS = new Set(['apng', 'avif', 'bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
|
||||
@@ -49,21 +53,22 @@ export function normalizeAttachment(input = {}) {
|
||||
const mm = String(input.mm || '').trim();
|
||||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||||
if (new TextEncoder().encode(name).length > 255) throw new Error('Имя файла превышает 255 байт UTF-8');
|
||||
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
||||
if (!validatePublicPiecesRoot(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
|
||||
if (pr && !validatePublicPiecesRoot(pr)) throw new Error('Некорректный Pieces Root');
|
||||
if (mm && (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(mm) || mm.length > 127)) throw new Error('Некорректный MIME');
|
||||
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
||||
return { v: 1, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||||
return { v: 2, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||||
}
|
||||
|
||||
export function buildAttachmentBlock(attachment) {
|
||||
const item = normalizeAttachment(attachment);
|
||||
const encodedName = encodeURIComponent(item.name);
|
||||
const encodedName = item.name.replace(V2_RESERVED, (char) => V2_ESCAPE[char]);
|
||||
const id = item.pr ? `;pr=${item.pr}` : `;sha256=${item.sha256}`;
|
||||
const mmPart = item.mm ? `;mm=${item.mm}` : '';
|
||||
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
||||
return `<S:att;v=1;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||||
return `<S:att;v=2;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||||
}
|
||||
|
||||
export function composeMessageWithAttachments(text, attachments = []) {
|
||||
@@ -76,15 +81,33 @@ export function composeMessageWithAttachments(text, attachments = []) {
|
||||
}
|
||||
|
||||
function parseFields(rawFields) {
|
||||
const out = {};
|
||||
String(rawFields || '').split(';').forEach((part) => {
|
||||
const parts = String(rawFields || '').split(';');
|
||||
const fields = Object.create(null);
|
||||
// Для v=1 сохраняем прежний мягкий разбор. Для v=2 — строгое правило полей.
|
||||
const strict = parts.some((part) => /^v\s*=\s*(?:0*2)$/u.test(part));
|
||||
for (const part of parts) {
|
||||
const eq = part.indexOf('=');
|
||||
if (eq <= 0) return;
|
||||
if (eq <= 0) {
|
||||
if (strict) throw new Error('Некорректное поле вложения');
|
||||
continue;
|
||||
}
|
||||
const key = part.slice(0, eq).trim();
|
||||
const value = part.slice(eq + 1).trim();
|
||||
if (key) out[key] = value;
|
||||
});
|
||||
return out;
|
||||
if (strict && (!ATTACH_ALLOWED_FIELDS.has(key) || Object.hasOwn(fields, key))) {
|
||||
throw new Error('Дублированное либо неизвестное поле вложения');
|
||||
}
|
||||
if (key) fields[key] = value;
|
||||
}
|
||||
if (strict) {
|
||||
if (!fields.nm || !fields.sz || !(fields.pr || fields.sha256) || (fields.pr && fields.sha256)) {
|
||||
throw new Error('Отсутствует обязательное поле вложения');
|
||||
}
|
||||
if (!/^(?:[^%]|%(?:25|3[bBcCdDeE]|0[aAdD]))*$/u.test(fields.nm)) {
|
||||
// Неизвестные и неполные %-коды запрещаем; это исключает неоднозначное толкование.
|
||||
throw new Error('Неканоническое экранирование имени файла');
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
export function parseMessageAttachments(rawText) {
|
||||
@@ -94,14 +117,20 @@ export function parseMessageAttachments(rawText) {
|
||||
while (true) {
|
||||
const match = rest.match(ATTACH_BLOCK_RE);
|
||||
if (!match) break;
|
||||
const fields = parseFields(match[2]);
|
||||
try {
|
||||
const fields = parseFields(match[2]);
|
||||
const version = Number(fields.v || 0);
|
||||
if (version !== 1 && version !== 2) {
|
||||
throw new Error('unsupported attachment version');
|
||||
}
|
||||
if (version === 2 && (!fields.v || fields.v !== '2')) throw new Error('Неканоническая версия');
|
||||
if (version === 2 && (/[<>=;]/u.test(fields.nm) || !/^[1-9][0-9]*$/u.test(fields.sz))) {
|
||||
throw new Error('Неканонические поля вложения');
|
||||
}
|
||||
const name = decodeURIComponent(String(fields.nm || fields.name || 'file'));
|
||||
if (version === 2 && /[\u0000-\u001f\u007f]/u.test(name)) throw new Error('Управляющий символ в имени файла');
|
||||
attachments.push(normalizeAttachment({
|
||||
nm: decodeURIComponent(String(fields.nm || fields.name || 'file')),
|
||||
nm: name,
|
||||
sz: fields.sz || fields.size,
|
||||
sha256: fields.sha256,
|
||||
pr: fields.pr,
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { verifyAns104DataItem } from './ans104-data-item.js';
|
||||
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
|
||||
import { readShineUserPda } from './shine-user-pda-service.js';
|
||||
|
||||
const HASH_RE = /^[0-9a-f]{64}$/iu;
|
||||
const DATA_ITEM_ID_RE = /^[A-Za-z0-9_-]{43}$/u;
|
||||
const MAX_SIGNED_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
function hex(bytes) {
|
||||
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function equalBytes(left, right) {
|
||||
return left.length === right.length && left.every((byte, index) => byte === right[index]);
|
||||
}
|
||||
export function arweaveBlockUrl(id) {
|
||||
return DATA_ITEM_ID_RE.test(String(id || '')) ? `https://arweave.net/raw/${id}` : '';
|
||||
}
|
||||
export function signedDataItemFilename(chain, number) {
|
||||
const safe = String(chain || 'block').replace(/[^a-z0-9@._-]/giu, '_').slice(0, 100);
|
||||
return `SHiNE-${safe}-${Number(number)}.ans104`;
|
||||
}
|
||||
|
||||
/** Получаем полный оригинал по существующему публичному API (не «от Arweave»). */
|
||||
export async function readSignedBlock({ authService, blockchainName, blockNumber, blockHash, dataItemId }) {
|
||||
const resp = await authService.ws.request('GetBlockchainBlock', { blockchainName, blockNumber });
|
||||
if (Number(resp?.status) !== 200) throw new Error('GetBlockchainBlock: блок недоступен');
|
||||
const body = resp?.payload || resp;
|
||||
if (!HASH_RE.test(String(body?.blockHash || '')) || String(body.blockHash).toLowerCase() !== String(blockHash).toLowerCase()) {
|
||||
throw new Error('Сервер вернул другой хеш блока');
|
||||
}
|
||||
const rawText = String(body?.blockBytesB64 || '');
|
||||
if (rawText.length > Math.ceil(MAX_SIGNED_BYTES * 4 / 3) + 8) throw new Error('Размер подписанного блока превышает лимит');
|
||||
const bytes = base64ToBytes(rawText);
|
||||
if (!bytes.length || bytes.length > MAX_SIGNED_BYTES) throw new Error('Некорректный размер блока');
|
||||
const proof = await verifyAns104DataItem(bytes);
|
||||
if (!proof.signatureValid) throw new Error('Недействительная подпись ANS-104');
|
||||
if (hex(proof.frameHashBytes) !== String(blockHash).toLowerCase()) throw new Error('Хеш содержимого блока не совпал');
|
||||
const actualId = bytesToBase64Url(proof.dataItemIdBytes);
|
||||
if (dataItemId && actualId !== dataItemId) throw new Error('Идентификатор Arweave отличается от ожидаемого');
|
||||
return { bytes, ...proof, actualId };
|
||||
}
|
||||
|
||||
/** Вспомогательная независимая сверка: шлюз возвращает payload, а не ANS-104 оболочку. */
|
||||
export async function checkArweavePayload(dataItemId, signedPayload) {
|
||||
const url = arweaveBlockUrl(dataItemId);
|
||||
if (!url) return { status: 'unavailable', reason: 'Нет идентификатора Arweave' };
|
||||
try {
|
||||
const response = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(15000) });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const length = Number(response.headers.get('Content-Length') || 0);
|
||||
if (length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
||||
const raw = new Uint8Array(await response.arrayBuffer());
|
||||
if (raw.length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
||||
return equalBytes(raw, signedPayload)
|
||||
? { status: 'valid' }
|
||||
: { status: 'invalid', reason: 'Содержимое Arweave не совпадает с подписанным блоком' };
|
||||
} catch (error) {
|
||||
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkSolanaAuthor({ authorLogin, blockchainName, owner32, solanaEndpoint }) {
|
||||
const forkMatch = String(blockchainName || '').match(/-(\d{3})$/u);
|
||||
const forkIndex = forkMatch ? Number(forkMatch[1]) - 1 : -1;
|
||||
if (forkIndex < 0 || !authorLogin || !solanaEndpoint) {
|
||||
return { status: 'unavailable', reason: 'Недостаточно данных для проверки Solana' };
|
||||
}
|
||||
try {
|
||||
const pda = await readShineUserPda({ login: authorLogin, solanaEndpoint });
|
||||
const key = pda?.forks?.[forkIndex]?.blockchainKey;
|
||||
if (!key) return { status: 'unavailable', reason: 'Исторический ключ форка отсутствует в PDA' };
|
||||
return equalBytes(new Uint8Array(key), owner32)
|
||||
? { status: 'valid', reason: `Solana PDA, форк ${forkMatch[1]}` }
|
||||
: { status: 'invalid', reason: 'Ключ подписанта не совпадает с ключом форка в Solana PDA' };
|
||||
} catch (error) {
|
||||
// FREE_CERT может не иметь PDA: это не доказательство подделки.
|
||||
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user