Files
SHiNE-server/shine-UI/tests/core-content-readers.test.mjs
T

92 lines
7.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { decodeCore, readCoreBlock } from '../js/services/core-content.js';
import { inspectCoreBlock } from '../js/services/blockchain-entry-inspector.js';
import { readSignedBlock } from '../js/services/blockchain-proof-service.js';
import { AuthService } from '../js/services/auth-service.js';
import { saveEncryptedUserSecrets } from '../js/services/key-vault.js';
import { canonicalReadPosts, readPrefixCount } from '../js/services/channel-message-ordinals.js';
import { buildBlockchainSnapshotFile } from '../js/services/shine-blockchain-snapshot-service.js';
const b64 = hex => Buffer.from(hex,'hex').toString('base64');
const id = hex => Buffer.from(hex,'hex').toString('base64url');
const fixtures = fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url),'utf8').trim().split('\n').slice(1).map(line => line.split('\t'));
const rows = fixtures.map(([name,owner,core,coreHash,content,contentHash,coreItem,coreItemId,contentItem,contentItemId]) => ({name,blockNumber:decodeCore(Uint8Array.from(Buffer.from(core,'hex'))).blockNumber,coreHash,contentHash,coreDataItemId:id(coreItemId),contentDataItemId:id(contentItemId),coreDataItemB64:b64(coreItem),contentDataItemB64:b64(contentItem),contentStatus:'VALID'}));
test('signed CORE reader and existing semantic inspector decode all external vectors', async () => {
for (const row of rows) {
const p = await readCoreBlock(row,{requireContent:true});
const inspection = await inspectCoreBlock(row);
assert.equal(p.actualId,row.coreDataItemId,row.name);
assert.equal(inspection.frame.blockNumber,row.blockNumber,row.name);
assert.equal(inspection.frame.type,p.content.type,row.name);
assert.equal(inspection.contentDataItemId,row.contentDataItemId,row.name);
assert.notEqual(inspection.frame.body.kind,'unknown',row.name);
if (p.core.line) assert.equal(inspection.frame.body.line.lineCode,p.core.line.lineCode,row.name);
}
});
test('CORE can be inspected without CONTENT, but a full proof cannot be claimed',async()=>{
const row={...rows[0],contentDataItemB64:null,contentStatus:'MISSING'};
assert.equal((await inspectCoreBlock(row)).frame.body.kind,'unknown');
await assert.rejects(readCoreBlock(row,{requireContent:true}),/CONTENT unavailable/);
});
test('read rejects altered metadata, substituted content, and invalid signature',async()=>{
const row=rows[0];
for (const change of [{blockNumber:1},{coreHash:'a'.repeat(64)},{contentDataItemId:'A'.repeat(43)},{contentHash:'b'.repeat(64)},{coreDataItemId:'B'.repeat(43)},{contentDataItemB64:rows[1].contentDataItemB64}]) await assert.rejects(readCoreBlock({...row,...change}));
const raw=Buffer.from(row.coreDataItemB64,'base64'); raw[2]^=1;
await assert.rejects(readCoreBlock({...row,coreDataItemB64:raw.toString('base64')}));
assert.equal((await inspectCoreBlock({...row,contentStatus:'INVALID'})).frame.body.kind,'unknown');
});
test('existing proof request verifies both exact DataItems and expected CORE ID',async()=>{
const row=rows[2];
const authService={ws:{request:async(op,payload)=>{assert.equal(op,'GetBlockchainBlock');assert.equal(payload.blockNumber,row.blockNumber);return {status:200,payload:{...row,blockHash:row.coreHash}};}}};
const args={authService,blockchainName:'Alice-001',blockNumber:row.blockNumber,blockHash:row.coreHash,dataItemId:row.coreDataItemId};
const p=await readSignedBlock(args);
assert.equal(Buffer.from(p.bytes).toString('base64'),row.coreDataItemB64);
assert.equal(Buffer.from(p.contentProof.bytes).toString('base64'),row.contentDataItemB64);
await assert.rejects(readSignedBlock({...args,dataItemId:'A'.repeat(43)}),/Arweave/);
await assert.rejects(readSignedBlock({...args,blockHash:'a'.repeat(64)}));
});
const h=x=>x.repeat(64);
const root={blockNumber:5,blockHash:h('a')};
const p1={authorLogin:'Alice',localNumber:2,messageRef:{blockNumber:6,blockHash:h('b')}};
const p2={authorLogin:'Alice',localNumber:1,messageRef:{blockNumber:9,blockHash:h('c')}};
const summary={channel:{ownerLogin:'Alice',channelRoot:root},followHash:h('d'),messagesCount:2,readAnchor:p2.messageRef};
test('read prefix is canonical not display order, and never skips an unseen publication',()=>{
const ordered=canonicalReadPosts([p2,p1],summary);
assert.deepEqual(ordered,[p1,p2]);
assert.equal(readPrefixCount(ordered,0,new Set([1])),0);
assert.equal(readPrefixCount(ordered,0,new Set([2])),1);
assert.equal(readPrefixCount(ordered,1,new Set([1])),2);
assert.equal(canonicalReadPosts([p2],summary),null);
assert.equal(canonicalReadPosts([p2,p1],{...summary,readAnchor:{...p2.messageRef,blockHash:h('e')}}),null);
assert.equal(canonicalReadPosts([p2,{...p1,authorLogin:'Other'}],summary),null);
assert.deepEqual(canonicalReadPosts([],{...summary,messagesCount:0,readAnchor:root}),[]);
});
test('SetChannelReadState signs the exact existing server contract with client key',async()=>{
const seed=Buffer.from(Array.from({length:32},(_,i)=>i));
const pkcs8=Buffer.concat([Buffer.from('302e020100300506032b657004220420','hex'),seed]);
const auth=new AuthService('wss://test.invalid/ws');
await saveEncryptedUserSecrets('Bob','read-test',{clientKey:pkcs8.toString('base64')});
const mark={owner:'Alice',root:5,rootHash:h('a'),followHash:h('d'),anchor:6,anchorHash:h('b'),timeMs:1760000000000};
const result={applied:true,state:{followHash:mark.followHash,initialized:true,readCount:1,unreadCount:1}};
auth.ws.request=async(op,payload)=>{
assert.equal(op,'SetChannelReadState');const {signatureB64,...rest}=payload;
assert.deepEqual(rest,mark);
const pub=await crypto.subtle.importKey('raw',Buffer.from(fixtures[0][1],'hex'),{name:'Ed25519'},false,['verify']);
assert.equal(await crypto.subtle.verify('Ed25519',pub,Buffer.from(signatureB64,'base64'),new TextEncoder().encode(['SHiNE_CORE_READ_V1','test5593','Bob','Alice',5,h('a'),h('d'),6,h('b'),mark.timeMs].join('|'))),true);
return {status:200,payload:{result}};
};
assert.deepEqual(await auth.setChannelReadState({login:'Bob',storagePwd:'read-test',...mark}),result);
await assert.rejects(auth.setChannelReadState({login:'Bob',storagePwd:'read-test',...mark,anchor:4}),/BAD_READ_STATE/);
await assert.rejects(auth.setChannelReadState({login:'Bob',storagePwd:'read-test',ownerBlockchainName:'Alice-001',channelName:'news',readCount:1}),/BAD_READ_STATE/);
});
test('public channel resolution uses original profile API, not another user’s subscriptions',async()=>{
const auth=new AuthService('wss://test.invalid/ws');
auth.ws.request=async(op,payload)=>{assert.equal(op,'ListUserProfileChannels');assert.deepEqual(payload,{login:'Alice',mode:'owned',limit:500,offset:0,includeDeleted:false});return {status:200,payload:{channels:[{ownerLogin:'Alice',ownerBlockchainName:'Alice-001',slug:'news',rootBlockNumber:5,rootBlockHashHex:h('a')}]}};};
const [row]=await auth.listOwnedChannelSummaries('Alice');
assert.equal(row.channel.channelName,'news');assert.deepEqual(row.channel.channelRoot,root);
});
test('snapshot creation is blocked until D rather than generating an empty legacy file',async()=>{
await assert.rejects(buildBlockchainSnapshotFile({authService:{ws:{request:()=>assert.fail('must not fetch legacy blocks')}}}));
});