SHA256
Добавить лицензию CC0 1.0
This commit is contained in:
@@ -42,7 +42,7 @@ test('avatar R2 upload reuses signed public PR prepare; no avatar-specific endpo
|
||||
assert.match(service, /\/api\/files\/prepare/);
|
||||
assert.doesNotMatch(service, /\/api\/avatars\/prepare/);
|
||||
assert.doesNotMatch(service, /avatars\/\$\{/);
|
||||
assert.match(source('js/components/avatar-image.js'), /img\.src = avatarR2Url\(expectedPr\)/);
|
||||
assert.match(source('js/pages/network/graph-canvas.js'), /avatarR2Url\(pr\)/);
|
||||
assert.match(source('js/pages/network-legacy/force-graph.js'), /avatarR2Url\(pr\)/);
|
||||
assert.match(source('js/components/avatar-image.js'), /resolvePublicFileUrl\(\{ pr: expectedPr, authorLogin \}\)/);
|
||||
assert.match(source('js/pages/network/graph-canvas.js'), /resolvePublicFileUrl\(\{ pr, authorLogin \}\)/);
|
||||
assert.match(source('js/pages/network-legacy/force-graph.js'), /resolvePublicFileUrl\(\{ pr, authorLogin \}\)/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { state } from '../js/state.js';
|
||||
import {
|
||||
clearUserFileServerCache, getUserFileServer, resolveUserFileUrl,
|
||||
refreshUserFileServerOnError, updatedUserFileUrlAfterError, userFileObjectUrl,
|
||||
SERVER_LOOKUP_COOLDOWN_MS,
|
||||
} from '../js/services/user-file-server-service.js';
|
||||
import { buildDmFileTechBlock, parseDmTechBlocks } from '../js/services/dm-tech-blocks.js';
|
||||
import { DM_FILE_RETENTION_MS, isDmFileExpired } from '../js/services/dm-file-service.js';
|
||||
import { encodePublicPiecesRoot } from '../js/services/public-pieces-root.js';
|
||||
|
||||
const login = 'anna@shine';
|
||||
const id = encodePublicPiecesRoot(new Uint8Array(32).fill(7));
|
||||
|
||||
// Чистим RAM-кэш между сценариями: без IndexedDB, localStorage и таймеров.
|
||||
test('федерация: единый API, один параллельный запрос, правильные файловые домены', async () => {
|
||||
clearUserFileServerCache();
|
||||
state.entrySettings.shineServerHttp = 'https://reader.example.com';
|
||||
const originalFetch = globalThis.fetch;
|
||||
const requests = [];
|
||||
globalThis.fetch = async (url) => {
|
||||
requests.push(url);
|
||||
return { ok: true, json: async () => ({ serverLogin: 'node-b@shine', serverUrl: 'https://node-b.example.net/ws' }) };
|
||||
};
|
||||
try {
|
||||
const results = await Promise.all(Array.from({ length: 12 }, () => getUserFileServer(login)));
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0], 'https://reader.example.com/api/files/user-server?login=anna%40shine');
|
||||
assert.equal(results[0].hostname, 'node-b.example.net');
|
||||
assert.equal(await resolveUserFileUrl({ login, id }), `https://files.node-b.example.net/${id}`);
|
||||
assert.equal(await resolveUserFileUrl({ login, id, kind: 'dm' }), `https://dm-files.node-b.example.net/${id}`);
|
||||
assert.equal(requests.length, 1);
|
||||
} finally { globalThis.fetch = originalFetch; clearUserFileServerCache(); }
|
||||
});
|
||||
|
||||
test('федерация: Solana server_address может быть WSS с портом и путём', async () => {
|
||||
clearUserFileServerCache();
|
||||
state.entrySettings.shineServerHttp = 'https://reader.example.com';
|
||||
const savedFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({
|
||||
serverLogin: 'node@shine', serverUrl: 'wss://node.example.com:8443/ws',
|
||||
}) });
|
||||
try {
|
||||
assert.equal(await resolveUserFileUrl({ login, id, kind: 'public' }), `https://files.node.example.com/${id}`);
|
||||
assert.equal(await resolveUserFileUrl({ login, id, kind: 'dm' }), `https://dm-files.node.example.com/${id}`);
|
||||
} finally { globalThis.fetch = savedFetch; clearUserFileServerCache(); }
|
||||
});
|
||||
|
||||
test('федерация: проверка при ошибке не чаще одного раза в час и только при смене адреса', async () => {
|
||||
clearUserFileServerCache();
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalNow = Date.now;
|
||||
let now = 100_000_000;
|
||||
let calls = 0;
|
||||
let address = 'server-a.example.com';
|
||||
Date.now = () => now;
|
||||
globalThis.fetch = async () => { calls++; return { ok: true, json: async () => ({ serverLogin: 's@shine', serverUrl: address }) }; };
|
||||
try {
|
||||
const first = userFileObjectUrl(await getUserFileServer(login), id);
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(await updatedUserFileUrlAfterError({ login, id, previousUrl: first }), null);
|
||||
assert.equal(calls, 1);
|
||||
now += SERVER_LOOKUP_COOLDOWN_MS + 1;
|
||||
address = 'server-b.example.com';
|
||||
const responses = await Promise.all(Array.from({ length: 12 }, () => refreshUserFileServerOnError(login)));
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(responses[0].hostname, 'server-b.example.com');
|
||||
assert.equal(await updatedUserFileUrlAfterError({ login, id, previousUrl: first }), `https://files.server-b.example.com/${id}`);
|
||||
assert.equal(calls, 2);
|
||||
} finally { Date.now = originalNow; globalThis.fetch = originalFetch; clearUserFileServerCache(); }
|
||||
});
|
||||
|
||||
test('DM v3: новые сообщения не содержат адреса, прежний v3 с URL продолжает читаться', () => {
|
||||
const base = { version: 3, id, url: `https://dm-files.shineup.me/${id}`,
|
||||
keyB64Url: 'AQID', ivPrefixB64Url: 'AQID',
|
||||
name: 'photo.png', mime: 'image/png', size: 123, encryptedSize: 139,
|
||||
chunkSize: 8388608, chunkCount: 1, kind: 'file', uploadedAtMs: 1005000 };
|
||||
const text = buildDmFileTechBlock(base);
|
||||
assert.doesNotMatch(text, /;url=/);
|
||||
const parsed = parseDmTechBlocks(text).fileAttachment;
|
||||
assert.equal(parsed.id, id);
|
||||
assert.equal(parsed.uploadedAtMs, base.uploadedAtMs);
|
||||
assert.equal(parsed.url, '');
|
||||
const oldText = text.replace(`;id=${id}`, `;id=${id};url=${encodeURIComponent(base.url)}`);
|
||||
assert.equal(parseDmTechBlocks(oldText).fileAttachment.url, base.url);
|
||||
});
|
||||
|
||||
test('R2 DM v3: после 14 дней не пробуем скачивание; старые legacy v2 без R2 TTL', () => {
|
||||
const now = Date.now();
|
||||
assert.equal(isDmFileExpired({ version: 3, uploadedAtMs: now - DM_FILE_RETENTION_MS - 1 }), true);
|
||||
assert.equal(isDmFileExpired({ version: 3, uploadedAtMs: now - DM_FILE_RETENTION_MS + 60_000 }), false);
|
||||
assert.equal(isDmFileExpired({ version: 3, messageTimestampMs: now - DM_FILE_RETENTION_MS - 1 }), true);
|
||||
assert.equal(isDmFileExpired({ version: 2, messageTimestampMs: now - 2 * DM_FILE_RETENTION_MS }), false);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const read = path => fs.readFileSync(new URL(path, import.meta.url), 'utf8');
|
||||
const auth = read('../js/services/auth-service.js');
|
||||
const inspector = read('../js/services/blockchain-entry-inspector.js');
|
||||
const source = auth.split('function makeHeaderBodyBytes(')[1]?.split('\nfunction makeUserParamBodyBytes(')[0];
|
||||
assert.ok(source, 'production makeHeaderBodyBytes must exist');
|
||||
const utf8 = value => new TextEncoder().encode(value);
|
||||
const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeHeaderBodyBytes`, {
|
||||
utf8Bytes: utf8,
|
||||
int8Byte: value => Uint8Array.of(value),
|
||||
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
|
||||
Uint8Array,
|
||||
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
|
||||
});
|
||||
|
||||
test('client writes HEADER v2 as SHiNE → login → literal license → key', () => {
|
||||
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
|
||||
const login = 'Alice@shine';
|
||||
const body = encode({ login, initialBlockchainKey32: key });
|
||||
const loginBytes = utf8(login);
|
||||
const expected = Uint8Array.from([
|
||||
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
|
||||
...utf8('license:CC0-1.0'), ...key,
|
||||
]);
|
||||
assert.deepEqual(Array.from(body), Array.from(expected));
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
|
||||
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
|
||||
});
|
||||
|
||||
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
|
||||
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
|
||||
const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, {
|
||||
TextDecoder, DataView, Uint8Array, BigInt,
|
||||
bytesToBase64Url: bytes => Buffer.from(bytes).toString('base64url'),
|
||||
Buffer,
|
||||
});
|
||||
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
|
||||
const login = utf8('Alice@shine');
|
||||
const prefix = Uint8Array.from([...utf8('SHiNE'), login.length, ...login]);
|
||||
const bodyV1 = Uint8Array.from([...prefix, ...key]);
|
||||
const bodyV2 = Uint8Array.from([...prefix, ...utf8('license:CC0-1.0'), ...key]);
|
||||
const frameFor = (version, body) => {
|
||||
const frame = new Uint8Array(88 + body.length);
|
||||
const view = new DataView(frame.buffer);
|
||||
view.setUint16(0, 1, false); // frameCode
|
||||
view.setInt32(66, frame.length, false);
|
||||
view.setInt32(70, 0, false); // blockNumber
|
||||
view.setBigInt64(74, 0n, false);
|
||||
view.setUint16(82, 0, false); // type TECH
|
||||
view.setUint16(84, 0, false); // subtype HEADER
|
||||
view.setUint16(86, version, false);
|
||||
frame.set(body, 88);
|
||||
return frame;
|
||||
};
|
||||
const old = inspect(frameFor(1, bodyV1));
|
||||
assert.equal(old.body.kind, 'header');
|
||||
assert.equal(old.body.license, null);
|
||||
const current = inspect(frameFor(2, bodyV2));
|
||||
assert.equal(current.body.kind, 'header');
|
||||
assert.equal(current.body.license, 'CC0-1.0');
|
||||
assert.equal(current.body.initialBlockchainKey, Buffer.from(key).toString('base64url'));
|
||||
assert.throws(() => inspect(frameFor(2, Uint8Array.from([...prefix, ...key, ...utf8('license:CC0-1.0')]))));
|
||||
const invalid = bodyV2.slice();
|
||||
invalid[prefix.length + 8] = 'X'.charCodeAt(0);
|
||||
assert.throws(() => inspect(frameFor(2, invalid)));
|
||||
assert.throws(() => inspect(frameFor(2, new Uint8Array(0))));
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
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 = {
|
||||
utf8Bytes: value => new TextEncoder().encode(value),
|
||||
int8Byte: value => Uint8Array.of(value),
|
||||
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
|
||||
Uint8Array,
|
||||
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
|
||||
};
|
||||
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
|
||||
|
||||
test('HEADER v2 places literal license:CC0-1.0 before the 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');
|
||||
assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE');
|
||||
assert.equal(result[5], login.length);
|
||||
assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login));
|
||||
assert.equal(new TextDecoder().decode(result.slice(6+login.length, 6+login.length+15)), 'license:CC0-1.0');
|
||||
assert.deepEqual(Array.from(result.slice(6+login.length+15)), Array.from(key));
|
||||
assert.equal(result.length, 5 + 1 + login.length + 15 + 32);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
|
||||
assert.match(auth, /export const HEADER_VERSION_CC0 = 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/);
|
||||
});
|
||||
Reference in New Issue
Block a user