Регистрация V2: не проверено end-to-end

This commit is contained in:
AidarKC
2026-10-23 19:21:52 +03:00
parent 6c8159c5f7
commit cab26bbf41
95 changed files with 4469 additions and 1088 deletions
+72 -413
View File
@@ -1,427 +1,86 @@
import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js';
import { authService, clearAuthMessages, resetRegistrationFlow, state } from '../state.js';
import { toUserMessage } from '../services/ui-error-texts.js';
import {
checkLoginExistsOnSolana,
formatSolanaErrorDetails,
isSolanaRpcUnavailableError,
precheckLoginClassOnSolana,
} from '../services/solana-register-service.js';
import {
emptyPasswordWords,
PASSWORD_MAX_LENGTH,
} from '../services/password-words.js';
import { openRegistrationFaq } from './registration-faq-view.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 };
const MIN_REGISTRATION_LOGIN_LENGTH = 8;
function normalizeLoginForTemporaryUiGuard(login) {
const source = String(login || '').trim();
if (!source || source.length > 20) return null;
let normalized = '';
for (const ch of source) {
if (ch === '_') continue;
if (!/[0-9A-Za-z]/.test(ch)) return null;
normalized += ch.toLowerCase();
}
if (!normalized || normalized.length > 20) return null;
return normalized;
}
function makePasswordToggleIcons() {
return {
eye: iconHtml('eye', false, 'key-toggle-icon'),
eyeOff: iconHtml('eyeOff', false, 'key-toggle-icon'),
};
}
export function render({ navigate }) {
const screen = document.createElement('section');
screen.className = 'stack registration-screen';
export function render({navigate}) {
clearAuthMessages();
const form = document.createElement('div');
form.className = 'card stack registration-form';
state.registrationDraft.passwordMode = 'single';
state.registrationDraft.passwordWords = emptyPasswordWords();
state.registrationDraft.passwordWordsLinked = false;
state.registrationDraft.usePromoCode = false;
state.registrationDraft.promoCode = '';
let loginCheckTimer = 0;
let loginCheckRunId = 0;
const loginInput = document.createElement('input');
loginInput.className = 'input';
loginInput.type = 'text';
loginInput.autocomplete = 'off';
loginInput.autocapitalize = 'off';
loginInput.spellcheck = false;
loginInput.value = state.registrationDraft.login;
loginInput.placeholder = 'Введите логин';
const passwordInput = document.createElement('input');
passwordInput.className = 'input';
passwordInput.type = 'password';
passwordInput.name = 'shine-register-password';
passwordInput.autocomplete = 'new-password';
passwordInput.autocapitalize = 'off';
passwordInput.spellcheck = false;
passwordInput.maxLength = PASSWORD_MAX_LENGTH;
passwordInput.value = String(state.registrationDraft.password || '');
passwordInput.placeholder = 'Введите пароль';
const passwordIcons = makePasswordToggleIcons();
const passwordToggleButton = document.createElement('button');
passwordToggleButton.className = 'icon-btn key-toggle-btn registration-password-toggle';
passwordToggleButton.type = 'button';
passwordToggleButton.setAttribute('aria-label', 'Показать пароль');
passwordToggleButton.setAttribute('title', 'Показать пароль');
passwordToggleButton.innerHTML = passwordIcons.eyeOff;
const passwordInputRow = document.createElement('div');
passwordInputRow.className = 'inline-input-row';
passwordInputRow.append(passwordInput, passwordToggleButton);
// Строка под логином всегда занимает место — сообщения не сдвигают форму.
const statusText = document.createElement('span');
statusText.className = 'status-line registration-login-status';
statusText.setAttribute('aria-live', 'polite');
const formError = document.createElement('p');
formError.className = 'status-line is-unavailable';
formError.style.display = 'none';
// Компактная ссылка на экран «Вопросы о регистрации» (registration-faq-view).
const faqButton = document.createElement('button');
faqButton.className = 'registration-faq-link';
faqButton.type = 'button';
faqButton.textContent = 'Вопросы о регистрации';
faqButton.addEventListener('click', () => openRegistrationFaq(navigate, 'key-derivation'));
const actions = document.createElement('div');
actions.className = 'auth-footer-actions';
const nextButton = document.createElement('button');
nextButton.className = 'primary-btn';
nextButton.type = 'button';
nextButton.textContent = 'Далее';
const passwordLengthText = document.createElement('p');
passwordLengthText.className = 'password-length-hint';
let lastCheckedLogin = '';
let lastCheckedFree = false;
let lastCheckedClassName = '';
let generationRunId = 0;
function getCurrentPassword() {
return String(passwordInput.value || '');
}
function updatePasswordLength() {
passwordLengthText.textContent = `Символов в пароле: ${getCurrentPassword().length}`;
}
function setStatusMessage(message, kind = '', details = '') {
statusText.textContent = message;
statusText.title = details || message;
statusText.className = kind ? `status-line registration-login-status ${kind}` : 'status-line registration-login-status';
}
function showCheckedLoginStatus(isFree, className) {
if (!isFree) {
setStatusMessage('Логин уже занят', 'is-unavailable');
} else if (className === 'free') {
setStatusMessage('Логин свободен', 'is-available');
} else if (className === 'premium') {
setStatusMessage('Премиум-логин – покупка через DAO', 'is-unavailable');
} else if (className === 'company') {
setStatusMessage('Логин бренда – нужно согласование', 'is-unavailable');
} else {
setStatusMessage('Не подходит для обычной регистрации', 'is-unavailable');
const screen=document.createElement('section'); screen.className='stack registration-screen';
const form=document.createElement('div'); form.className='card stack registration-form';
const method=document.createElement('select'); method.className='input';
method.innerHTML='<option value="1">Регистрация через Solana</option><option value="2">Бесплатная регистрация</option>';
method.value=state.registrationDraft.flowType==='free'?'2':'1';
const namespace=document.createElement('select'); namespace.className='input';
const local=document.createElement('input'); local.className='input'; local.placeholder='Логин (без @)';
local.autocomplete='off';local.spellcheck=false;local.autocapitalize='off';
local.value=String(state.registrationDraft.login || '').split('@')[0];
const full=document.createElement('p'); full.className='meta-muted';
const password=document.createElement('input'); password.className='input';password.type='password';
password.autocomplete='new-password';password.maxLength=PASSWORD_MAX_LENGTH;
password.placeholder='Пароль';password.value=state.registrationDraft.password || '';
const status=document.createElement('p'); status.className='status-line';status.setAttribute('aria-live','polite');
const action=document.createElement('button');action.className='primary-btn';action.textContent='Проверить логин и продолжить';
const nsLabel=document.createElement('label');nsLabel.className='stack';nsLabel.textContent='Пространство имён'; nsLabel.append(namespace);
const methodLabel=document.createElement('label');methodLabel.className='stack'; methodLabel.textContent='Способ регистрации';methodLabel.append(method);
const pwLabel=document.createElement('label');pwLabel.className='stack';pwLabel.textContent='Пароль (ключи остаются только у вас)';pwLabel.append(password);
form.append(methodLabel,nsLabel,local,full,pwLabel,status,action);
let namespaces=[]; let disposed=false; let request=0;
const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6);
function selected() { return namespaces.find(n=>n.name===namespace.value); }
function display() {
namespace.replaceChildren();
for (const ns of namespaces.filter(n=>Number(n.type)===Number(method.value))) {
const opt=document.createElement('option');opt.value=ns.name;
opt.textContent=`@${ns.name} · от ${ns.minLocalLength} симв. · ${feeToSol(ns.registrationFeeLamports)} SOL`;
namespace.append(opt);
}
}
function resetLoginCheckState() {
lastCheckedLogin = '';
lastCheckedFree = false;
lastCheckedClassName = '';
loginCheckRunId += 1;
if (loginCheckTimer) {
window.clearTimeout(loginCheckTimer);
loginCheckTimer = 0;
if (state.registrationDraft.login.includes('@')) {
const wanted=state.registrationDraft.login.split('@')[1];
if([...namespace.options].some(x=>x.value===wanted))namespace.value=wanted;
}
showFull();
}
function scheduleAvailabilityCheck() {
resetLoginCheckState();
setStatusMessage('');
if (!loginInput.value.trim()) return;
loginCheckTimer = window.setTimeout(() => {
loginCheckTimer = 0;
runAvailabilityCheck({ automatic: true }).catch(() => {});
}, 1500);
function showFull() {
full.textContent=namespace.value?`Полное имя: ${local.value.trim()}@${namespace.value}`:'Нет доступных namespace этого типа';
status.textContent='';request++;
}
function togglePasswordVisibility() {
const reveal = passwordInput.type === 'password';
passwordInput.type = reveal ? 'text' : 'password';
passwordToggleButton.innerHTML = reveal ? passwordIcons.eye : passwordIcons.eyeOff;
passwordToggleButton.setAttribute('aria-label', reveal ? 'Скрыть пароль' : 'Показать пароль');
passwordToggleButton.setAttribute('title', reveal ? 'Скрыть пароль' : 'Показать пароль');
}
function syncDraftState() {
state.registrationDraft.login = String(loginInput.value.trim());
state.registrationDraft.password = getCurrentPassword();
}
async function runAvailabilityCheck({ automatic = false } = {}) {
const runId = ++loginCheckRunId;
const login = loginInput.value.trim();
if (!login) {
setStatusMessage(automatic ? '' : 'Введите логин');
formError.style.display = 'none';
return false;
}
const normalizedLogin = normalizeLoginForTemporaryUiGuard(login);
if (!normalizedLogin) {
setStatusMessage('Только латиница, цифры и _, до 20 символов', 'is-unavailable');
formError.style.display = 'none';
return false;
}
if (normalizedLogin.length < MIN_REGISTRATION_LOGIN_LENGTH) {
setStatusMessage(`Не короче ${MIN_REGISTRATION_LOGIN_LENGTH} символов`, 'is-unavailable');
formError.style.display = 'none';
return false;
}
if (login === lastCheckedLogin) {
showCheckedLoginStatus(lastCheckedFree, lastCheckedClassName);
formError.style.display = 'none';
return lastCheckedFree && lastCheckedClassName === 'free';
}
setStatusMessage('Проверяем логин…', 'is-checking');
method.addEventListener('change',display);namespace.addEventListener('change',showFull);local.addEventListener('input',showFull);
void getRegistrationNamespaces().then(data=>{
if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display();
if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером';
}).catch(error=>{if(!disposed)status.textContent=`Не удалось получить namespace: ${error.message}`;});
action.addEventListener('click',async()=>{
const ns=selected();if(!ns){status.textContent='Выберите доступный namespace';return;}
let login;
try {
const check = await checkLoginExistsOnSolana({
login,
solanaEndpoint: state.entrySettings.solanaServer,
});
if (runId !== loginCheckRunId) return false;
const isFree = !check.exists;
let className = '';
if (isFree) {
try {
const precheck = await precheckLoginClassOnSolana({
login,
solanaEndpoint: state.entrySettings.solanaServer,
});
className = precheck.className;
} catch (precheckError) {
className = 'free';
console.warn('Solana login precheck fallback to free', formatSolanaErrorDetails(precheckError));
}
}
lastCheckedLogin = login;
lastCheckedFree = isFree;
lastCheckedClassName = className;
showCheckedLoginStatus(isFree, className);
formError.style.display = 'none';
return isFree && className === 'free';
} catch (error) {
if (runId !== loginCheckRunId) return false;
if (isSolanaRpcUnavailableError(error)) {
setStatusMessage('Нет связи с Solana – попробуйте позже', 'is-unavailable');
return false;
}
const base = toUserMessage(error, 'Не удалось проверить логин');
const details = formatSolanaErrorDetails(error);
setStatusMessage(base, 'is-unavailable', `${base}. Детали: ${details}`);
return false;
}
}
passwordToggleButton.addEventListener('click', togglePasswordVisibility);
loginInput.addEventListener('input', () => {
syncDraftState();
scheduleAvailabilityCheck();
});
passwordInput.addEventListener('input', () => {
syncDraftState();
updatePasswordLength();
});
nextButton.addEventListener('click', async () => {
formError.style.display = 'none';
const isFree = await runAvailabilityCheck();
if (!isFree) return;
const prevLogin = String(state.registrationDraft.login || '');
const prevPassword = String(state.registrationDraft.password || '');
const nextLogin = String(loginInput.value.trim());
const nextPassword = getCurrentPassword();
if (nextPassword.length === 0) {
formError.textContent = 'Пустой пароль запрещён. Введите непустой пароль для регистрации.';
formError.style.display = '';
return;
}
if (nextPassword.length > PASSWORD_MAX_LENGTH) {
formError.textContent = `Пароль получился слишком длинным. Максимальная длина: ${PASSWORD_MAX_LENGTH} символов.`;
formError.style.display = '';
return;
}
const credsChanged = prevLogin !== nextLogin || prevPassword !== nextPassword;
state.registrationDraft.login = nextLogin;
state.registrationDraft.password = nextPassword;
if (credsChanged) {
state.registrationDraft.preGeneratedKeyBundle = null;
}
startGenerationStage();
});
function renderInputStage() {
form.innerHTML = '';
const loginField = document.createElement('label');
loginField.className = 'stack';
loginField.innerHTML = '<span class="field-label">Логин</span>';
const passwordLabel = document.createElement('label');
passwordLabel.className = 'stack registration-password-single';
passwordLabel.innerHTML = '<span class="field-label">Пароль</span>';
form.append(loginField, passwordLabel);
loginField.append(loginInput, statusText);
passwordLabel.append(passwordInputRow);
form.append(passwordLengthText, formError, faqButton);
actions.innerHTML = '';
actions.append(nextButton);
updatePasswordLength();
syncDraftState();
}
async function startGenerationStage() {
const runId = ++generationRunId;
form.innerHTML = '';
const title = document.createElement('p');
title.className = 'auth-copy';
title.textContent = 'Для повышения безопасности мы генерируем секрет из вашего логина и пароля с помощью Argon2id.';
const subtitle = document.createElement('p');
subtitle.className = 'meta-muted';
subtitle.textContent = 'Процесс запускается сразу: из этого секрета будут вычислены ключ восстановления, ключ блокчейна и ключ доступа.';
const details = document.createElement('p');
details.className = 'meta-muted';
details.textContent = 'Параметры: t=2, m=65536 KiB (64 MB), p=1, dkLen=32.';
const details2 = document.createElement('p');
details2.className = 'meta-muted';
details2.textContent = 'Замедление нужно специально: оно усложняет подбор пароля и повышает цену атак на видеокартах и GPU.';
const details3 = document.createElement('p');
details3.className = 'meta-muted';
details3.textContent = `Длина вашего текущего пароля: ${getCurrentPassword().length} символов.`;
const progressWrap = document.createElement('div');
progressWrap.className = 'registration-progress';
const progressBar = document.createElement('div');
progressBar.className = 'registration-progress-bar';
progressWrap.append(progressBar);
const progressText = document.createElement('p');
progressText.className = 'meta-muted';
progressText.textContent = 'Подготовка...';
const genError = document.createElement('p');
genError.className = 'status-line is-unavailable';
genError.style.display = 'none';
form.append(title, subtitle, details, details2, details3, progressWrap, progressText, genError);
const cancelBtn = document.createElement('button');
cancelBtn.className = 'ghost-btn';
cancelBtn.type = 'button';
cancelBtn.textContent = 'Отмена';
cancelBtn.addEventListener('click', () => {
generationRunId += 1;
renderInputStage();
});
actions.innerHTML = '';
actions.append(cancelBtn);
login=normalizeFullLogin(`${local.value.trim()}@${ns.name}`);
if(local.value.trim().length < Number(ns.minLocalLength))throw new Error(`Логин не короче ${ns.minLocalLength} символов`);
if(!password.value || password.value.length>PASSWORD_MAX_LENGTH)throw new Error('Введите непустой пароль допустимой длины');
}catch(error){status.textContent=error.message;return;}
const thisRun=++request;
action.disabled=true;status.textContent='Проверяем выбранный логин…';
try {
if (!state.registrationDraft.preGeneratedKeyBundle) {
const keyBundle = await authService.derivePasswordKeyBundle(
state.registrationDraft.login,
state.registrationDraft.password,
{
onProgress: ({ percent, message }) => {
if (runId !== generationRunId) return;
const safePercent = Math.max(0, Math.min(100, Number(percent) || 0));
progressBar.style.width = `${safePercent}%`;
progressText.textContent = `${safePercent}% · ${String(message || '').trim()}`;
},
isCancelled: () => runId !== generationRunId,
},
);
if (runId !== generationRunId) return;
state.registrationDraft.preGeneratedKeyBundle = keyBundle;
}
if (runId !== generationRunId) return;
progressBar.style.width = '100%';
progressText.textContent = '100%';
title.textContent = 'Ключи сгенерированы';
window.setTimeout(() => navigate('registration-payment-view'), 350);
} catch (error) {
if (runId !== generationRunId) return;
if (String(error?.message || '') === 'DERIVE_CANCELLED') {
renderInputStage();
return;
}
genError.textContent = `Ошибка генерации ключей: ${error?.message || 'неизвестная ошибка'}`;
genError.style.display = '';
const retry = document.createElement('button');
retry.className = 'primary-btn';
retry.type = 'button';
retry.textContent = 'Повторить';
retry.addEventListener('click', startGenerationStage);
const goBack = document.createElement('button');
goBack.className = 'ghost-btn';
goBack.type = 'button';
goBack.textContent = 'Назад';
goBack.addEventListener('click', renderInputStage);
actions.innerHTML = '';
actions.append(goBack, retry);
}
}
renderInputStage();
screen.append(
createTopBar({
title: 'Регистрация',
back: {
label: '←',
onClick: () => {
resetRegistrationFlow();
navigate('start-view');
},
},
}),
form,
actions,
);
const check=await checkRegistrationLogin(login);
if(disposed || thisRun!==request)return;
if(!check.loginAvailable)throw new Error('Этот логин уже занят');
if(Number(check.namespaceType)!==Number(method.value))throw new Error('Тип namespace изменился. Обновите список.');
const draft=state.registrationDraft;
const changed=draft.login!==login || draft.password!==password.value;
draft.login=login;draft.password=password.value;draft.flowType=method.value==='2'?'free':'paid';
draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports);
draft.namespaceServerLogin=ns.defaultServerLogin||'';
if(changed)draft.preGeneratedKeyBundle=null;
status.textContent='Создаём ключи локально (Argon2id)…';
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
if(disposed || thisRun!==request)return;
draft.preGeneratedKeyBundle=bundle;
navigate(draft.flowType==='free'?'registration-email-view':'registration-payment-view');
}catch(error){if(!disposed && thisRun===request)status.textContent=error.message;}
finally {action.disabled=false;}
});
screen.append(createTopBar({title:'Регистрация',back:{label:'←',onClick:()=>{resetRegistrationFlow();navigate('start-view');}}}),form);
return screen;
}