SHA256
235 lines
13 KiB
JavaScript
235 lines
13 KiB
JavaScript
import { createTopBar } from '../components/topbar.js';
|
|
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
|
import { authService, clearAuthMessages, state } from '../state.js';
|
|
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
|
|
import { getRegistrationNamespaces, checkRegistrationLogin } from '../services/registration-v2-api.js';
|
|
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
|
|
|
|
export const pageMeta = { id: 'register-view', title: 'Регистрация', showAppChrome: false };
|
|
|
|
export function render({ navigate }) {
|
|
clearAuthMessages();
|
|
const draft = state.registrationDraft;
|
|
const screen = document.createElement('section');
|
|
screen.className = 'stack registration-screen signup-wizard';
|
|
const body = document.createElement('div');
|
|
body.className = 'card stack registration-form signup-wizard__body';
|
|
const header = createTopBar({ title: 'Регистрация в Сиянии', back: { label: '←', onClick: goBack } });
|
|
screen.append(header, body);
|
|
|
|
let namespaces = [];
|
|
let isLoading = true;
|
|
let fetchError = '';
|
|
let inputRevision = 0;
|
|
let requestId = 0;
|
|
let localDraft = String(draft.login || '').split('@')[0];
|
|
const flowType = draft.flowType;
|
|
|
|
function confirmFundedWalletChange() {
|
|
const balance = Number(state.registrationPayment?.balanceSOL || 0);
|
|
if (balance <= 0) return true;
|
|
return window.confirm('Внимание: кошелёк уже пополнен. Изменение логина или пароля создаст другой кошелёк! Средства останутся на старом адресе, и для доступа к ним потребуется прежний пароль. Продолжить?');
|
|
}
|
|
function goBack() {
|
|
if (Number(draft.uiStep) === 2) {
|
|
draft.uiStep = 1;
|
|
showLogin();
|
|
return;
|
|
}
|
|
navigate('registration-choice-view');
|
|
}
|
|
// Кнопка назад TopBar создана один раз, переход между шагами — внутри страницы.
|
|
function statusLine() {
|
|
const status = document.createElement('p');
|
|
status.className = 'status-line';
|
|
status.setAttribute('aria-live', 'polite');
|
|
return status;
|
|
}
|
|
function title(text, detail) {
|
|
const heading = document.createElement('h1');
|
|
heading.className = 'signup-title';
|
|
heading.textContent = text;
|
|
const subtitle = document.createElement('p');
|
|
subtitle.className = 'signup-lead';
|
|
subtitle.textContent = detail;
|
|
return [heading, subtitle];
|
|
}
|
|
function selectedNamespace() {
|
|
const candidates = namespaces.filter(n => Number(n.type) === (flowType === 'free' ? 2 : 1));
|
|
return candidates.find(n => String(n.name).toLowerCase() === (flowType === 'free' ? 'free' : 'shine')) || candidates[0];
|
|
}
|
|
function showLogin() {
|
|
draft.uiStep = 1;
|
|
body.replaceChildren(createRegistrationStepper(1));
|
|
const [heading, description] = title('Введите логин', 'Это имя навсегда сохранится и будет отображаться именно так, как вы выберете сейчас. Позже изменить его нельзя.');
|
|
const label = document.createElement('label');
|
|
label.className = 'stack';
|
|
const labelText = document.createElement('span');
|
|
labelText.className = 'field-label';
|
|
labelText.textContent = 'Ваш логин';
|
|
const input = document.createElement('input');
|
|
input.className = 'input';
|
|
input.placeholder = 'Например, Alice';
|
|
input.autocomplete = 'off';
|
|
input.autocapitalize = 'off';
|
|
input.spellcheck = false;
|
|
input.value = localDraft;
|
|
label.append(labelText, input);
|
|
const fullLogin = document.createElement('p');
|
|
fullLogin.className = 'signup-full-login';
|
|
const caseInfo = document.createElement('p');
|
|
caseInfo.className = 'meta-muted';
|
|
caseInfo.textContent = 'Регистр сохраняется: Alice и alice при проверке считаются одним логином, но отображаться будет выбранное написание всегда.';
|
|
const status = statusLine();
|
|
const next = document.createElement('button');
|
|
next.className = 'primary-btn signup-next';
|
|
next.textContent = 'Продолжить';
|
|
next.type = 'button';
|
|
next.disabled = isLoading;
|
|
function updateFull() {
|
|
const ns = selectedNamespace();
|
|
fullLogin.textContent = ns ? `${input.value.trim() || 'ВашЛогин'}@${ns.name}` : 'Пока нет доступного пространства имён';
|
|
status.textContent = fetchError;
|
|
next.disabled = isLoading || !ns;
|
|
}
|
|
input.addEventListener('input', () => { inputRevision++; localDraft = input.value; updateFull(); });
|
|
next.addEventListener('click', async () => {
|
|
const ns = selectedNamespace();
|
|
if (!ns) { status.textContent = 'Пространство имён пока недоступно'; return; }
|
|
let login;
|
|
try {
|
|
const local = input.value.trim();
|
|
if (local.length < Number(ns.minLocalLength)) throw new Error(`Минимальная длина логина: ${ns.minLocalLength} символов.`);
|
|
login = normalizeFullLogin(`${local}@${ns.name}`);
|
|
} catch (error) { status.textContent = error.message; return; }
|
|
const revision = inputRevision;
|
|
const thisRequest = ++requestId;
|
|
next.disabled = true;
|
|
status.textContent = 'Проверяем доступность логина…';
|
|
try {
|
|
const available = await checkRegistrationLogin(login);
|
|
if (!screen.isConnected || thisRequest !== requestId) return;
|
|
if (revision !== inputRevision) throw new Error('Логин изменился. Нажмите «Продолжить» ещё раз.');
|
|
if (!available.loginAvailable) throw new Error('Такой логин уже занят. Попробуйте другой.');
|
|
if (Number(available.namespaceType) !== Number(ns.type)) throw new Error('Тип регистрации изменился. Вернитесь к выбору аккаунта.');
|
|
if (draft.login !== login) {
|
|
if (!confirmFundedWalletChange()) return;
|
|
state.registrationPayment.walletAddress = '';
|
|
state.registrationPayment.balanceSOL = '0.0000';
|
|
draft.preGeneratedKeyBundle = null;
|
|
draft.challengeId = '';
|
|
draft.challengeExpiresAtMs = 0;
|
|
}
|
|
draft.login = login;
|
|
draft.namespaceFeeLamports = String(available.registrationFeeLamports ?? ns.registrationFeeLamports ?? 0);
|
|
draft.namespaceServerLogin = ns.defaultServerLogin || '';
|
|
draft.uiStep = 2;
|
|
showPassword();
|
|
} catch (error) {
|
|
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || 'Ошибка проверки логина.';
|
|
} finally {
|
|
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
|
|
}
|
|
});
|
|
body.append(heading, description, label, fullLogin, caseInfo, status, next);
|
|
updateFull();
|
|
}
|
|
function showPassword() {
|
|
draft.uiStep = 2;
|
|
body.replaceChildren(createRegistrationStepper(2));
|
|
const [heading, description] = title('Придумайте пароль', 'На вашем устройстве из логина и пароля создаются криптографические ключи доступа. Приватные ключи не хранятся на сервере.');
|
|
const label = document.createElement('label');
|
|
label.className = 'stack';
|
|
const labelText = document.createElement('span');
|
|
labelText.className = 'field-label';
|
|
labelText.textContent = `Пароль (от 1 до ${PASSWORD_MAX_LENGTH} символов)`;
|
|
const input = document.createElement('input');
|
|
input.className = 'input';
|
|
input.type = 'text';
|
|
input.autocomplete = 'new-password';
|
|
input.maxLength = PASSWORD_MAX_LENGTH;
|
|
input.placeholder = 'Ваш секретный пароль';
|
|
input.value = draft.password || '';
|
|
const toggle = document.createElement('button');
|
|
toggle.className = 'secondary-btn';
|
|
toggle.type = 'button';
|
|
toggle.textContent = 'Скрыть';
|
|
toggle.setAttribute('aria-label', 'Показать или скрыть пароль');
|
|
toggle.addEventListener('click', () => {
|
|
input.type = input.type === 'password' ? 'text' : 'password';
|
|
toggle.textContent = input.type === 'password' ? 'Показать' : 'Скрыть';
|
|
});
|
|
label.append(labelText, input);
|
|
const guidance = document.createElement('div');
|
|
guidance.className = 'signup-guidance';
|
|
guidance.innerHTML = `
|
|
<strong>Лучший пароль — тот, который вы точно помните.</strong>
|
|
<p>Подойдёт любой непустой пароль. Для надёжности лучше выбрать свою длинную фразу или случайный код. Не используйте известные цитаты и очевидные последовательности.</p>
|
|
<p>На привычном устройстве обычно не придётся вводить пароль при каждом входе: рабочие ключи сохраняются локально. Для входа с нового устройства пароль — ваш резервный способ доступа.</p>
|
|
<p class="signup-guidance__warning"><strong>Не теряйте пароль!</strong> Мы не можем восстановить его или ваши ключи. Если доступ к ключам на всех устройствах утрачен, зашифрованная личная переписка может оказаться недоступна.</p>
|
|
<p>${flowType === 'free'
|
|
? 'В бесплатном аккаунте смена пароля недоступна. После перехода на полноценный аккаунт появится возможность его менять.'
|
|
: 'Для полноценного аккаунта поддерживается смена пароля: необходимые зашифрованные сообщения перешифровываются на вашем устройстве, а не на сервере.'}</p>
|
|
`;
|
|
const status = statusLine();
|
|
const next = document.createElement('button');
|
|
next.className = 'primary-btn signup-next';
|
|
next.type = 'button';
|
|
next.textContent = 'Продолжить';
|
|
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; });
|
|
next.addEventListener('click', async () => {
|
|
const value = input.value;
|
|
if (value.length < 1 || value.length > PASSWORD_MAX_LENGTH) {
|
|
status.textContent = `Введите пароль длиной от 1 до ${PASSWORD_MAX_LENGTH} символов.`;
|
|
return;
|
|
}
|
|
if (!draft.login || !draft.login.includes('@')) { status.textContent = 'Сначала выберите логин.'; return; }
|
|
if (draft.password && draft.password !== value && !confirmFundedWalletChange()) return;
|
|
if (draft.password && draft.password !== value) {
|
|
state.registrationPayment.walletAddress = '';
|
|
state.registrationPayment.balanceSOL = '0.0000';
|
|
draft.challengeId = '';
|
|
draft.challengeExpiresAtMs = 0;
|
|
}
|
|
const revision = inputRevision;
|
|
const thisRequest = ++requestId;
|
|
next.disabled = true;
|
|
status.textContent = 'Генерируем ключи из пароля на этом устройстве…';
|
|
try {
|
|
const changed = draft.password !== value;
|
|
draft.password = value;
|
|
if (changed) draft.preGeneratedKeyBundle = null;
|
|
const bundle = draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(draft.login, value);
|
|
if (!screen.isConnected || thisRequest !== requestId) return;
|
|
if (revision !== inputRevision) throw new Error('Пароль изменился. Нажмите «Продолжить» ещё раз.');
|
|
draft.preGeneratedKeyBundle = bundle;
|
|
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
|
} catch (error) {
|
|
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || 'Не удалось создать ключи.';
|
|
} finally {
|
|
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
|
|
}
|
|
});
|
|
body.append(heading, description, label, toggle, guidance, status, next);
|
|
}
|
|
|
|
if (flowType !== 'free' && flowType !== 'paid') {
|
|
queueMicrotask(() => navigate('registration-choice-view'));
|
|
return screen;
|
|
}
|
|
if (Number(draft.uiStep) === 2 && draft.login) showPassword();
|
|
else showLogin();
|
|
|
|
void getRegistrationNamespaces().then(data => {
|
|
namespaces = Array.isArray(data.namespaces) ? data.namespaces : [];
|
|
isLoading = false;
|
|
if (!selectedNamespace()) fetchError = 'Сервер пока не предоставил пространство имён для выбранного типа регистрации.';
|
|
if (screen.isConnected && Number(draft.uiStep) === 1) showLogin();
|
|
}).catch(error => {
|
|
isLoading = false;
|
|
fetchError = `Не удалось загрузить пространства имён: ${error.message}`;
|
|
if (screen.isConnected && Number(draft.uiStep) === 1) showLogin();
|
|
});
|
|
return screen;
|
|
}
|