SHA256
Регистрация: бесплатная регистрация работает
This commit is contained in:
@@ -27,7 +27,7 @@ export function render({navigate}) {
|
||||
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;
|
||||
let namespaces=[]; let disposed=false; let inputRevision=0; let submission=0;
|
||||
const feeToSol = fee => (Number(fee || '0')/1e9).toFixed(6);
|
||||
function selected() { return namespaces.find(n=>n.name===namespace.value); }
|
||||
function display() {
|
||||
@@ -45,9 +45,11 @@ export function render({navigate}) {
|
||||
}
|
||||
function showFull() {
|
||||
full.textContent=namespace.value?`Полное имя: ${local.value.trim()}@${namespace.value}`:'Нет доступных namespace этого типа';
|
||||
status.textContent='';request++;
|
||||
status.textContent='';
|
||||
}
|
||||
method.addEventListener('change',display);namespace.addEventListener('change',showFull);local.addEventListener('input',showFull);
|
||||
method.addEventListener('change',()=>{inputRevision++;display();});
|
||||
namespace.addEventListener('change',()=>{inputRevision++;showFull();});
|
||||
local.addEventListener('input',()=>{inputRevision++;showFull();});
|
||||
void getRegistrationNamespaces().then(data=>{
|
||||
if(disposed)return;namespaces=Array.isArray(data.namespaces)?data.namespaces:[];display();
|
||||
if(!namespaces.length)status.textContent='Solana namespace ещё не синхронизированы с сервером';
|
||||
@@ -60,11 +62,13 @@ export function render({navigate}) {
|
||||
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;
|
||||
const thisRun=++submission;
|
||||
const thisInputRevision=inputRevision;
|
||||
action.disabled=true;status.textContent='Проверяем выбранный логин…';
|
||||
try {
|
||||
const check=await checkRegistrationLogin(login);
|
||||
if(disposed || thisRun!==request)return;
|
||||
if(disposed || thisRun!==submission)return;
|
||||
if(thisInputRevision!==inputRevision)throw new Error('Данные формы изменились. Проверьте их и повторите попытку.');
|
||||
if(!check.loginAvailable)throw new Error('Этот логин уже занят');
|
||||
if(Number(check.namespaceType)!==Number(method.value))throw new Error('Тип namespace изменился. Обновите список.');
|
||||
const draft=state.registrationDraft;
|
||||
@@ -73,13 +77,17 @@ export function render({navigate}) {
|
||||
draft.namespaceFeeLamports=String(check.registrationFeeLamports||ns.registrationFeeLamports);
|
||||
draft.namespaceServerLogin=ns.defaultServerLogin||'';
|
||||
if(changed)draft.preGeneratedKeyBundle=null;
|
||||
if(draft.flowType==='free') {
|
||||
navigate('registration-email-view');
|
||||
return;
|
||||
}
|
||||
status.textContent='Создаём ключи локально (Argon2id)…';
|
||||
const bundle=draft.preGeneratedKeyBundle || await authService.derivePasswordKeyBundle(login,password.value);
|
||||
if(disposed || thisRun!==request)return;
|
||||
if(disposed || thisRun!==submission)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;}
|
||||
navigate('registration-payment-view');
|
||||
}catch(error){if(!disposed && thisRun===submission)status.textContent=error.message || 'Не удалось продолжить регистрацию.';}
|
||||
finally {if(thisRun===submission)action.disabled=false;}
|
||||
});
|
||||
screen.append(createTopBar({title:'Регистрация',back:{label:'←',onClick:()=>{resetRegistrationFlow();navigate('start-view');}}}),form);
|
||||
return screen;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { state } from '../state.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { checkRegistrationEmail, startFreeRegistration, confirmFreeRegistration } from '../services/registration-v2-api.js';
|
||||
import { completeRegistrationLogin } from './registration-payment-view.js';
|
||||
|
||||
@@ -24,13 +24,18 @@ export function render({navigate}) {
|
||||
let disposed=false;
|
||||
function showConfirm(){ input.disabled=true;next.hidden=true;code.hidden=false;codeLabel.hidden=false;confirm.hidden=false;retry.hidden=false; }
|
||||
next.addEventListener('click',async()=>{
|
||||
if(!draft.preGeneratedKeyBundle || draft.flowType!=='free'){status.textContent='Сначала подготовьте ключи на предыдущем экране';return;}
|
||||
if(draft.flowType!=='free'){status.textContent='Выберите бесплатную регистрацию на предыдущем экране';return;}
|
||||
next.disabled=true;status.textContent='Проверяем email…';
|
||||
try {
|
||||
const address=input.value.trim();
|
||||
const available=await checkRegistrationEmail(address);
|
||||
if(!available.emailAvailable) throw new Error('Этот email уже использован для бесплатной регистрации');
|
||||
draft.email=address;
|
||||
if(!draft.preGeneratedKeyBundle){
|
||||
if(!draft.login || !draft.password) throw new Error('Логин или пароль не сохранены. Вернитесь на предыдущий экран.');
|
||||
status.textContent='Создаём ключи локально (Argon2id)…';
|
||||
draft.preGeneratedKeyBundle=await authService.derivePasswordKeyBundle(draft.login,draft.password);
|
||||
}
|
||||
status.textContent='Создаём временную заявку…';
|
||||
const started=await startFreeRegistration({fullLogin:draft.login,keyBundle:draft.preGeneratedKeyBundle,email:address});
|
||||
if(disposed)return;
|
||||
|
||||
@@ -13,8 +13,10 @@ import {
|
||||
import { clearStoredMessages } from '../services/message-store.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
createSolanaWalletFromPrivateBase58,
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import {
|
||||
@@ -25,12 +27,14 @@ import {
|
||||
registerUserOnSolana,
|
||||
} from '../services/solana-register-service.js';
|
||||
import { defaultServerLogin } from '../deploy-config.js';
|
||||
import { normalizeFullLogin } from '../services/shine-namespace-service.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-payment-view', title: 'Оплата регистрации', showAppChrome: false };
|
||||
const MIN_REQUIRED_SOL = 0.01;
|
||||
const RECOMMENDED_TOPUP_SOL = 0.02;
|
||||
const TEST_TOPUP_AMOUNT_SOL = 0.02;
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||||
const AUTO_LOGIN_RETRY_MS = 2000;
|
||||
const REGISTRATION_PROGRESS_DURATION_MS = 12000;
|
||||
@@ -68,6 +72,12 @@ function parseBalanceSol(value) {
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
function registrationAccessServerLogin() {
|
||||
const configured = String(state.entrySettings.shineServerLogin || defaultServerLogin || '').trim().toLowerCase();
|
||||
if (!configured) return '';
|
||||
return normalizeFullLogin(configured.includes('@') ? configured : `${configured}@shine`);
|
||||
}
|
||||
|
||||
function getCryptoRuntimeState() {
|
||||
const hasCrypto = Boolean(globalThis.crypto);
|
||||
const hasGetRandomValues = Boolean(globalThis.crypto && typeof globalThis.crypto.getRandomValues === 'function');
|
||||
@@ -249,13 +259,35 @@ export function render({ navigate }) {
|
||||
topupButton.className = 'ghost-btn';
|
||||
topupButton.type = 'button';
|
||||
topupButton.textContent = 'Тестовое пополнение (пока доступно в тестовом режиме)';
|
||||
// Браузерная раздача devnet SOL с приватным ключом отправителя опасна.
|
||||
// Ссылка на публичный faucet безопаснее, чем встраивать секрет в JS.
|
||||
topupButton.textContent = 'Как пополнить через devnet faucet';
|
||||
topupButton.addEventListener('click', () => {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = 'Скопируйте адрес кошелька выше и пополните его через доверенный Solana devnet faucet. Приватный ключ отправителя не должен находиться в приложении.';
|
||||
status.style.display = '';
|
||||
topupButton.addEventListener('click', async () => {
|
||||
status.style.display = 'none';
|
||||
topupButton.disabled = true;
|
||||
const defaultText = 'Тестовое пополнение (пока доступно в тестовом режиме)';
|
||||
topupButton.textContent = 'Пополняем...';
|
||||
try {
|
||||
const address = await deriveUserWalletAddress();
|
||||
const sender = await createSolanaWalletFromPrivateBase58(TEST_TOPUP_SENDER_PRIVATE_32_BASE58);
|
||||
await transferSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
fromKeypair: sender.keypair,
|
||||
toAddress: address,
|
||||
amountSol: TEST_TOPUP_AMOUNT_SOL,
|
||||
});
|
||||
const balance = await getBalanceSol({
|
||||
endpoint: DEVNET_ENDPOINT,
|
||||
address,
|
||||
});
|
||||
state.registrationPayment.balanceSOL = String(balance.sol);
|
||||
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = `Тестовое пополнение выполнено: +${TEST_TOPUP_AMOUNT_SOL} SOL. Баланс: ${formatSol(balance.sol, 6)} SOL.`;
|
||||
status.style.display = '';
|
||||
} catch (error) {
|
||||
showWalletError(error, 'Не удалось выполнить тестовое пополнение. Попробуйте ещё раз.');
|
||||
} finally {
|
||||
topupButton.disabled = false;
|
||||
topupButton.textContent = defaultText;
|
||||
}
|
||||
});
|
||||
|
||||
const submitButton = document.createElement('button');
|
||||
@@ -289,7 +321,7 @@ export function render({ navigate }) {
|
||||
: `Для регистрации пополните этот кошелёк соланами примерно на ${RECOMMENDED_TOPUP_SOL} SOL. Сейчас на кошельке ${formatSol(currentBalance, 6)} SOL. Минимум для продолжения: ${requiredSol.toFixed(6)} SOL.`;
|
||||
status.style.display = '';
|
||||
if (isTestContour) {
|
||||
status.textContent += ' Для тестового пополнения используйте внешний devnet faucet.';
|
||||
status.textContent += ` Нажмите «Тестовое пополнение», чтобы сразу добавить ${TEST_TOPUP_AMOUNT_SOL} SOL без перехода на другой экран.`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -315,7 +347,7 @@ export function render({ navigate }) {
|
||||
login: state.registrationDraft.login,
|
||||
keyBundle,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
accessServers: [state.entrySettings.shineServerLogin || defaultServerLogin],
|
||||
accessServers: [registrationAccessServerLogin()],
|
||||
});
|
||||
registrationTxId = String(registrationResult?.signature || '').trim();
|
||||
} catch (solanaError) {
|
||||
|
||||
Reference in New Issue
Block a user