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
+11
View File
@@ -0,0 +1,11 @@
// Только явно заявленный Primary может участвовать в официальных подтверждениях.
export function accountRoleFromHeader(accountType) {
return accountType === 1 ? 'primary' : accountType === 0 ? 'non_voting' : '';
}
export function confirmationRights(actor, target) {
const a = String(actor?.login || '').trim().toLowerCase();
const b = String(target?.login || '').trim().toLowerCase();
const primary = Boolean(a && b && a !== b && actor?.accountRole === 'primary' && target?.accountRole === 'primary');
return { primary, shine: primary && actor?.shineStatus === 'shining' && target?.shineStatus !== 'not_interested' };
}
+29 -3
View File
@@ -41,6 +41,7 @@ import {
} from './key-vault.js';
import { signEventContainer, submitSignedEvent, readStoredLineMeta } from './core-content.js';
import { defaultServerWs } from '../deploy-config.js';
import { readPendingHeaderIdentity, clearPendingHeaderIdentity } from './pending-header-identity.js';
const BCH_SUFFIX = '001';
const ZERO64 = '0'.repeat(64);
@@ -540,11 +541,15 @@ function extractContactsFromDialogs(dialogs) {
return out;
}
export const HEADER_VERSION = 1;
export const HEADER_VERSION = 3;
// Временное значение до утверждения лицензии проекта.
export const HEADER_DEFAULT_LICENSE = '';
function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
function makeHeaderBodyBytes({ login, initialBlockchainKey32, license = '', accountType = null, previousAccounts = [] }) {
const cleanLogin = String(login || '').trim();
const loginBytes = utf8Bytes(cleanLogin);
const licenseBytes = utf8Bytes(license);
if (licenseBytes.length > 255) throw new Error('HEADER license must be 0..255 UTF-8 bytes');
const keyBytes = initialBlockchainKey32 instanceof Uint8Array
? initialBlockchainKey32
: new Uint8Array(initialBlockchainKey32 || []);
@@ -552,10 +557,25 @@ function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
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);
}
return concatBytes(
utf8Bytes('SHiNE'),
int8Byte(loginBytes.length),
loginBytes,
identityBytes,
int8Byte(licenseBytes.length),
licenseBytes,
keyBytes,
);
}
@@ -1270,6 +1290,7 @@ export class AuthService {
...currentSecrets,
clientKey: keyBundle.clientPair.privatePkcs8B64,
};
if (saveOptions.headerIdentity) secrets.headerIdentity = saveOptions.headerIdentity;
if (saveOptions.saveRoot) secrets.rootKey = keyBundle.rootPair.privatePkcs8B64;
if (saveOptions.saveBlockchain) secrets.blockchainKey = keyBundle.blockchainPair.privatePkcs8B64;
await saveEncryptedUserSecrets(login, storagePwd, secrets);
@@ -1774,6 +1795,9 @@ export class AuthService {
}
const registeredLogin = await this.requireRegisteredDisplayLogin(cleanLogin);
// Never invent an account type after a lost registration draft.
const identity = keyBundle?.headerIdentity || readPendingHeaderIdentity(registeredLogin, publicKeyB64);
if (!identity || ![0, 1].includes(identity.accountType)) throw new Error('HEADER identity declaration is missing; resume registration on the original device');
await this.addBlockSigned({
login: cleanLogin,
storagePwd,
@@ -1782,9 +1806,10 @@ export class AuthService {
msgVersion: HEADER_VERSION,
// HEADER хранит исходный регистр неизменяемого имени из Solana/Arweave.
// Нормализация нужна только для уникальности и имени самой цепочки.
bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32 }),
bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32, license: HEADER_DEFAULT_LICENSE, accountType: identity.accountType, previousAccounts: identity.previousAccounts }),
_skipHeaderEnsure: true,
});
clearPendingHeaderIdentity(registeredLogin, publicKeyB64);
return this.getUser(cleanLogin);
}
@@ -3268,6 +3293,7 @@ export class AuthService {
const cleanParam = (param || '').trim();
const cleanValue = String(value ?? '').trim();
if (!cleanLogin || !cleanParam) throw new Error('Не переданы login/param.');
if (['account_role', 'official'].includes(cleanParam.toLowerCase())) throw new Error('account_type_immutable');
if (!cleanValue) throw new Error('Значение параметра не может быть пустым.');
if (!storagePwd) throw new Error('Не передан storagePwd для подписи AddBlock.');
@@ -125,14 +125,35 @@ function parseTechBody(subType, body, frame) {
if (magic !== 'SHiNE') throw new Error('Неправильная сигнатура HEADER');
const login = reader.textU8('HEADER login');
let license = null;
if (frame.version === 2) {
const marker = reader.text(15, 'HEADER license');
if (marker !== 'license:CC0-1.0') throw new Error('Неподдерживаемая лицензия HEADER');
license = 'CC0-1.0';
let accountType = null;
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));
}
}
const initialBlockchainKey = bytesToBase64Url(reader.raw(32, 'initialBlockchainKey32'));
if (reader.remaining() !== 0) throw new Error('Неожиданные данные после HEADER');
return { kind: 'header', magic, login, license, initialBlockchainKey };
return { kind: 'header', magic, login, license, accountType, previousAccounts, initialBlockchainKey };
}
if (subType === 1) {
const line = frame.signedLine ?? parseLinePrefix(reader);
@@ -240,7 +261,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)) {
if (version !== 1 && !(type === 0 && subType === 0 && (version === 2 || version === 3))) {
return { kind: 'unsupported_version', rawBodyLength: body.length };
}
if (type === 0) return parseTechBody(subType, body, frame);
+1 -1
View File
@@ -79,8 +79,8 @@ export function coreTags(core) {
}
function checkEventLine(content, core) {
const { type, subType, version } = content;
if (version !== 1) throw new Error('Unsupported CONTENT version for creation');
const header = type === 0 && subType === 0;
if (version !== 1 && !(header && (version === 2 || version === 3))) 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'); }
@@ -0,0 +1,21 @@
// Только будущие публичные поля HEADER; никаких паролей или приватных ключей.
const prefix = 'shine-pending-header-v3:';
const memory = new Map();
const key = (login, publicKey) => `${prefix}${String(login).trim().toLowerCase()}:${String(publicKey).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`;
export function savePendingHeaderIdentity(login, publicKey, identity) {
if (!publicKey || ![0, 1].includes(identity.accountType)) throw new Error('Missing HEADER identity');
const k = key(login, publicKey);
const data = JSON.stringify({ accountType: identity.accountType, previousAccounts: [...identity.previousAccounts] });
memory.set(k, data);
try { localStorage.setItem(k, data); } catch { /* encrypted vault is a second persistence path */ }
}
export function readPendingHeaderIdentity(login, publicKey) {
const k = key(login, publicKey);
let value = memory.get(k);
try { value = value || localStorage.getItem(k); } catch {}
try { return value ? JSON.parse(value) : null; } catch { return null; }
}
export function clearPendingHeaderIdentity(login, publicKey) {
const k = key(login, publicKey); memory.delete(k);
try { localStorage.removeItem(k); } catch {}
}
+13
View File
@@ -0,0 +1,13 @@
// Public counter represents declared Primary accounts, not verified unique people.
function safeCount(raw) {
const n = Number(raw);
return Number.isFinite(n) ? Math.max(0, Math.trunc(n)) : 0;
}
export function publicLikeCount(message) {
return safeCount(message?.primaryLikesCount);
}
export function hasLikeStatistics(message) {
return publicLikeCount(message) > 0 || safeCount(message?.likesCount) > 0;
}
+7 -7
View File
@@ -1,3 +1,4 @@
import { accountRoleFromHeader } from './account-voting.js';
import { t } from '../i18n/index.js';
import { authService, state } from '../state.js';
import { validateArweaveTxId } from './arweave-file-service.js';
@@ -119,10 +120,7 @@ export async function loadProfileSnapshot(login) {
}
const latestAccountRole = loadLatestByAliasesFromItems(items, ['account_role']);
const rawAccountRole = String(latestAccountRole?.value || '').trim().toLowerCase();
const accountRole = rawAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY || rawAccountRole === PROFILE_ACCOUNT_ROLE_NON_VOTING
? rawAccountRole
: '';
const accountRole = accountRoleFromHeader(payload?.accountType);
const latestShine = loadLatestByAliasesFromItems(items, ['shine']);
const rawShine = String(latestShine?.value || '').trim().toLowerCase();
@@ -165,6 +163,8 @@ export async function loadProfileSnapshot(login) {
fields,
toggles,
accountRole,
accountType: payload?.accountType ?? null,
previousAccounts: Array.isArray(payload?.previousAccounts) ? payload.previousAccounts : [],
accountRoleTimeMs: latestAccountRole?.timeMs || 0,
shineStatus,
shineTimeMs: latestShine?.timeMs || 0,
@@ -193,8 +193,8 @@ export async function saveProfileParamBlock(login, key, value) {
export async function saveProfileStatus(login, key, value) {
const cleanKey = String(key || '').trim();
const cleanValue = String(value || '').trim().toLowerCase();
if (cleanKey === 'account_role' && ![PROFILE_ACCOUNT_ROLE_PRIMARY, PROFILE_ACCOUNT_ROLE_NON_VOTING].includes(cleanValue)) {
throw new Error(t('remaining.profile_errors.invalid_account_role_value'));
if (['account_role', 'official'].includes(cleanKey.toLowerCase())) {
throw new Error(t('screens.registration_identity.immutable'));
}
if (cleanKey === 'shine' && ![PROFILE_SHINE_SHINING, PROFILE_SHINE_UNKNOWN, PROFILE_SHINE_NOT_INTERESTED].includes(cleanValue)) {
throw new Error(t('remaining.profile_errors.invalid_shine_value'));
@@ -206,7 +206,7 @@ export async function saveProfileStatus(login, key, value) {
// Kept only for old callers outside the current UI. New code must use saveProfileStatus().
export async function saveProfileToggle(login, key, enabled) {
if (key === 'shine') return saveProfileStatus(login, 'shine', enabled ? PROFILE_SHINE_SHINING : PROFILE_SHINE_UNKNOWN);
if (key === 'official') throw new Error(t('remaining.profile_errors.the_official_parameter_is_deprecated_use_account_role'));
if (key === 'official') throw new Error(t('screens.registration_identity.immutable'));
throw new Error(`Неизвестный legacy toggle: ${key}`);
}