Перевести вложения DM на R2 и обновить файловый API

This commit is contained in:
AidarKC
2026-11-15 14:33:52 +03:00
parent 3ecec25fce
commit 70540ff041
23 changed files with 770 additions and 202 deletions
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { validatePublicPiecesRoot } from '../js/services/public-pieces-root.js';
const source = await readFile(new URL('../js/services/attachment-format.js', import.meta.url), 'utf8');
@@ -52,7 +53,7 @@ function loadRenderer() {
.replace(/^import .*;\s*$/gm, '')
.replace(/^export /gm, '');
const factory = new Function('t', 'th', 'formatNumber', 'openMediaViewer', 'buildArweaveDataUrl',
'validateArweaveTxId', 'validateSha256Hex', 'resolvePublicFileUrl', 'document', 'window', 'fetch',
'validateArweaveTxId', 'validateSha256Hex', 'resolvePublicFileUrl', 'validatePublicPiecesRoot', 'document', 'window', 'fetch',
`${normalized}\nreturn { getAttachmentKind, createAttachmentCarouselElement, parseMessageAttachments };`);
const api = factory(
(key) => key,
@@ -63,6 +64,7 @@ function loadRenderer() {
(id) => /^[A-Za-z0-9_-]{43}$/.test(id),
(id) => /^[a-f0-9]{64}$/.test(id),
async ({ pr, sha256 }) => pr ? `https://files.shineup.me/${pr}` : `https://old.example/files/${sha256}`,
validatePublicPiecesRoot,
{ createElement: (tag) => new TestElement(tag) },
{ location: { origin: 'https://shineup.me' }, open() {} },
async () => ({ ok: true }),
@@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { encodePublicPiecesRoot, validatePublicPiecesRoot } from '../js/services/public-pieces-root.js';
import { preparePublicFile } from '../js/services/file-preparation-service.js';
import { publicR2Url } from '../js/services/public-file-service.js';
import { buildAttachmentBlock, parseMessageAttachments, normalizeAttachment } from '../js/services/attachment-format.js';
import { computeTorrentV2PieceRoot } from '../js/services/torrent-v2-service.js';
test('Base58-кодирование публичного PR: 32 байта, в том числе ведущие нули', () => {
const vectors = [
[0, '1'.repeat(32)],
[1, '4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi'],
[255, 'JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG'],
];
for (const [value, expected] of vectors) {
assert.equal(encodePublicPiecesRoot(new Uint8Array(32).fill(value)), expected);
assert.equal(validatePublicPiecesRoot(expected), true);
assert.equal(publicR2Url(expected), `https://files.shineup.me/${expected}`);
}
assert.throws(() => encodePublicPiecesRoot(new Uint8Array(31)));
});
test('не принимает старый Base64URL, некорректные символы, длину и ненормализованные значения', () => {
for (const invalid of [
'', 'A'.repeat(42) + '_', 'A'.repeat(42) + '-', 'A'.repeat(43) + '=',
'0'.repeat(44), 'O'.repeat(44), 'I'.repeat(44), 'l'.repeat(44),
'A'.repeat(31), 'A'.repeat(45), '1'.repeat(33), ` ${'1'.repeat(32)}`,
]) {
assert.equal(validatePublicPiecesRoot(invalid), false, invalid);
assert.throws(() => publicR2Url(invalid), invalid);
}
});
test('подготовка публичного файла создаёт BitTorrent v2 PR именно в Base58', async () => {
const bytes = Uint8Array.from([10, 20, 30, 40, 50, 60, 70]);
const file = new File([bytes], 'photo.png', { type: 'image/png' });
const prepared = await preparePublicFile(file);
const expectedMerkleRoot = await computeTorrentV2PieceRoot(bytes);
assert.equal(prepared.pr, encodePublicPiecesRoot(expectedMerkleRoot));
assert.equal(validatePublicPiecesRoot(prepared.pr), true);
assert.equal(prepared.mm, 'image/png');
assert.equal(prepared.size, bytes.length);
});
test('публичный S:att сохраняет PR в Base58 без перекодирования, включая Arweave', () => {
for (const value of [0, 1, 255]) {
const pr = encodePublicPiecesRoot(new Uint8Array(32).fill(value));
const attachment = { name: 'photo.jpg', size: 100, pr, mm: 'image/jpeg', ar: '' };
const encoded = buildAttachmentBlock(attachment);
assert.match(encoded, new RegExp(`;pr=${pr};mm=image/jpeg>`));
const decoded = parseMessageAttachments(`${encoded}\nТекст`);
assert.equal(decoded.attachments.length, 1);
assert.equal(decoded.attachments[0].pr, pr);
assert.equal(decoded.text, 'Текст');
assert.equal(normalizeAttachment({ ...attachment, ar: 'A'.repeat(43) }).ar, 'A'.repeat(43));
}
const legacyEncoded = `<S:att;v=1;nm=photo.jpg;sz=100;pr=${'A'.repeat(42)}_>`;
assert.equal(parseMessageAttachments(legacyEncoded).attachments.length, 0);
});