SHA256
HEADER v3, primary аккаунты и подтверждения
This commit is contained in:
@@ -1,13 +1,13 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
/** В выборе тарифа счётчик не показываем: он начинается с логина. */
|
||||
export function createRegistrationStepper(step) {
|
||||
const current = Math.max(1, Math.min(3, Number(step) || 1));
|
||||
const current = Math.max(1, Math.min(4, Number(step) || 1));
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'signup-stepper';
|
||||
wrapper.setAttribute('aria-label', t('screens.registration_stepper.text_001', { value1: current }));
|
||||
const dots = document.createElement('div');
|
||||
dots.className = 'signup-stepper__dots';
|
||||
for (let i = 1; i <= 3; i += 1) {
|
||||
for (let i = 1; i <= 4; i += 1) {
|
||||
const dot = document.createElement('span');
|
||||
dot.className = `signup-stepper__dot${i === current ? ' is-active' : ''}${i < current ? ' is-complete' : ''}`;
|
||||
dots.append(dot);
|
||||
|
||||
@@ -2545,7 +2545,7 @@
|
||||
"text_139": "Channel ID's not ready.",
|
||||
"text_140": "Channel ID's not ready.",
|
||||
"text_141": "<span class=\"channel-header-title\">Channel</span><span class=\"channel-header-owner\"> </span>",
|
||||
"text_150": "View statistics and list of likes: {value1}",
|
||||
"text_150": "View statistics and list of likes. Primary account likes: {value1}",
|
||||
"text_151": "Open discussion, answers: {value1}",
|
||||
"text_145": "The interlocutor {value1} has not yet created a personal response chat.",
|
||||
"text_146": "modified by {value1}",
|
||||
@@ -3151,13 +3151,13 @@
|
||||
"text_115": "{value1} • Record",
|
||||
"text_116": "Comments · {value1}",
|
||||
"text_119": "Answer {value1}...",
|
||||
"text_103": "View the statistics of likes: {value1}",
|
||||
"text_103": "View like statistics. Primary account likes: {value1}",
|
||||
"text_106": "Answer for {value1}. Turn to his comment",
|
||||
"text_092": "Could not create a discussion link.",
|
||||
"text_098": "Message in the {value1} channel",
|
||||
"text_109": "Action with the comment by {value1}",
|
||||
"text_110": "Responses to this comment · {value1}",
|
||||
"text_107": "Likes statistics: {value1}",
|
||||
"text_107": "Like statistics. Primary account likes: {value1}",
|
||||
"text_108": "Answer {value1}",
|
||||
"text_111": "{value1} {value2}",
|
||||
"text_112": "Response {value1} · {value2}",
|
||||
@@ -4226,9 +4226,26 @@
|
||||
"text_001": "Select \"{value1}\" section",
|
||||
"text_002": "{value1}: {value2}. Select a section"
|
||||
},
|
||||
"registration_identity": {
|
||||
"title": "Choose your account type",
|
||||
"immutable": "The account type is chosen once at registration and cannot be changed later.",
|
||||
"primary": "Primary account",
|
||||
"primary_detail": "SHiNE counts votes from real people. Each person is entitled to only one primary account.",
|
||||
"alternative": "Alternative account",
|
||||
"alternative_detail": "You may have any number of alternative accounts. Likes and ratings from alternative accounts are counted separately from votes of real people using primary accounts.",
|
||||
"previous_detail": "If you previously had primary accounts, list them. Analysis systems can trace your identity history through social connections, for example when friends move from an old account to your new one. This is only your declaration; previous accounts are not blocked and their votes do not change for now.",
|
||||
"disclosure": "Your declaration will be publicly recorded in the blockchain and preserved in the public blockchain archive. Analysis systems may check the account status in the future. If you provide false information, it will remain in the public blockchain history. Proof of ownership of previous accounts is not required.",
|
||||
"add": "+ Add account",
|
||||
"remove": "Remove from list",
|
||||
"search": "Login or user name",
|
||||
"find": "Search",
|
||||
"not_found": "No matching accounts found.",
|
||||
"search_error": "Search failed.",
|
||||
"next": "Continue"
|
||||
},
|
||||
"registration_stepper": {
|
||||
"text_001": "Registration: step {value1} out of 3",
|
||||
"text_002": "Step {value1} of 3"
|
||||
"text_001": "Registration: step {value1} out of 4",
|
||||
"text_002": "Step {value1} of 4"
|
||||
},
|
||||
"network_version_switcher": {
|
||||
"text_001": "<span>Version:</span>",
|
||||
|
||||
@@ -2690,7 +2690,7 @@
|
||||
"text_147": "История #{value1}",
|
||||
"text_148": "Удалённое сообщение от {value1}",
|
||||
"text_149": "История #{value1}",
|
||||
"text_150": "Посмотреть статистику и список лайков: {value1}",
|
||||
"text_150": "Посмотреть статистику и список лайков. Лайки основных аккаунтов: {value1}",
|
||||
"text_151": "Открыть обсуждение, ответов: {value1}",
|
||||
"text_152": "Публикация №{value1} не найдена в канале.",
|
||||
"text_153": "Не удалось сохранить, сколько сообщений прочитано.{value1}{value2}",
|
||||
@@ -3376,11 +3376,11 @@
|
||||
"text_100": "История #{value1}",
|
||||
"text_101": "Удалённое сообщение от {value1}",
|
||||
"text_102": "История #{value1}",
|
||||
"text_103": "Посмотреть статистику лайков: {value1}",
|
||||
"text_103": "Посмотреть статистику лайков. Лайки основных аккаунтов: {value1}",
|
||||
"text_104": "Открыть обсуждение, ответов: {value1}",
|
||||
"text_105": "Профиль {value1}",
|
||||
"text_106": "Ответ для {value1}. Перейти к его комментарию",
|
||||
"text_107": "Статистика лайков: {value1}",
|
||||
"text_107": "Статистика лайков. Лайки основных аккаунтов: {value1}",
|
||||
"text_108": "Ответить {value1}",
|
||||
"text_109": "Действия с комментарием {value1}",
|
||||
"text_110": "Ответы на этот комментарий · {value1}",
|
||||
@@ -4229,9 +4229,26 @@
|
||||
"dropdown_menu": {
|
||||
"text_001": "Назад: {value1}"
|
||||
},
|
||||
"registration_identity": {
|
||||
"title": "Выберите тип аккаунта",
|
||||
"immutable": "Тип аккаунта выбирается один раз при регистрации и впоследствии не может быть изменён.",
|
||||
"primary": "Основной аккаунт (Primary)",
|
||||
"primary_detail": "В SHiNE учитываются голоса реальных людей. Каждый человек имеет право иметь только один основной аккаунт.",
|
||||
"alternative": "Альтернативный аккаунт (Alternative)",
|
||||
"alternative_detail": "Вы можете иметь любое количество альтернативных аккаунтов. Лайки и рейтинги альтернативных аккаунтов учитываются отдельно от голосов реальных людей с основных аккаунтов.",
|
||||
"previous_detail": "Если у вас ранее были основные аккаунты, укажите их. Система анализа сможет проследить историю вашей личности по социальным связям, например когда друзья переходят от прежнего аккаунта к новому. Это только ваше заявление: прежние аккаунты не блокируются и их голоса пока не меняются.",
|
||||
"disclosure": "Ваше заявление будет публично записано в блокчейн и сохранено в публичном блокчейн-архиве. Статус аккаунта в будущем сможет проверять система анализа. Если вы предоставите ложную информацию, она останется в публичной истории блокчейна. Подтверждать владение прежними аккаунтами не требуется.",
|
||||
"add": "+ Добавить аккаунт",
|
||||
"remove": "Удалить из списка",
|
||||
"search": "Логин или имя пользователя",
|
||||
"find": "Найти",
|
||||
"not_found": "Подходящие аккаунты не найдены.",
|
||||
"search_error": "Не удалось выполнить поиск.",
|
||||
"next": "Продолжить"
|
||||
},
|
||||
"registration_stepper": {
|
||||
"text_001": "Регистрация: шаг {value1} из 3",
|
||||
"text_002": "Шаг {value1} из 3"
|
||||
"text_001": "Регистрация: шаг {value1} из 4",
|
||||
"text_002": "Шаг {value1} из 4"
|
||||
},
|
||||
"topbar_filter_title": {
|
||||
"text_001": "Выбрать раздел «{value1}»",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
|
||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||
import { publicLikeCount, hasLikeStatistics } from '../services/public-like-count.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { attachMessageMenu } from '../components/message-menu.js';
|
||||
@@ -624,9 +625,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
const versions = Array.isArray(node?.versions) ? node.versions : [];
|
||||
const versionsTotal = Number(node?.versionsTotal || versions.length || 1);
|
||||
const text = resolveNodeText(node) || (versionsTotal > 1 ? t('screens.channel_thread_view.text_060') : t('screens.channel_thread_view.text_061'));
|
||||
const likes = Number(node?.likesCount || 0);
|
||||
const primaryLikes = Number(node?.primaryLikesCount || 0);
|
||||
const shiningLikes = Number(node?.shiningLikesCount || 0);
|
||||
const likes = publicLikeCount(node);
|
||||
const replies = replyCountOf(node);
|
||||
const ratings = Number(node?.ratingsCount || 0);
|
||||
const isOwnMessage = Boolean(state.session.isAuthorized && state.session.login) && String(node?.authorLogin || '').trim().toLowerCase() === String(state.session.login).trim().toLowerCase();
|
||||
@@ -836,7 +835,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
const likesStatsButton = document.createElement('button');
|
||||
likesStatsButton.type = 'button';
|
||||
likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats';
|
||||
likesStatsButton.textContent = String(Number(likes) || '');
|
||||
likesStatsButton.textContent = String(likes);
|
||||
likesStatsButton.setAttribute('aria-label', t('screens.channel_thread_view.text_103', { value1: likes }));
|
||||
likesStatsButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
@@ -920,8 +919,8 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
|
||||
void handlers.onRepost?.(target);
|
||||
});
|
||||
if (threadsLayout) actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), shareButton, discussionButton);
|
||||
if (threadsLayout) actions.append(likeButton, ...(hasLikeStatistics(node) ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, ...(hasLikeStatistics(node) ? [likesStatsButton] : []), shareButton, discussionButton);
|
||||
const supportBtn = document.createElement('button');
|
||||
supportBtn.type = 'button';
|
||||
supportBtn.className = 'ui-button channel-action-item channel-action-support';
|
||||
@@ -1169,7 +1168,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
|
||||
setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked');
|
||||
const liked = getMessageReactionState(target) === 'liked';
|
||||
const likes = Number(node?.likesCount || 0);
|
||||
const likes = publicLikeCount(node);
|
||||
const like = document.createElement('button');
|
||||
like.type = 'button';
|
||||
like.className = `channel-action-item thread-comment__like${liked ? ' is-liked' : ''}`;
|
||||
@@ -1186,7 +1185,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
const commentLikeStats = document.createElement('button');
|
||||
commentLikeStats.type = 'button';
|
||||
commentLikeStats.className = 'channel-action-item thread-comment__like-count';
|
||||
commentLikeStats.textContent = String(likes || '');
|
||||
commentLikeStats.textContent = String(likes);
|
||||
commentLikeStats.setAttribute('aria-label', t('screens.channel_thread_view.text_107', { value1: likes }));
|
||||
commentLikeStats.addEventListener('click', () => { void showLikeStatistics({ counts: node }); });
|
||||
|
||||
@@ -1247,7 +1246,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
repost.addEventListener('click', () => (REPOSTS_ENABLED ? handlers.onRepost?.(target) : notifyRepostSoon()));
|
||||
|
||||
// Ряд действий как у записи канала: лайк, ответы, репост, поделиться.
|
||||
actions.append(like, ...(likes > 0 ? [commentLikeStats] : []), reply, repost, share);
|
||||
actions.append(like, ...(hasLikeStatistics(node) ? [commentLikeStats] : []), reply, repost, share);
|
||||
const supportBtn = document.createElement('button');
|
||||
supportBtn.type = 'button';
|
||||
supportBtn.className = 'channel-action-item thread-comment__support';
|
||||
|
||||
@@ -7,6 +7,7 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { openBlockchainDetailsModal } from '../components/blockchain-details-dialog.js';
|
||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||
import { publicLikeCount, hasLikeStatistics } from '../services/public-like-count.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
@@ -1990,7 +1991,7 @@ function renderPostCard(post, {
|
||||
<span class="channel-action-label">${isPending ? t('screens.channel_view.text_096') : t('screens.channel_view.text_097')}</span>
|
||||
`;
|
||||
likeButton.setAttribute('aria-pressed', String(isLiked));
|
||||
setActionTitle(likeButton, isPending ? t('screens.channel_view.text_098') : `${isLiked ? t('screens.channel_view.text_099') : t('screens.channel_view.text_100')}, ${post.likesCount || 0}`);
|
||||
setActionTitle(likeButton, isPending ? t('screens.channel_view.text_098') : `${isLiked ? t('screens.channel_view.text_099') : t('screens.channel_view.text_100')}, ${publicLikeCount(post)}`);
|
||||
likeButton.disabled = isPending;
|
||||
likeButton.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
@@ -2009,8 +2010,8 @@ function renderPostCard(post, {
|
||||
const likesStatsButton = document.createElement('button');
|
||||
likesStatsButton.type = 'button';
|
||||
likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats';
|
||||
likesStatsButton.textContent = String(Number(post.likesCount) || '');
|
||||
likesStatsButton.setAttribute('aria-label', t('screens.channel_view.text_150', { value1: Number(post.likesCount) || 0 }));
|
||||
likesStatsButton.textContent = String(publicLikeCount(post));
|
||||
likesStatsButton.setAttribute('aria-label', t('screens.channel_view.text_150', { value1: publicLikeCount(post) }));
|
||||
likesStatsButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
void showLikeStatistics({
|
||||
@@ -2158,8 +2159,8 @@ function renderPostCard(post, {
|
||||
} });
|
||||
});
|
||||
// Четыре кнопки как в Threads: лайк, ответы, репост, поделиться.
|
||||
if (threadsLayout) actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), shareButton, discussionButton);
|
||||
if (threadsLayout) actions.append(likeButton, ...(hasLikeStatistics(post) ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, ...(hasLikeStatistics(post) ? [likesStatsButton] : []), shareButton, discussionButton);
|
||||
actions.append(supportButton);
|
||||
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
|
||||
const streamRoute = makeShineChannelStreamRoute({
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
PROFILE_GENDER_MALE,
|
||||
PROFILE_GENDER_UNKNOWN,
|
||||
PROFILE_ACCOUNT_ROLE_PRIMARY,
|
||||
PROFILE_ACCOUNT_ROLE_NON_VOTING,
|
||||
PROFILE_SHINE_SHINING,
|
||||
PROFILE_SHINE_UNKNOWN,
|
||||
loadProfileSnapshot,
|
||||
@@ -36,18 +35,6 @@ function shineStatusLabel(value) {
|
||||
|
||||
|
||||
|
||||
function officialSteps(firstName, lastName) {
|
||||
const name = `${firstName} ${lastName}`.trim();
|
||||
return [
|
||||
{ title: t('dialogs.final.consent.official_steps.odin_chelovek_odin_ofitsialnyy_akkaunt'), text: t('dialogs.final.consent.official_steps.ofitsialnyy_akkaunt_vashe_zayavlenie_chto_eto_vash') },
|
||||
{ title: t('dialogs.final.consent.official_steps.priznanie_zavisit_ot_drugih_lyudey'), text: t('dialogs.final.consent.official_steps.samo_zayavlenie_ne_delaet_lichnost_proverennoy_dru') },
|
||||
{ title: t('dialogs.final.consent.official_steps.istoriya_perezhivaet_akkaunt'), text: t('dialogs.final.consent.official_steps.esli_vy_poteryaete_dostup_mozhno_zaregistrirovat_n') },
|
||||
{ title: t('dialogs.final.consent.official_steps.eto_deystvitelno_vy'), text: t('dialogs.final.consent.official_steps.v_profile_ukazano_value1_podtverzhdayte_tolko_esli', { value1: name }), accept: t('dialogs.final.consent.official_steps.podtverzhdayu_chto_value1_moi_nastoyaschie_imya_i', { value1: name }) },
|
||||
{ title: t('dialogs.final.consent.official_steps.podtverzhdaya_drugih_otvechayte_za_svoi_slova'), text: t('dialogs.final.consent.official_steps.ofitsialnyy_akkaunt_mozhet_podtverzhdat_osnovnye_a'), accept: t('dialogs.final.consent.official_steps.ponimayu_otvetstvennost_za_svoi_podtverzhdeniya') },
|
||||
{ title: t('dialogs.final.consent.official_steps.publichnaya_zapis'), text: t('dialogs.final.consent.official_steps.zayavlenie_i_buduschie_podtverzhdeniya_popadayut_v'), accept: t('dialogs.final.consent.official_steps.ya_ponimayu_publichnost_i_dolgovremennoe_hranenie'), button: t('dialogs.final.consent.official_steps.stat_ofitsialnym') },
|
||||
];
|
||||
}
|
||||
|
||||
function shiningSteps() { return [
|
||||
{ title: t('dialogs.final.consent.shining_steps.siyayuschiy_ofitsialnyy'), text: t('dialogs.final.consent.shining_steps.otmetit_sebya_siyayuschim_mozhno_i_s_neofitsialnog') },
|
||||
{ title: t('dialogs.final.consent.shining_steps.chto_znachit_siyayuschiy'), text: t('dialogs.final.consent.shining_steps.v_shine_eto_chelovek_kotoryy_zanimaetsya_vnutrenni') },
|
||||
@@ -120,7 +107,7 @@ export function render({ navigate, chrome }) {
|
||||
const badgesRow = document.createElement('div');
|
||||
badgesRow.className = 'chip-row profile-edit-statuses';
|
||||
badgesRow.innerHTML = `
|
||||
<button class="chip profile-toggle-btn is-no" type="button" data-status="account_role">${th('screens.profile_edit_view.text_029')}</button>
|
||||
<span class="badge is-no" data-status="account_role">${th('screens.profile_edit_view.text_029')}</span>
|
||||
<button class="chip profile-toggle-btn is-no" type="button" data-status="shine">${th('screens.profile_edit_view.text_030')}</button>
|
||||
`;
|
||||
|
||||
@@ -138,6 +125,7 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
let currentFields = [];
|
||||
let currentAccountRole = '';
|
||||
let currentAccountType = null;
|
||||
let currentShineStatus = '';
|
||||
let currentGender = PROFILE_GENDER_UNKNOWN;
|
||||
let statusFlowOpen = false;
|
||||
@@ -229,7 +217,9 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
function updateStatusesUi() {
|
||||
if (accountRoleBtn) {
|
||||
accountRoleBtn.textContent = t('screens.profile_edit_view.text_020', { value1: accountRoleLabel(currentAccountRole) });
|
||||
accountRoleBtn.textContent = currentAccountType === 1 ? t('screens.profile_edit_view.text_009')
|
||||
: currentAccountType === 0 ? t('screens.registration_identity.alternative')
|
||||
: t('screens.profile_edit_view.text_020', { value1: accountRoleLabel(currentAccountRole) });
|
||||
accountRoleBtn.classList.remove('is-no', 'is-yes-official', 'is-yes-shine', 'is-not-interested');
|
||||
accountRoleBtn.classList.add(currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY ? 'is-yes-official' : 'is-no');
|
||||
}
|
||||
@@ -341,13 +331,13 @@ export function render({ navigate, chrome }) {
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('dialogs.modals.profile_edit_view.label_003');
|
||||
reloadBtn.disabled = true;
|
||||
accountRoleBtn.disabled = true;
|
||||
shineBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const snapshot = await loadProfileSnapshot(login);
|
||||
currentFields = snapshot.fields;
|
||||
currentAccountRole = snapshot.accountRole || '';
|
||||
currentAccountType = snapshot.accountType;
|
||||
currentShineStatus = snapshot.shineStatus || '';
|
||||
currentGender = snapshot.gender || PROFILE_GENDER_UNKNOWN;
|
||||
currentAvatar = snapshot.avatar || { value: '', source: '', txId: '', pr: '', timeMs: 0 };
|
||||
@@ -366,7 +356,6 @@ export function render({ navigate, chrome }) {
|
||||
showLocalErrorAlert(t('screens.profile_edit_view.text_007'), error);
|
||||
} finally {
|
||||
reloadBtn.disabled = false;
|
||||
accountRoleBtn.disabled = false;
|
||||
shineBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
@@ -409,63 +398,28 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
|
||||
async function onStatusClick(statusKey) {
|
||||
if (statusFlowOpen) return;
|
||||
if (statusKey !== 'shine' || statusFlowOpen) return;
|
||||
statusFlowOpen = true;
|
||||
try {
|
||||
const isAccountRole = statusKey === 'account_role';
|
||||
const alreadyOn = isAccountRole
|
||||
? currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY
|
||||
: currentShineStatus === PROFILE_SHINE_SHINING;
|
||||
let accepted = false;
|
||||
if (alreadyOn) {
|
||||
accepted = await confirmDialog({
|
||||
title: isAccountRole ? t('dialogs.final.consent.remove_official') : t('dialogs.final.consent.remove_shining'),
|
||||
text: t('dialogs.pages.profile_edit_view.text_001'),
|
||||
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_002'),
|
||||
});
|
||||
} else if (isAccountRole) {
|
||||
const firstName = String(currentFields.find((field) => field.key === 'first_name')?.value || '').trim();
|
||||
const lastName = String(currentFields.find((field) => field.key === 'last_name')?.value || '').trim();
|
||||
if (!firstName || !lastName) {
|
||||
await confirmDialog({
|
||||
title: t('dialogs.pages.profile_edit_view.title_003'),
|
||||
text: t('dialogs.pages.profile_edit_view.text_004'),
|
||||
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_005'),
|
||||
cancelLabel: t('dialogs.pages.profile_edit_view.cancelLabel_006'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
accepted = await confirmConsentSteps({ title: t('dialogs.final.consent.official_title'), steps: officialSteps(firstName, lastName) });
|
||||
} else {
|
||||
accepted = await confirmConsentSteps({ title: t('dialogs.final.consent.shining_title'), steps: shiningSteps() });
|
||||
}
|
||||
const alreadyOn = currentShineStatus === PROFILE_SHINE_SHINING;
|
||||
const accepted = alreadyOn ? await confirmDialog({
|
||||
title: t('dialogs.final.consent.remove_shining'), text: t('dialogs.pages.profile_edit_view.text_001'),
|
||||
confirmLabel: t('dialogs.pages.profile_edit_view.confirmLabel_002'),
|
||||
}) : await confirmConsentSteps({ title: t('dialogs.final.consent.shining_title'), steps: shiningSteps() });
|
||||
if (!accepted || !screen.isConnected) return;
|
||||
const nextValue = isAccountRole
|
||||
? (alreadyOn ? PROFILE_ACCOUNT_ROLE_NON_VOTING : PROFILE_ACCOUNT_ROLE_PRIMARY)
|
||||
: (alreadyOn ? PROFILE_SHINE_UNKNOWN : PROFILE_SHINE_SHINING);
|
||||
status.className = 'status-line';
|
||||
status.textContent = t('dialogs.modals.profile_edit_view.label_009');
|
||||
accountRoleBtn.disabled = true;
|
||||
status.className = 'status-line'; status.textContent = t('dialogs.modals.profile_edit_view.label_009');
|
||||
shineBtn.disabled = true;
|
||||
try {
|
||||
await saveProfileStatus(login, statusKey, nextValue);
|
||||
if (!screen.isConnected) return;
|
||||
await refreshProfileSnapshot();
|
||||
await saveProfileStatus(login, 'shine', alreadyOn ? PROFILE_SHINE_UNKNOWN : PROFILE_SHINE_SHINING);
|
||||
if (screen.isConnected) await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
if (!screen.isConnected) return;
|
||||
status.className = 'status-line is-unavailable';
|
||||
const what = isAccountRole ? t('screens.profile_edit_view.text_017') : t('screens.profile_edit_view.text_018');
|
||||
const what = t('screens.profile_edit_view.text_018');
|
||||
status.textContent = t('screens.profile_edit_view.text_022', { value1: what, value2: toUserMessage(error, t('dialogs.modals.profile_edit_view.label_010')) });
|
||||
showLocalErrorAlert(t('screens.profile_edit_view.text_023', { value1: what }), error);
|
||||
} finally {
|
||||
if (screen.isConnected) {
|
||||
accountRoleBtn.disabled = false;
|
||||
shineBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
statusFlowOpen = false;
|
||||
}
|
||||
} finally { if (screen.isConnected) shineBtn.disabled = false; }
|
||||
} finally { statusFlowOpen = false; }
|
||||
}
|
||||
|
||||
async function onEditFieldClick(fieldKey) {
|
||||
@@ -547,7 +501,7 @@ export function render({ navigate, chrome }) {
|
||||
});
|
||||
|
||||
reloadBtn.addEventListener('click', refreshProfileSnapshot);
|
||||
accountRoleBtn.addEventListener('click', () => onStatusClick('account_role'));
|
||||
accountRoleBtn.title = t('screens.registration_identity.immutable');
|
||||
shineBtn.addEventListener('click', () => onStatusClick('shine'));
|
||||
avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); });
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createRegistrationStepper } from '../components/registration-stepper.js
|
||||
import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js';
|
||||
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
|
||||
import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js';
|
||||
import { savePendingHeaderIdentity } from '../services/pending-header-identity.js';
|
||||
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
|
||||
|
||||
export const pageMeta = { id: 'register-view', get title() { return t('screens.register_view.text_001'); }, showAppChrome: false };
|
||||
@@ -36,6 +37,10 @@ export function render({ navigate }) {
|
||||
return window.confirm(t('screens.register_view.text_039'));
|
||||
}
|
||||
function goBack() {
|
||||
if (Number(draft.uiStep) === 3) {
|
||||
showPassword();
|
||||
return;
|
||||
}
|
||||
if (Number(draft.uiStep) === 2) {
|
||||
draft.uiStep = 1;
|
||||
showLogin();
|
||||
@@ -220,7 +225,7 @@ export function render({ navigate }) {
|
||||
// Hide the password before navigation to prevent a visible flash.
|
||||
input.clearPasswordField();
|
||||
refreshPasswordCount();
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
showAccountType();
|
||||
} catch (error) {
|
||||
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028');
|
||||
} finally {
|
||||
@@ -231,11 +236,93 @@ export function render({ navigate }) {
|
||||
body.append(heading, description, label, guidance, status, next);
|
||||
}
|
||||
|
||||
function showAccountType() {
|
||||
draft.uiStep = 3;
|
||||
body.replaceChildren(createRegistrationStepper(3));
|
||||
const tr = key => t(`screens.registration_identity.${key}`);
|
||||
const [heading, description] = title(tr('title'), tr('immutable'));
|
||||
const choices = document.createElement('div'); choices.className = 'stack';
|
||||
const option = (type, name, detail) => {
|
||||
const label = document.createElement('label'); label.className = 'stack signup-guidance';
|
||||
const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'registration-account-type';
|
||||
radio.checked = draft.accountType === type;
|
||||
const titleRow = document.createElement('strong'); titleRow.append(radio, ' ' + tr(name));
|
||||
const p = document.createElement('p'); p.textContent = tr(detail);
|
||||
label.append(titleRow, p); choices.append(label);
|
||||
radio.addEventListener('change', () => { draft.accountType = type; refresh(); });
|
||||
};
|
||||
option(1, 'primary', 'primary_detail');
|
||||
option(0, 'alternative', 'alternative_detail');
|
||||
const previous = document.createElement('div'); previous.className = 'stack';
|
||||
const explanation = document.createElement('p'); explanation.textContent = tr('previous_detail');
|
||||
const disclosure = document.createElement('p'); disclosure.className = 'signup-guidance'; disclosure.textContent = tr('disclosure');
|
||||
const list = document.createElement('div'); list.className = 'stack';
|
||||
const add = document.createElement('button'); add.type = 'button'; add.className = 'secondary-btn'; add.textContent = tr('add');
|
||||
const searchBox = document.createElement('div'); searchBox.className = 'stack'; searchBox.hidden = true;
|
||||
const input = document.createElement('input'); input.className = 'input'; input.placeholder = tr('search'); input.autocomplete = 'off';
|
||||
const search = document.createElement('button'); search.type = 'button'; search.className = 'secondary-btn'; search.textContent = tr('find');
|
||||
const results = document.createElement('div'); results.className = 'stack';
|
||||
const status = statusLine();
|
||||
searchBox.append(input, search, results);
|
||||
previous.append(explanation, list, add, searchBox, disclosure);
|
||||
const next = document.createElement('button'); next.type = 'button'; next.className = 'primary-btn signup-next'; next.textContent = tr('next');
|
||||
let queryRevision = 0;
|
||||
function refresh() {
|
||||
previous.hidden = draft.accountType !== 1;
|
||||
next.disabled = draft.accountType === null;
|
||||
list.replaceChildren();
|
||||
for (const login of draft.previousAccounts) {
|
||||
const row = document.createElement('div'); row.className = 'signup-full-login';
|
||||
const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'secondary-btn'; remove.textContent = '×';
|
||||
remove.setAttribute('aria-label', `${tr('remove')} ${login}`);
|
||||
remove.addEventListener('click', () => { draft.previousAccounts = draft.previousAccounts.filter(v => v !== login); refresh(); });
|
||||
row.append(login, ' ', remove); list.append(row);
|
||||
}
|
||||
add.disabled = draft.previousAccounts.length >= 10;
|
||||
if (add.disabled || draft.accountType !== 1) { searchBox.hidden = true; results.replaceChildren(); queryRevision++; }
|
||||
}
|
||||
add.addEventListener('click', () => { searchBox.hidden = false; input.focus(); });
|
||||
input.addEventListener('input', () => { queryRevision++; results.replaceChildren(); });
|
||||
input.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); search.click(); } });
|
||||
search.addEventListener('click', async () => {
|
||||
const query = input.value.trim(); if (!query) return;
|
||||
const revision = ++queryRevision; results.replaceChildren(); status.textContent = '';
|
||||
try {
|
||||
const users = await authService.searchPeople(query, { limit: 20 });
|
||||
if (!screen.isConnected || draft.uiStep !== 3 || revision !== queryRevision || draft.accountType !== 1) return;
|
||||
const seen = new Set([draft.login, ...draft.previousAccounts].map(v => v.toLowerCase()));
|
||||
for (const user of users) {
|
||||
const login = String(user?.login || '');
|
||||
if (!login || seen.has(login.toLowerCase())) continue;
|
||||
seen.add(login.toLowerCase());
|
||||
const choose = document.createElement('button'); choose.type = 'button'; choose.className = 'secondary-btn';
|
||||
choose.textContent = login;
|
||||
choose.addEventListener('click', () => {
|
||||
if (draft.previousAccounts.length >= 10 || draft.accountType !== 1 || draft.previousAccounts.some(v => v.toLowerCase() === login.toLowerCase())) return;
|
||||
draft.previousAccounts.push(login); input.value = ''; searchBox.hidden = true; results.replaceChildren(); queryRevision++; refresh();
|
||||
});
|
||||
results.append(choose);
|
||||
}
|
||||
if (!results.childElementCount) status.textContent = tr('not_found');
|
||||
} catch (error) { if (screen.isConnected && revision === queryRevision) status.textContent = error.message || tr('search_error'); }
|
||||
});
|
||||
next.addEventListener('click', () => {
|
||||
if (![0, 1].includes(draft.accountType)) return;
|
||||
try {
|
||||
if (draft.accountType === 0) draft.previousAccounts = [];
|
||||
savePendingHeaderIdentity(draft.login, draft.preGeneratedKeyBundle?.blockchainPair?.publicKeyB64, draft);
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
} catch (error) { status.textContent = error.message; }
|
||||
});
|
||||
body.append(heading, description, choices, previous, status, next); refresh();
|
||||
}
|
||||
|
||||
if (flowType !== 'free' && flowType !== 'paid') {
|
||||
queueMicrotask(() => navigate('registration-choice-view'));
|
||||
return screen;
|
||||
}
|
||||
if (Number(draft.uiStep) === 2 && draft.login) showPassword();
|
||||
if (Number(draft.uiStep) === 3 && draft.login && draft.preGeneratedKeyBundle) showAccountType();
|
||||
else if (Number(draft.uiStep) === 2 && draft.login) showPassword();
|
||||
else showLogin();
|
||||
|
||||
void getRegistrationNamespaces().then(data => {
|
||||
|
||||
@@ -12,6 +12,9 @@ export function render({ navigate }) {
|
||||
const form = document.createElement('div');
|
||||
form.className = 'card stack registration-form signup-wizard__body';
|
||||
const draft = state.registrationDraft;
|
||||
if (![0, 1].includes(draft.accountType) || !draft.preGeneratedKeyBundle) {
|
||||
queueMicrotask(() => navigate('register-view')); return screen;
|
||||
}
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'signup-title';
|
||||
@@ -75,7 +78,7 @@ export function render({ navigate }) {
|
||||
edit.className = 'ghost-btn';
|
||||
edit.textContent = t('screens.registration_email_view.text_011');
|
||||
|
||||
form.append(createRegistrationStepper(3), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit);
|
||||
form.append(createRegistrationStepper(4), title, lead, inputLabel, info, status, next, codeLabel, codeInfo, confirm, resend, edit);
|
||||
let disposed = false;
|
||||
let emailRequestId = 0;
|
||||
let confirming = false;
|
||||
@@ -204,6 +207,6 @@ export function render({ navigate }) {
|
||||
} else {
|
||||
showEmail();
|
||||
}
|
||||
screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = 2; navigate('register-view'); } } }), form);
|
||||
screen.append(createTopBar({ title: t('screens.registration_email_view.text_025'), back: { label: '←', onClick: () => { draft.uiStep = 3; navigate('register-view'); } } }), form);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@ function clamp(value, min, max) {
|
||||
}
|
||||
|
||||
export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
const draft = state.registrationDraft;
|
||||
if (![0, 1].includes(draft.accountType)) throw new Error('Missing registration account type');
|
||||
// Финальный вход регистрации нельзя повторять на сокете, который мог
|
||||
// стать авторизованным после частично успешной предыдущей попытки.
|
||||
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
|
||||
@@ -115,7 +117,10 @@ export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
// После регистрации оба рабочих ключа сохраняются автоматически.
|
||||
// Приватный Recovery/root key не записывается на устройство.
|
||||
try {
|
||||
await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle);
|
||||
await authService.persistSelectedKeys(result.login, result.storagePwd, keyBundle, {
|
||||
saveRoot: true, saveBlockchain: true,
|
||||
headerIdentity: { accountType: draft.accountType, previousAccounts: [...draft.previousAccounts] },
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Не удалось сохранить рабочие ключи после регистрации; текущая сессия продолжает работать', error);
|
||||
}
|
||||
@@ -163,6 +168,9 @@ export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
if (![0, 1].includes(state.registrationDraft.accountType) || !state.registrationDraft.preGeneratedKeyBundle) {
|
||||
queueMicrotask(() => navigate('register-view')); return screen;
|
||||
}
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack registration-payment-card';
|
||||
@@ -438,14 +446,14 @@ export function render({ navigate }) {
|
||||
card.append(testHint);
|
||||
}
|
||||
card.append(submitButton, status);
|
||||
card.prepend(createRegistrationStepper(3));
|
||||
card.prepend(createRegistrationStepper(4));
|
||||
|
||||
screen.append(
|
||||
createTopBar({
|
||||
title: t('screens.registration_payment_view.text_022'),
|
||||
back: { label: '←', onClick: () => {
|
||||
if (parseBalanceSol(state.registrationPayment.balanceSOL) > 0 && !window.confirm(t('screens.registration_payment_view.text_071'))) return;
|
||||
state.registrationDraft.uiStep = 2; navigate('register-view');
|
||||
state.registrationDraft.uiStep = 3; navigate('register-view');
|
||||
} },
|
||||
}),
|
||||
card,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { confirmationRights } from '../services/account-voting.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
@@ -158,11 +159,8 @@ export function render({ route, chrome }) {
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
// Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует официальный аккаунт,
|
||||
// за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений.
|
||||
const selfPrimary = selfCard?.accountRole === 'primary';
|
||||
const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting';
|
||||
const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested';
|
||||
// Совпадает с серверными предикатами; отсутствие HEADER не даёт прав.
|
||||
const { primary: canPrimary, shine: canShine } = confirmationRights(selfCard, targetCard);
|
||||
|
||||
body.innerHTML = `
|
||||
<section class="card stack relation-manage-card relation-manage-card--social">
|
||||
@@ -212,6 +210,9 @@ export function render({ route, chrome }) {
|
||||
const social = button.dataset.socialKind;
|
||||
const confirm = button.dataset.confirm;
|
||||
if (!social && !confirm) return;
|
||||
const rights = confirmationRights(selfCard, targetCard);
|
||||
if (confirm === 'official_account' && !rights.primary) return;
|
||||
if (confirm === 'shine_confirmed' && !rights.shine) return;
|
||||
if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; }
|
||||
|
||||
const isAttestation = confirm === 'official_account' || confirm === 'shine_confirmed';
|
||||
|
||||
@@ -495,7 +495,14 @@ export function parseRouteFromPath(pathname = '') {
|
||||
}
|
||||
|
||||
export function getRoute() {
|
||||
return parseRouteFromPath(window.location.pathname || '');
|
||||
const path = window.location.pathname || '';
|
||||
// Нормализуем старые ссылки чатов также при прямом входе и Back/Forward.
|
||||
const pretty = path.replace(/^(\/(?:chat|chat-view)\/)([^/]+)/i, (_, prefix, id) => prefix + id.replace(/%40/gi, '@'));
|
||||
if (pretty !== path) {
|
||||
window.history.replaceState(window.history.state, '', pretty + window.location.search + window.location.hash);
|
||||
if (currentTrackedPath === path) currentTrackedPath = pretty;
|
||||
}
|
||||
return parseRouteFromPath(pretty);
|
||||
}
|
||||
|
||||
export function navigate(path) {
|
||||
@@ -557,7 +564,7 @@ export function toPrettyPath(path) {
|
||||
const prettyHead = PRETTY_PATHS.get(head) || head;
|
||||
// Старые вызовы навигации могут передавать %40 через encodeURIComponent.
|
||||
// Для публичных SHiNE-путей оставляем @ видимым, сохраняя остальные escape-коды.
|
||||
if (prettyHead.toLowerCase() === 'shine') {
|
||||
if (['shine', 'chat'].includes(prettyHead.toLowerCase())) {
|
||||
return [prettyHead, ...tail.map((segment) => segment.replace(/%40/gi, '@'))].join('/');
|
||||
}
|
||||
return [prettyHead, ...tail].join('/');
|
||||
|
||||
@@ -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' };
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ const INVALID_SESSION_CODES = new Set([
|
||||
function createEmptyRegistrationDraft() {
|
||||
return {
|
||||
uiStep: 1,
|
||||
accountType: null,
|
||||
previousAccounts: [],
|
||||
flowType: '',
|
||||
namespaceFeeLamports: '',
|
||||
namespaceServerLogin: '',
|
||||
|
||||
@@ -1930,16 +1930,41 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
};
|
||||
}
|
||||
|
||||
function parseHeaderBody(bodyBytes) {
|
||||
function parseHeaderBody(bodyBytes, version) {
|
||||
const reader = makeBigEndianReader(bodyBytes, 'HEADER');
|
||||
const tag = readUtf8(reader.readBytes(5));
|
||||
if (tag !== MAGIC) {
|
||||
throw new Error(`HEADER: неожиданный tag ${tag}`);
|
||||
}
|
||||
const login = reader.readUtf8U8();
|
||||
let accountType = null, previousAccounts = [], license = null;
|
||||
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 initialBlockchainKey = base64Url(reader.readBytes(32));
|
||||
reader.ensureDone();
|
||||
return { kind: 'header', login, tag, initialBlockchainKey };
|
||||
return { kind: 'header', login, tag, initialBlockchainKey, accountType, previousAccounts, license };
|
||||
}
|
||||
|
||||
function parseCreateChannelBody(bodyBytes, line) {
|
||||
@@ -2026,11 +2051,11 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
}
|
||||
|
||||
function parseBlockchainBody(type, subType, version, bodyBytes, line) {
|
||||
if (version !== 1) {
|
||||
if (version !== 1 && !(type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER && [2,3].includes(version))) {
|
||||
return { kind: 'unsupported', reason: `Неподдерживаемая версия body ${version}` };
|
||||
}
|
||||
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_HEADER) {
|
||||
return parseHeaderBody(bodyBytes);
|
||||
return parseHeaderBody(bodyBytes, version);
|
||||
}
|
||||
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_CREATE_CHANNEL) {
|
||||
return parseCreateChannelBody(bodyBytes, line);
|
||||
@@ -2069,7 +2094,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)!==(core.blockNumber===0)) throw new Error('Invalid CONTENT version/HEADER');
|
||||
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');
|
||||
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');
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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}));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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_\]\+/);
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user