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
@@ -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);
+22 -5
View File
@@ -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\">&nbsp;</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>",
+22 -5
View File
@@ -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}»",
+8 -9
View File
@@ -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';
+6 -5
View File
@@ -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({
+19 -65
View File
@@ -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(); });
+89 -2
View File
@@ -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 => {
+5 -2
View File
@@ -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;
}
+11 -3
View File
@@ -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';
+9 -2
View File
@@ -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('/');
+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}`);
}
+2
View File
@@ -32,6 +32,8 @@ const INVALID_SESSION_CODES = new Set([
function createEmptyRegistrationDraft() {
return {
uiStep: 1,
accountType: null,
previousAccounts: [],
flowType: '',
namespaceFeeLamports: '',
namespaceServerLogin: '',