Унифицировать HEADER в формате 1.0

This commit is contained in:
AidarKC
2026-12-02 17:57:28 +03:00
parent 58e4bac3c8
commit c61cbf239c
24 changed files with 230 additions and 394 deletions
+10 -13
View File
@@ -544,11 +544,11 @@ function extractContactsFromDialogs(dialogs) {
return out;
}
export const HEADER_VERSION = 3;
export const HEADER_VERSION = 1;
// Временное значение до утверждения лицензии проекта.
export const HEADER_DEFAULT_LICENSE = '';
function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = '', accountType = null, previousAccounts = [] }) {
function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = '', accountType = 1, previousAccounts = [] }) {
const cleanLogin = String(login || '').trim();
const loginBytes = utf8Bytes(cleanLogin);
const licenseBytes = utf8Bytes(license);
@@ -560,18 +560,15 @@ function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = '', acco
if (keyBytes.length !== 32 || keyBytes.every((value) => value === 0)) {
throw new Error('HEADER initialBlockchainKey32 must be a non-zero 32-byte key');
}
let identityBytes = new Uint8Array(0);
if (accountType !== null) {
if (accountType !== 0 && accountType !== 1) throw new Error('Invalid HEADER account type');
if (!Array.isArray(previousAccounts) || previousAccounts.length > 10 || (accountType === 0 && previousAccounts.length)) throw new Error('Invalid HEADER previous accounts');
const seen = new Set([cleanLogin.toLowerCase()]);
for (const previous of previousAccounts) {
if (typeof previous !== 'string' || !(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid or duplicate previous account');
seen.add(previous.toLowerCase());
}
const csv = utf8Bytes(previousAccounts.join(','));
identityBytes = accountType === 1 ? concatBytes(int8Byte(1), Uint8Array.of(csv.length >> 8, csv.length & 255), csv) : int8Byte(0);
if (accountType !== 0 && accountType !== 1) throw new Error('Invalid HEADER account type');
if (!Array.isArray(previousAccounts) || previousAccounts.length > 10 || (accountType === 0 && previousAccounts.length)) throw new Error('Invalid HEADER previous accounts');
const seen = new Set([cleanLogin.toLowerCase()]);
for (const previous of previousAccounts) {
if (typeof previous !== 'string' || !(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid or duplicate previous account');
seen.add(previous.toLowerCase());
}
const csv = utf8Bytes(previousAccounts.join(','));
const identityBytes = accountType === 1 ? concatBytes(int8Byte(1), Uint8Array.of(csv.length >> 8, csv.length & 255), csv) : int8Byte(0);
return concatBytes(
utf8Bytes('SHiNE'),
int8Byte(loginBytes.length),
@@ -124,33 +124,20 @@ function parseTechBody(subType, body, frame) {
const magic = reader.text(5, 'HEADER magic');
if (magic !== 'SHiNE') throw new Error('Неправильная сигнатура HEADER');
const login = reader.textU8('HEADER login');
let license = null;
let accountType = null;
const accountType = reader.u8('HEADER account type');
if (accountType !== 0 && accountType !== 1) throw new Error('Invalid HEADER account type');
let previousAccounts = [];
if (frame.version === 3) {
accountType = reader.u8('HEADER account type');
if (accountType !== 0 && accountType !== 1) throw new Error('Invalid HEADER account type');
if (accountType === 1) {
const csv = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u16('HEADER previous accounts length'), 'HEADER previous accounts'));
previousAccounts = csv ? csv.split(',') : [];
const seen = new Set([login.toLowerCase()]);
if (previousAccounts.length > 10) throw new Error('Too many previous accounts');
for (const previous of previousAccounts) {
if (!(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid previous account');
seen.add(previous.toLowerCase());
}
}
license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u8('HEADER license length'), 'HEADER license'));
} else if (frame.version === 2) {
const field = reader.raw(reader.remaining() - 32, 'HEADER license');
const marker = 'license:CC0-1.0';
if (field.length === marker.length && field.every((b, i) => b === marker.charCodeAt(i))) {
license = 'CC0-1.0'; // исторический HEADER v2
} else {
if (!field.length || field[0] !== field.length - 1) throw new Error('Некорректная длина лицензии HEADER');
license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(field.slice(1));
if (accountType === 1) {
const csv = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u16('HEADER previous accounts length'), 'HEADER previous accounts'));
previousAccounts = csv ? csv.split(',') : [];
const seen = new Set([login.toLowerCase()]);
if (previousAccounts.length > 10) throw new Error('Too many previous accounts');
for (const previous of previousAccounts) {
if (!(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid previous account');
seen.add(previous.toLowerCase());
}
}
const license = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(reader.raw(reader.u8('HEADER license length'), 'HEADER license'));
const initialBlockchainKey = bytesToBase64Url(reader.raw(32, 'initialBlockchainKey32'));
if (reader.remaining() !== 0) throw new Error('Неожиданные данные после HEADER');
return { kind: 'header', magic, login, license, accountType, previousAccounts, initialBlockchainKey };
@@ -260,8 +247,7 @@ function parseStatusBody(subType, body) {
}
function parseBody(type, subType, version, body, frame) {
// Only TECH HEADER subtype 0 has a second version; all other records stay v1.
if (version !== 1 && !(type === 0 && subType === 0 && (version === 2 || version === 3))) {
if (version !== 1) {
return { kind: 'unsupported_version', rawBodyLength: body.length };
}
if (type === 0) return parseTechBody(subType, body, frame);
+1 -1
View File
@@ -80,7 +80,7 @@ export function coreTags(core) {
function checkEventLine(content, core) {
const { type, subType, version } = content;
const header = type === 0 && subType === 0;
if (version !== 1 && !(header && (version === 2 || version === 3))) throw new Error('Unsupported CONTENT version for creation');
if (version !== 1) throw new Error('Unsupported CONTENT version for creation');
if (header !== (core.blockNumber === 0)) throw new Error('HEADER must be CORE #0');
const code = core.line?.lineCode;
if (type === 0 && !header) { if (code !== SHINE_CORE_LINE_TECH) throw new Error('Wrong TECH line'); }
+14 -24
View File
@@ -1936,31 +1936,21 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
throw new Error(`HEADER: неожиданный tag ${tag}`);
}
const login = reader.readUtf8U8();
let accountType = null, previousAccounts = [], license = null;
let previousAccounts = [];
const strict = bytes => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
if (version === 3) {
accountType = reader.readU8();
if (![0,1].includes(accountType)) throw new Error('Invalid HEADER account type');
if (accountType === 1) {
const csv = strict(reader.readBytes(reader.readU16()));
previousAccounts = csv ? csv.split(',') : [];
const seen = new Set([login.toLowerCase()]);
if (previousAccounts.length > 10) throw new Error('Too many previous accounts');
for (const previous of previousAccounts) {
if (!(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid previous account');
seen.add(previous.toLowerCase());
}
}
license = strict(reader.readBytes(reader.readU8()));
} else if (version === 2) {
const field = bodyBytes.slice(6 + bodyBytes[5], -32);
if (field.length === 15 && field.every((b,i) => b === 'license:CC0-1.0'.charCodeAt(i))) {
reader.readBytes(15); license = 'CC0-1.0';
} else {
if (!field.length || field[0] !== field.length - 1) throw new Error('Invalid HEADER license length');
license = strict(reader.readBytes(reader.readU8()));
const accountType = reader.readU8();
if (![0,1].includes(accountType)) throw new Error('Invalid HEADER account type');
if (accountType === 1) {
const csv = strict(reader.readBytes(reader.readU16()));
previousAccounts = csv ? csv.split(',') : [];
const seen = new Set([login.toLowerCase()]);
if (previousAccounts.length > 10) throw new Error('Too many previous accounts');
for (const previous of previousAccounts) {
if (!(/^[A-Za-z0-9_]{1,255}$/.test(previous) || (previous.length <= 30 && /^[A-Za-z0-9_]+@[a-z0-9_]+$/.test(previous))) || seen.has(previous.toLowerCase())) throw new Error('Invalid previous account');
seen.add(previous.toLowerCase());
}
}
const license = strict(reader.readBytes(reader.readU8()));
const initialBlockchainKey = base64Url(reader.readBytes(32));
reader.ensureDone();
return { kind: 'header', login, tag, initialBlockchainKey, accountType, previousAccounts, license };
@@ -2050,7 +2040,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
}
function parseBlockchainBody(type, subType, version, bodyBytes, line) {
if (version !== 1 && !(type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER && [2,3].includes(version))) {
if (version !== 1) {
return { kind: 'unsupported', reason: `Неподдерживаемая версия body ${version}` };
}
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER) {
@@ -2093,7 +2083,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
const core = parseCorePayload(coreBytes);
if (contentBytes.length < 7 || contentBytes.length > 8*1024*1024-117 || contentBytes[0] !== 1 || bytesToHex(await digestSha256(contentBytes)) !== core.contentHashHex) throw new Error('CONTENT hash/format mismatch');
const type=readUint16BE(contentBytes,1),subType=readUint16BE(contentBytes,3),version=readUint16BE(contentBytes,5);
if ((version !== 1 && !(type===0 && subType===0 && [2,3].includes(version))) || (type===0 && subType===0)!==(core.blockNumber===0)) throw new Error('Invalid CONTENT version/HEADER');
if (version !== 1 || (type===0 && subType===0)!==(core.blockNumber===0)) throw new Error('Invalid CONTENT version/HEADER');
const channelText=type===1 && [10,11,50,90,92,100,110,120,130].includes(subType);
const expectedLine=type===0&&subType!==0?2147483647:type===3?2147483646:type===4?2147483645:null;
if (channelText ? !core.line||core.line.lineCode>CORE_MAX_NUMBER : expectedLine===null ? !!core.line : core.line?.lineCode!==expectedLine) throw new Error('CONTENT/CORE line mismatch');
+1 -1
View File
@@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs';
import { profileCardHtml } from '../js/components/profile-card.js';
import { accountRoleFromHeader, confirmationRights } from '../js/services/account-voting.js';
test('only explicit HEADER V3 type 1 is Primary; no legacy fallbacks', () => {
test('only explicit HEADER 1.0 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), '');
+4 -4
View File
@@ -92,20 +92,20 @@ test('Minimal pair codec and container: exact vectors, tampering, unsigned lengt
import { inspectBlockchainDataItem } from '../js/services/blockchain-entry-inspector.js';
test('HEADER v2 signed CORE/CONTENT and inspector accept arbitrary UTF-8 license', async () => {
test('HEADER 1.0 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 body=Buffer.concat([Buffer.from('SHiNE'),Buffer.of(login.length),login,Buffer.of(1, 0, 0, bytes.length),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 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);
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}));
}
});
+38 -69
View File
@@ -16,85 +16,54 @@ const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeH
Uint8Array,
});
test('client writes HEADER v2 as SHiNE → login → length + license → key', () => {
function inspectorParser() {
const stripped = inspector.replace(/^import .+;\s*$/gm, '').replace(/^export /gm, '');
return vm.runInNewContext(`${stripped}\nparseShineFrame`, {
TextDecoder, DataView, Uint8Array, BigInt,
bytesToBase64Url: bytes => Buffer.from(bytes).toString('base64url'), Buffer,
});
}
function headerFrame(body, version = 1) {
const frame = new Uint8Array(88 + body.length);
const view = new DataView(frame.buffer);
view.setUint16(0, 1, false);
view.setInt32(66, frame.length, false);
view.setInt32(70, 0, false);
view.setBigInt64(74, 0n, false);
view.setUint16(82, 0, false);
view.setUint16(84, 0, false);
view.setUint16(86, version, false);
frame.set(body, 88);
return frame;
}
test('client writes only HEADER 1.0: identity, arbitrary license, then initial key', () => {
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
const login = 'Alice@shine';
const license = 'Лицензия 🌞';
const body = encode({ login, initialBlockchainKey32: key, license });
const loginBytes = utf8(login);
const previous = 'Bob@free,Older';
const body = encode({ login, initialBlockchainKey32: key, accountType: 1, previousAccounts: ['Bob@free', 'Older'], license });
const expected = Uint8Array.from([
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
utf8(license).length, ...utf8(license), ...key,
...utf8('SHiNE'), utf8(login).length, ...utf8(login),
1, 0, utf8(previous).length, ...utf8(previous), 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 = 3/);
assert.match(auth, /export const HEADER_VERSION = 1/);
});
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,
bytesToBase64Url: bytes => Buffer.from(bytes).toString('base64url'),
Buffer,
});
test('inspector accepts only HEADER 1.0 and validates its identity and license', () => {
const inspect = inspectorParser();
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)));
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))));
const body = encode({ login: 'Alice@shine', initialBlockchainKey32: key, accountType: 1, previousAccounts: ['Bob@free'], license });
const parsed = inspect(headerFrame(body)).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))));
assert.equal(inspect(headerFrame(body, 2)).body.kind, 'unsupported_version');
}
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]))));
assert.throws(() => encode({ login: 'Alice@shine', initialBlockchainKey32: key, accountType: 0, previousAccounts: ['Bob@free'] }));
});
@@ -24,18 +24,21 @@ const context = {
};
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
test('CORE/CONTENT HEADER v2 contains login, empty license and initial key', () => {
test('CORE/CONTENT HEADER 1.0 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');
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(7+login.length)), Array.from(key));
assert.equal(result[6+login.length], 0);
assert.equal(result.length, 5 + 1 + login.length + 1 + 32);
const identityOffset = 6 + login.length;
assert.equal(result[identityOffset], 1);
assert.deepEqual(Array.from(result.slice(identityOffset + 1, identityOffset + 3)), [0, 0]);
assert.equal(result[identityOffset + 3], 0);
assert.deepEqual(Array.from(result.slice(identityOffset + 4)), Array.from(key));
assert.equal(result.length, 5 + 1 + login.length + 1 + 2 + 1 + 32);
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
assert.match(auth, /export const HEADER_VERSION = 3/);
assert.match(auth, /export const HEADER_VERSION = 1/);
});
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {