HEADER v3, primary аккаунты и подтверждения

This commit is contained in:
AidarKC
2026-11-27 12:29:24 +03:00
parent f9e7c4ef94
commit ae430e84c7
89 changed files with 1201 additions and 1596 deletions
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { accountRoleFromHeader, confirmationRights } from '../js/services/account-voting.js';
test('only explicit HEADER V3 type 1 is Primary; no legacy fallbacks', () => {
assert.equal(accountRoleFromHeader(1), 'primary');
assert.equal(accountRoleFromHeader(0), 'non_voting');
for (const x of [undefined, null, '1', 2, true]) assert.equal(accountRoleFromHeader(x), '');
});
test('confirmation permissions match all actor and target categories', () => {
const types = [null, 0, 1];
const statuses = ['', 'shining', 'unknown', 'not_interested'];
for (const a of types) for (const b of types) for (const as of statuses) for (const bs of statuses) {
const actor = { login: 'A@free', accountRole: accountRoleFromHeader(a), shineStatus: as };
const target = { login: 'B@free', accountRole: accountRoleFromHeader(b), shineStatus: bs };
assert.deepEqual(confirmationRights(actor, target), { primary: a === 1 && b === 1, shine: a === 1 && b === 1 && as === 'shining' && bs !== 'not_interested' });
assert.deepEqual(confirmationRights(actor, { ...target, login: 'a@FREE' }), { primary: false, shine: false });
}
assert.deepEqual(confirmationRights(null, null), {primary:false,shine:false});
});
test('profile has no official toggle; both confirmation actions enforce shared rules', () => {
const src = name => readFileSync(new URL(`../js/pages/${name}`, import.meta.url), 'utf8');
const profile = src('profile-edit-view.js');
assert.match(profile, /<span class="badge is-no" data-status="account_role">/);
assert.doesNotMatch(profile, /accountRoleBtn\.addEventListener/);
const relations = src('user-relation-manage-view.js');
assert.match(relations, /confirmationRights\(selfCard, targetCard\)/);
assert.match(relations, /!rights\.primary/);
assert.match(relations, /!rights\.shine/);
});
@@ -55,7 +55,7 @@ test('при навигации старые вручную закодирова
const { toPrettyPath } = await import('../js/router.js');
assert.equal(toPrettyPath('SHiNE/innaa%40free/news/3'), 'SHiNE/innaa@free/news/3');
assert.equal(toPrettyPath('SHiNE/Prof/innaa%40free'), 'SHiNE/Prof/innaa@free');
assert.equal(toPrettyPath('chat/innaa%40free'), 'chat/innaa%40free');
assert.equal(toPrettyPath('chat/innaa%40free'), 'chat/innaa@free');
} finally {
globalThis.window = previousWindow;
}
+32
View File
@@ -0,0 +1,32 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const source = fs.readFileSync(new URL('../js/router.js', import.meta.url), 'utf8').replace(/^import .*$/gm, '').replace(/^export /gm, '');
function setup(path) {
const url = new URL(path, 'https://t2.shineup.me');
const calls = [];
const window = { location: url, history: { state: { shineFrom: '/messages' }, replaceState(state, _, value) { calls.push([state, value]); url.href = new URL(value, url).href; }, pushState(state, _, value) { url.href = new URL(value, url).href; } }, dispatchEvent() {} };
const router = vm.runInNewContext(source + '\n({toPrettyPath,getRoute,navigate})', { window, PopStateEvent: class {}, parseShineRouteParts: () => null });
return { router, window, calls };
}
test('chat navigation keeps @ visible; other escapes unchanged', () => {
const {router, window} = setup('/messages');
assert.equal(router.toPrettyPath('chat-view/qwer1%40free'), 'chat/qwer1@free');
assert.equal(router.toPrettyPath('chat/qwer1%40free/media'), 'chat/qwer1@free/media');
assert.equal(router.toPrettyPath('chat/a%40b%2Fc'), 'chat/a@b%2Fc');
assert.equal(router.toPrettyPath('settings/a%40b'), 'settings/a%40b');
router.navigate('chat-view/qwer1%40free');
assert.equal(window.location.pathname, '/chat/qwer1@free');
assert.equal(router.getRoute().params.chatId, 'qwer1@free');
});
test('direct legacy URL canonicalizes without new history entry and retains query/hash', () => {
const {router, window, calls} = setup('/chat/qwer1%40free/media?x=1#anchor');
const route = router.getRoute();
assert.equal(route.pageId, 'chat-media-view');
assert.equal(route.params.chatId, 'qwer1@free');
assert.equal(window.location.pathname, '/chat/qwer1@free/media');
assert.deepEqual(calls, [[{shineFrom:'/messages'}, '/chat/qwer1@free/media?x=1#anchor']]);
router.getRoute();
assert.equal(calls.length, 1);
});
@@ -89,3 +89,23 @@ test('Minimal pair codec and container: exact vectors, tampering, unsigned lengt
}
assert.throws(()=>unpackCoreContent(new Uint8Array(CORE_MAX_CONTAINER_BYTES+1)));
});
import { inspectBlockchainDataItem } from '../js/services/blockchain-entry-inspector.js';
test('HEADER v2 signed CORE/CONTENT and inspector accept arbitrary UTF-8 license', async () => {
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
const owner=unhex(rows[0][1]);
const login=Buffer.from('Alice@shine');
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', '\ufeffx', 'x'.repeat(255)]) {
const bytes=Buffer.from(license);
const body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(bytes.length),bytes,owner]);
const content={type:0,subType:0,version:2,body};
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content,prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null});
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
const result=await inspectBlockchainDataItem(Buffer.from(raw).toString('base64'));
assert.equal(result.frame.body.license,license);
assert.equal(result.frame.version,2);
await assert.rejects(signCoreContentPair({owner32:owner,privateKey:key,content:{...content,version:4},prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null}));
}
});
+35 -5
View File
@@ -16,21 +16,22 @@ const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeH
Uint8Array,
});
test('client writes new HEADER v1 as SHiNE → login → key', () => {
test('client writes HEADER v2 as SHiNE → login → length + license → key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine';
const body = encode({ login, initialBlockchainKey32: key });
const license = 'Лицензия 🌞';
const body = encode({ login, initialBlockchainKey32: key, license });
const loginBytes = utf8(login);
const expected = Uint8Array.from([
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
...key,
utf8(license).length, ...utf8(license), ...key,
]);
assert.deepEqual(Array.from(body), Array.from(expected));
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 1/);
assert.match(auth, /export const HEADER_VERSION = 3/);
});
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
test('inspector decodes both v1 and v2 and supports arbitrary license and rejects malformed v2', () => {
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, {
TextDecoder, DataView, Uint8Array, BigInt,
@@ -66,5 +67,34 @@ test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', ()
const invalid = bodyV2.slice();
invalid[prefix.length + 8] = 'X'.charCodeAt(0);
assert.throws(() => inspect(frameFor(2, invalid)));
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', 'x'.repeat(255)]) {
const body = encode({ login: 'Alice@shine', initialBlockchainKey32: key, license });
assert.equal(inspect(frameFor(2, body)).body.license, license);
assert.throws(() => inspect(frameFor(2, body.slice(0, -1))));
}
assert.throws(() => encode({ login: 'Alice@shine', initialBlockchainKey32: key, license: 'x'.repeat(256) }));
assert.throws(() => inspect(frameFor(2, Uint8Array.from([...prefix, 1, 255, ...key]))));
assert.throws(() => inspect(frameFor(2, new Uint8Array(0))));
});
test('HEADER v3: actual serializer and inspector agree on identity and reject malformed declarations', () => {
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
const inspect = vm.runInNewContext(`${stripped}\nparseShineFrame`, {TextDecoder, DataView, Uint8Array, BigInt, bytesToBase64Url: b => Buffer.from(b).toString('base64url'), Buffer});
const login = 'Alice@shine', key = Uint8Array.from({length:32}, (_,i)=>i+1);
const prefix = [...utf8('SHiNE'), utf8(login).length, ...utf8(login)];
const frame = body => {const a=new Uint8Array(88+body.length), v=new DataView(a.buffer);v.setUint16(0,1);v.setInt32(66,a.length);v.setUint16(86,3);a.set(body,88);return a;};
const make = (accountType,previousAccounts=[],license='')=>encode({login,initialBlockchainKey32:key,accountType,previousAccounts,license});
assert.deepEqual([...make(0)], [...prefix,0,0,...key]);
assert.deepEqual([...make(1)], [...prefix,1,0,0,0,...key]);
for(const previousAccounts of [[],['Bob@free','Older'],Array.from({length:10},(_,i)=>'old'+i+'@free')]) {
const body=make(1,previousAccounts,'Лицензия');
const parsed=inspect(frame(body)).body;
assert.equal(parsed.accountType,1);assert.deepEqual(Array.from(parsed.previousAccounts),previousAccounts);assert.equal(parsed.license,'Лицензия');
assert.throws(()=>inspect(frame(body.slice(0,-1))));
}
assert.equal(inspect(frame(make(0))).body.accountType,0);
for(const list of [['ALICE@shine'],['Bob@free','bob@free'],['a,b'],Array.from({length:11},(_,i)=>'old'+i)]) assert.throws(()=>make(1,list));
assert.throws(()=>make(0,['Bob@free']));assert.throws(()=>make(2));
const bad=make(1);bad[prefix.length]=2;assert.throws(()=>inspect(frame(bad)));
const csv=utf8('Bob@free,bob@free');assert.throws(()=>inspect(frame(Uint8Array.from([...prefix,1,0,csv.length,...csv,0,...key]))));
});
@@ -68,7 +68,7 @@ test('HEADER и PostgreSQL требуют неизменяемого регис
const handler = readFileSync(new URL('../../SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler.java', import.meta.url), 'utf8');
const header = readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/body/HeaderBody.java', import.meta.url), 'utf8');
const migration = readFileSync(new URL('../../SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v37.sql', import.meta.url), 'utf8');
assert.match(client, /bodyBytes: makeHeaderBodyBytes\(\{ login: registeredLogin, initialBlockchainKey32 \}\)/);
assert.match(client, /bodyBytes: makeHeaderBodyBytes\(\{ login: registeredLogin, initialBlockchainKey32, license: HEADER_DEFAULT_LICENSE, accountType: identity\.accountType, previousAccounts: identity\.previousAccounts \}\)/);
assert.doesNotMatch(client, /makeHeaderBodyBytes\(\{ login: cleanLogin\.toLowerCase\(\)/);
assert.match(handler, /headerBody\.login\.equals\(registeredOwner\.getLogin\(\)\)/);
assert.match(header, /\[A-Za-z0-9_\]\+@\[a-z0-9_\]\+/);
+11
View File
@@ -35,3 +35,14 @@ test('viewer: requests CORE then CONTENT by ID and never claims signature verifi
ctx.fetch=async url=>url.endsWith(cid)?{ok:false,status:404}:{ok:true,arrayBuffer:async()=>bytes(f.core).buffer};
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
});
test('viewer: parses historical v2 and v3 primary declaration',async()=>{
const f=find('header'), old=bytes(f.content), key=old.slice(-32), prefix=old.slice(7,-32);
const csv=new TextEncoder().encode('Bob@free,Older');
for(const [version,body,role] of [[2,[...prefix,0,...key],null],[3,[...prefix,0,0,...key],0],[3,[...prefix,1,0,csv.length,...csv,0,...key],1]]){
const content=Uint8Array.from([1,0,0,0,0,0,version,...body]),core=bytes(f.core);
core.set(new Uint8Array(await webcrypto.subtle.digest('SHA-256',content)),45);
const result=await v.parseBlockchainBlock(core,content);
assert.equal(result.body.accountType,role);assert.equal(result.body.license,'');
assert.deepEqual(Array.from(result.body.previousAccounts),role===1?['Bob@free','Older']:[]);
}
});
@@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {savePendingHeaderIdentity,readPendingHeaderIdentity,clearPendingHeaderIdentity} from '../js/services/pending-header-identity.js';
test('pending HEADER declaration survives module reload and remains bound to login and key',async()=>{
const m=new Map();globalThis.localStorage={setItem:(k,v)=>m.set(k,v),getItem:k=>m.get(k),removeItem:k=>m.delete(k)};
const declaration={accountType:1,previousAccounts:['Bob@free']};
savePendingHeaderIdentity('Alice@shine','a+/=',declaration);
const fresh=await import('../js/services/pending-header-identity.js?reload');
assert.deepEqual(fresh.readPendingHeaderIdentity('alice@shine','a-_'),declaration);
assert.equal(fresh.readPendingHeaderIdentity('alice@shine','other'),null);
assert.equal(fresh.readPendingHeaderIdentity('bob@shine','a-_'),null);
clearPendingHeaderIdentity('Alice@shine','a+/=');
assert.equal(fresh.readPendingHeaderIdentity('alice@shine','a-_'),null);
delete globalThis.localStorage;
});
+29
View File
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { publicLikeCount, hasLikeStatistics } from '../js/services/public-like-count.js';
test('public likes only count declared Primary accounts', () => {
const post = { likesCount: 20, primaryLikesCount: 5, shiningLikesCount: 2 };
assert.equal(publicLikeCount(post), 5);
assert.equal(hasLikeStatistics(post), true);
assert.equal(publicLikeCount({ likesCount: 20, primaryLikesCount: 0 }), 0);
assert.equal(hasLikeStatistics({ likesCount: 20, primaryLikesCount: 0 }), true);
assert.equal(publicLikeCount({ likesCount: 20 }), 0);
assert.equal(publicLikeCount({ primaryLikesCount: -1 }), 0);
assert.equal(publicLikeCount({ primaryLikesCount: 'invalid' }), 0);
assert.equal(hasLikeStatistics({ likesCount: 0, primaryLikesCount: 0 }), false);
});
test('feed and both thread layouts use the public count and keep stats accessible', () => {
const src = name => readFileSync(new URL(`../js/pages/${name}`, import.meta.url), 'utf8');
const feed = src('channel-view.js');
const thread = src('channel-thread-view.js');
assert.match(feed, /likesStatsButton\.textContent = String\(publicLikeCount\(post\)\)/);
assert.equal((feed.match(/hasLikeStatistics\(post\) \? \[likesStatsButton\]/g) || []).length, 2);
assert.equal((thread.match(/const likes = publicLikeCount\(node\);/g) || []).length, 2);
assert.match(thread, /commentLikeStats\.textContent = String\(likes\)/);
assert.equal((thread.match(/hasLikeStatistics\(node\)/g) || []).length, 3);
assert.match(feed, /counts: post/);
assert.match(thread, /showLikeStatistics\(\{ counts: node \}\)/);
});
@@ -24,17 +24,18 @@ const context = {
};
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('CORE/CONTENT HEADER v1 contains login and initial key without CC0', () => {
test('CORE/CONTENT HEADER v2 contains login, empty license and 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.deepEqual(Array.from(result.slice(6+login.length)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 32);
assert.deepEqual(Array.from(result.slice(7+login.length)), Array.from(key));
assert.equal(result[6+login.length], 0);
assert.equal(result.length, 5 + 1 + login.length + 1 + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 1/);
assert.match(auth, /export const HEADER_VERSION = 3/);
});
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {
@@ -53,7 +53,7 @@ async function simulateCompletion({ headerFails = false } = {}) {
const calls = [];
const state = {
entrySettings: { shineServer: 'wss://test.invalid' },
registrationDraft: { login: 'AlexSmith@shine', password: 'secret' },
registrationDraft: { login: 'AlexSmith@shine', password: 'secret', accountType: 1, previousAccounts: ['old@free'] },
loginDraft: {},
registrationPayment: {},
authReturnHash: '',
@@ -64,7 +64,10 @@ async function simulateCompletion({ headerFails = false } = {}) {
async createSessionForExistingUser() {
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session', sessionMaterial: {} };
},
async persistSelectedKeys() {},
async persistSelectedKeys(login, pwd, bundle, options) {
assert.equal(options.headerIdentity.accountType, 1);
assert.deepEqual(Array.from(options.headerIdentity.previousAccounts), ['old@free']);
},
async persistSessionMaterial() {},
async resumeSession() {
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session' };
@@ -3,7 +3,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
const read = relative => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8'));
test('выбор аккаунта перед шагом 1, всего три шага', () => {
test('выбор тарифа перед шагом 1, всего четыре шага', () => {
const choice = read('../js/pages/registration-choice-view.js');
const login = read('../js/pages/register-view.js');
const email = read('../js/pages/registration-email-view.js');
@@ -11,8 +11,9 @@ test('выбор аккаунта перед шагом 1, всего три ш
assert.doesNotMatch(choice, /createRegistrationStepper\(/);
assert.match(login, /createRegistrationStepper\(1\)/);
assert.match(login, /createRegistrationStepper\(2\)/);
assert.match(email, /createRegistrationStepper\(3\)/);
assert.match(payment, /createRegistrationStepper\(3\)/);
assert.match(login, /createRegistrationStepper\(3\)/);
assert.match(email, /createRegistrationStepper\(4\)/);
assert.match(payment, /createRegistrationStepper\(4\)/);
});
test('реальная почта и 256-символьный лимит сохранены', () => {
const email = read('../js/pages/registration-email-view.js');