Разделить среды и закрепить лицензии в HEADER 1.0

This commit is contained in:
AidarKC
2026-12-05 11:42:20 +03:00
parent a64168a748
commit 77c7021aed
89 changed files with 4204 additions and 211 deletions
+21 -17
View File
@@ -1,21 +1,25 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const read = (p) => fs.readFileSync(path.join(root, p), 'utf8');
test('CORE эпоха одинакова в UI, Server, discovery и сертификате; viewer', () => {
const ui = read('shine-UI/js/services/protocol-tags.js');
const server = read('SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java');
const viewer = read('shine-UI/static-sites/arweave-viewer/index.html');
const reg = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationCertificateV1.java');
const archive = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlocksConfig.java');
assert.match(ui, /SHINE_CORE_NAMESPACE\s*=\s*'SHiNE'/);
assert.match(archive, /TEST_TAG_VALUE\s*=\s*ShineProtocolTags\.CORE_NAMESPACE/);
assert.match(server, /CORE_NAMESPACE\s*=\s*"SHiNE"/);
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'SHiNE'/);
assert.match(reg, /ShineProtocolTags\.CORE_REGISTRATION_TAGS/);
for (const txt of [ui, server, viewer, reg]) assert.doesNotMatch(txt, /test5591/);
import { parseServerEnvironment } from '../js/services/server-environment.js';
import { coreTags } from '../js/services/core-content.js';
const read = p => fs.readFileSync(new URL('../../'+p, import.meta.url), 'utf8');
test('GetServerInfo: strict environment tuple; absent or inconsistent mode cannot sign', () => {
for (const [testMode,arweaveAppTag,solanaCluster] of [[true,'test5570','devnet'],[false,'SHiNE','mainnet-beta']]) {
const env = parseServerEnvironment({status:200,payload:{testMode,arweaveAppTag,solanaCluster}});
assert.equal(coreTags({blockNumber:0},env.arweaveAppTag)[0].value, arweaveAppTag);
assert.throws(()=>parseServerEnvironment({status:200,payload:{testMode,arweaveAppTag:'test5599',solanaCluster}}));
assert.throws(()=>parseServerEnvironment({status:200,payload:{testMode:!testMode,arweaveAppTag,solanaCluster}}));
}
assert.throws(()=>parseServerEnvironment({status:200,payload:{solanaCluster:'mainnet-beta'}}));
assert.throws(()=>coreTags({blockNumber:0}));
assert.throws(()=>coreTags({blockNumber:0},'test5599'));
});
test('Server/Viewer/ESP32 use the current independent namespaces', () => {
const server=read('SHiNE-server/shine-server-config/src/main/java/utils/config/ServerEnvironment.java');
const viewer=read('shine-UI/static-sites/arweave-viewer/index.html');
const esp=read('ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/shine_registration_signer/certificate_v1.h');
assert.match(server,/PRODUCTION_APP = "SHiNE"/); assert.match(server,/TEST_APP = "test5570"/);
assert.match(viewer,/\[SHINE_ARWEAVE_APP_TAG\]/); assert.doesNotMatch(viewer,/test5599/);
assert.match(esp,/avroString\(a,"SHiNE"\)/);
});
+7 -7
View File
@@ -16,7 +16,7 @@ const special = new Map([[SHINE_CORE_LINE_PROFILE,'P'],[SHINE_CORE_LINE_CONNECTI
test('CORE v2 namespace и числовые линии согласованы в Java и UI', () => {
const server=fs.readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java',import.meta.url),'utf8');
assert.equal(SHINE_CORE_NAMESPACE,'SHiNE');
assert.match(server,/CORE_NAMESPACE\s*=\s*"SHiNE"/);
assert.match(server,/CORE_NAMESPACE\s*=\s*utils.config.ServerEnvironment.ARWEAVE_APP_TAG/);
assert.equal(SHINE_CORE_MAX_BLOCK_NUMBER,2147482623);
assert.deepEqual([...special.keys()],[2147483645,2147483646,2147483647]);
});
@@ -41,7 +41,7 @@ test('CORE/CONTENT fixtures: BigEndian, hash, ANS-104 Ed25519 и подписи
newCore.writeInt32BE(history.length,33);
newCore.writeBigInt64BE(core.readBigInt64BE(37),37);
unhex(contentHash).copy(newCore,45); unhex(contentId).copy(newCore,77);
const tags=[{name:'App',value:'test5599'},{name:'n',value:String(history.length)}];
const tags=[{name:'App',value:'test5570'},{name:'n',value:String(history.length)}];
if(core.length===149) {
const line=core.readInt32BE(109), prev=core.readInt32BE(113);
newCore.writeInt32BE(line,109); newCore.writeInt32BE(prev,113); unhex(history[prev]).copy(newCore,117);
@@ -70,7 +70,7 @@ test('Minimal pair codec and container: exact vectors, tampering, unsigned lengt
for (const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
const core=decodeCore(unhex(coreHex)), content=decodeContent(unhex(contentHex)), owner=unhex(ownerHex);
assert.equal(hex(encodeCore(core)),coreHex); assert.equal(hex(encodeContent(content)),contentHex);
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content, ...core});
const signed=await signCoreContentPair({arweaveAppTag:"SHiNE",owner32:owner,privateKey:key,content, ...core});
assert.notEqual(hex(signed.coreDataItem),coreItemHex,name); assert.equal(hex(signed.contentDataItem),contentItemHex,name);
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
assert.equal(Buffer.from(raw).readUInt32BE(),signed.coreDataItem.length);
@@ -97,15 +97,15 @@ test('HEADER 1.0 signed CORE/CONTENT and inspector accept arbitrary UTF-8 licens
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)]) {
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', '\ufeffx', 'x'.repeat(300)]) {
const bytes=Buffer.from(license);
const body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(1, 0, 0, bytes.length),bytes,owner]);
const body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(1, 0, 0, bytes.length >> 8, bytes.length & 255),bytes,owner]);
const content={type:0,subType:0,version:1,body};
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content,prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null});
const signed=await signCoreContentPair({arweaveAppTag:"SHiNE",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,1);
await assert.rejects(signCoreContentPair({owner32:owner,privateKey:key,content:{...content,version:4},prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null}));
await assert.rejects(signCoreContentPair({arweaveAppTag:"SHiNE",owner32:owner,privateKey:key,content:{...content,version:4},prevCoreHash32:new Uint8Array(32),blockNumber:0,timestamp:1700001000n,line:null}));
}
});
+6 -5
View File
@@ -10,6 +10,7 @@ const source = auth.split('function makeHeaderBodyBytes(')[1]?.split('\nfunction
assert.ok(source, 'production makeHeaderBodyBytes must exist');
const utf8 = value => new TextEncoder().encode(value);
const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeHeaderBodyBytes`, {
HEADER_DEFAULT_LICENSE: auth.match(/export const HEADER_DEFAULT_LICENSE = '([^']+)'/)[1],
utf8Bytes: utf8,
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
@@ -38,7 +39,7 @@ function headerFrame(body, version = 1) {
return frame;
}
test('client writes only HEADER 2: identity, arbitrary license, then initial key', () => {
test('client writes only HEADER 1: identity, arbitrary license, then initial key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine';
const license = 'Лицензия 🌞';
@@ -49,19 +50,19 @@ test('client writes only HEADER 2: identity, arbitrary license, then initial key
1, 0, utf8(previous).length, ...utf8(previous), 0, utf8(license).length, ...utf8(license), ...key,
]);
assert.deepEqual(Array.from(body), Array.from(expected));
assert.match(auth, /export const HEADER_VERSION = 2/);
assert.match(auth, /export const HEADER_VERSION = 1/);
});
test('inspector accepts only HEADER 2 and validates its identity and license', () => {
test('inspector accepts only HEADER 1 and validates its identity and license', () => {
const inspect = inspectorParser();
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
for (const license of ['', 'CC-BY-NC-4.0', 'Лицензия 🌞', 'x'.repeat(300)]) {
const body = encode({ login: 'Alice@shine', initialBlockchainKey32: key, accountType: 1, previousAccounts: ['Bob@free'], license });
const parsed = inspect(headerFrame(body, 2)).body;
const parsed = inspect(headerFrame(body, 1)).body;
assert.equal(parsed.accountType, 1);
assert.deepEqual(Array.from(parsed.previousAccounts), ['Bob@free']);
assert.equal(parsed.license, license);
assert.throws(() => inspect(headerFrame(body.slice(0, -1), 2)));
assert.throws(() => inspect(headerFrame(body.slice(0, -1), 1)));
assert.equal(inspect(headerFrame(body, 3)).body.kind, 'unsupported_version');
}
assert.throws(() => encode({ login: 'Alice@shine', initialBlockchainKey32: key, license: 'x'.repeat(65536) }));
@@ -45,7 +45,8 @@ test('переводы согласий вычисляются при откры
const profile = source('pages/profile-edit-view.js');
assert.match(consent, /export function getPublicHistoryRememberLabel\(\)/);
assert.match(consent, /label:\s*getPublicHistoryRememberLabel\(\)/);
assert.match(likes, /getPublicHistoryRememberLabel\(\)/);
assert.match(likes, /confirmPublicHistoryAction\(\{ text: warning\.textContent \}\)/);
assert.match(likes, /warning\.textContent = t\('dialogs\.modals\.like_action_sheet\.label_002'\)/);
assert.doesNotMatch(likes, /PUBLIC_HISTORY_REMEMBER_LABEL/);
assert.match(profile, /function shiningSteps\(\)/);
assert.match(profile, /steps:\s*shiningSteps\(\)/);
+1 -1
View File
@@ -11,7 +11,7 @@ const owner=Buffer.from((await crypto.subtle.exportKey('jwk',key)).x,'base64url'
const stored=rows.map(r=>({blockHash:r[3],blockBytesB64:b64(packCoreContent(h(r[6]),h(r[8])))}));
for (const cutoff of [0,2,7]) test(`M5 FORK at #${cutoff}: new owner, retained TECH tail, deterministic retry`,async()=>{
const calls=[];
const client=new KeyRotationClient({ws:{async request(op,p){
const client=new KeyRotationClient({getServerEnvironment:async()=>({arweaveAppTag:"test5570"}),ws:{ws:{},connectionGeneration:1,async request(op,p){
if(op==='GetBlockchainBlock'){assert.equal(p.blockchainName,'Alice-001');return {status:200,payload:stored[p.blockNumber]};}
assert.equal(op,'KeyRotationAddBlock');calls.push(p);return {status:200,payload:{}};
}}});
+9 -13
View File
@@ -10,7 +10,7 @@ const funcs=html.slice(html.indexOf(' async function digestSha256'),html.indexO
const b64=html.slice(html.indexOf(' function base64Url('),html.indexOf(' async function arweaveOwnerAddressFromBlockchainKey'));
const loader=html.slice(html.indexOf(' async function loadArweavePairs('),html.indexOf(' async function checkSolanaEndpoint('));
const checks=html.slice(html.indexOf(' function v3ZeroHash('),html.indexOf(' function v3MetricText('));
const ctx=vm.createContext({crypto:webcrypto,Uint8Array,DataView,TextDecoder,TextEncoder,btoa, MAGIC:'SHiNE',bytesToHex:b=>Buffer.from(b).toString('hex'),baseUrl:s=>s,fetch:()=>{throw Error('unexpected fetch')}});
const ctx=vm.createContext({URLSearchParams,location:{search:"?network=test"},crypto:webcrypto,Uint8Array,DataView,TextDecoder,TextEncoder,btoa, MAGIC:'SHiNE',bytesToHex:b=>Buffer.from(b).toString('hex'),baseUrl:s=>s,fetch:()=>{throw Error('unexpected fetch')}});
vm.runInContext(source+funcs+b64+loader+checks+';globalThis.viewer={parseCorePayload,parseBlockchainBlock,checkIndexedCoreTags,loadArweavePairs,v3Verification}',ctx);
const v=ctx.viewer,bytes=s=>Uint8Array.from(Buffer.from(s,'hex'));
const itemid=x=>Buffer.from(x,'hex').toString('base64url');
@@ -29,20 +29,16 @@ test('viewer: rejects tampered CONTENT, invalid CORE and wrong indexed tags',asy
test('viewer: requests CORE then CONTENT by ID and never claims signature verification',async()=>{
const f=find('post'),id=itemid(f.coreItemId),cid=itemid(f.contentItemId),calls=[];
ctx.fetch=async url=>{calls.push(url);const raw=url.endsWith(cid)?f.content:f.core;return {ok:true,arrayBuffer:async()=>bytes(raw).buffer};};
const r=await v.loadArweavePairs('https://mock.invalid',[{id,owner:{address:'indexed'},tags:[{name:'App',value:'test5599'},{name:'n',value:'2'},{name:'l',value:'1'}]}]);
const r=await v.loadArweavePairs('https://mock.invalid',[{id,owner:{address:'indexed'},tags:[{name:'App',value:'test5570'},{name:'n',value:'2'},{name:'l',value:'1'}]}]);
assert.deepEqual(calls,[`https://mock.invalid/${id}`,`https://mock.invalid/${cid}`]);assert.equal(r.blocks[0].hashHex,f.coreHash);
const checks=v.v3Verification(r.blocks);assert.equal(checks.signature.ok,0);assert.equal(checks.signature.na,1);assert.equal(checks.global.na,1);
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:'test5599'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5570'},{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],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);if (role !== null) assert.equal(result.body.license,'');
if (role !== null) assert.deepEqual(Array.from(result.body.previousAccounts),[]);
}
test('viewer: rejects HEADER body version 2',async()=>{
const f=find('header'), content=bytes(f.content), core=bytes(f.core);
content[6]=2;
core.set(new Uint8Array(await webcrypto.subtle.digest('SHA-256',content)),45);
const result=await v.parseBlockchainBlock(core,content);
assert.equal(result.body.kind,'unsupported');
});
+2 -2
View File
@@ -25,7 +25,7 @@ test('existing body factories produce exact independent signed pair; ordinal is
const key=await crypto.subtle.importKey('pkcs8',Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]),{name:'Ed25519'},false,['sign']);
for(const r of rows){
const core=decodeCore(unhex(r[2])),content=decodeContent(unhex(r[4]));
const args={owner32:unhex(r[1]),privateKey:key,blockNumber:core.blockNumber,prevBlockHash:Buffer.from(core.prevCoreHash32).toString('hex'),timestamp:core.timestamp,msgType:content.type,msgSubType:content.subType,msgVersion:content.version};
const args={arweaveAppTag:"SHiNE",owner32:unhex(r[1]),privateKey:key,blockNumber:core.blockNumber,prevBlockHash:Buffer.from(core.prevCoreHash32).toString('hex'),timestamp:core.timestamp,msgType:content.type,msgSubType:content.subType,msgVersion:content.version};
const result=await signEventContainer({...args,bodyBytes:oldFactoryBody(core,content)});
assert.notDeepEqual(result.bytes,fixture(r),r[0]);assert.equal(result.hash,r[3]);
if(core.line){
@@ -39,7 +39,7 @@ test('existing body factories produce exact independent signed pair; ordinal is
assert.equal(inspection.frame.blockNumber,core.blockNumber);assert.equal(inspection.frame.type,content.type);
assert.deepEqual(Buffer.from(inspection.frame.bodyBytes),Buffer.from(content.body));
if(core.line) assert.equal(inspection.frame.body.line.lineSequence,42);
if(core.blockNumber===0) assert.equal(inspection.frame.body.license,'');
if(core.blockNumber===0) assert.match(inspection.frame.body.license,/^licenses:CC-BY-NC-4\.0\/sha256:/);
}
});
test('lost response: retransmit the identical signed container, then confirm canonical bytes',async()=>{
@@ -5,18 +5,12 @@ 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 = {
HEADER_DEFAULT_LICENSE: auth.match(/export const HEADER_DEFAULT_LICENSE = '([^']+)'/)[1],
utf8Bytes: value => new TextEncoder().encode(value),
int8Byte: value => Uint8Array.of(value),
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
@@ -24,7 +18,7 @@ const context = {
};
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('CORE/CONTENT HEADER 2 contains identity, arbitrary license and initial key', () => {
test('CORE/CONTENT HEADER 1 contains identity, arbitrary 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');
@@ -34,21 +28,12 @@ test('CORE/CONTENT HEADER 2 contains identity, arbitrary license and initial key
const identityOffset = 6 + login.length;
assert.equal(result[identityOffset], 1);
assert.deepEqual(Array.from(result.slice(identityOffset + 1, identityOffset + 3)), [0, 0]);
assert.deepEqual(Array.from(result.slice(identityOffset + 3, identityOffset + 5)), [0, 7]);
assert.equal(new TextDecoder().decode(result.slice(identityOffset + 5, identityOffset + 12)), 'CC0-1.0');
assert.deepEqual(Array.from(result.slice(identityOffset + 12)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 1 + 2 + 2 + 7 + 32);
const license = context.HEADER_DEFAULT_LICENSE;
const licenseBytes = new TextEncoder().encode(license);
assert.deepEqual(Array.from(result.slice(identityOffset + 3, identityOffset + 5)), [licenseBytes.length >> 8, licenseBytes.length & 255]);
assert.equal(new TextDecoder().decode(result.slice(identityOffset + 5, identityOffset + 5 + licenseBytes.length)), license);
assert.deepEqual(Array.from(result.slice(identityOffset + 5 + licenseBytes.length)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 1 + 2 + 2 + licenseBytes.length + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 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/);
assert.match(auth, /export const HEADER_VERSION = 1/);
});