SHA256
Промежуточный коммит: состояние до нормальной Solana-first регистрации
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import { formatSol, getBalanceSol, transferSol, createSolanaWalletFromPrivateBase58 } from '../services/solana-wallet-service.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
export const pageMeta = { id: 'devnet-topup-view', title: 'Пополнение DEVNET', showAppChrome: false };
|
||||
|
||||
const SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const TRANSFER_AMOUNT_SOL = 0.01;
|
||||
|
||||
function readWalletFromUrl() {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
return String(url.searchParams.get('wallet') || '').trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
|
||||
const targetWallet = readWalletFromUrl();
|
||||
|
||||
const senderBox = document.createElement('div');
|
||||
senderBox.className = 'card stack';
|
||||
senderBox.innerHTML = `
|
||||
<strong>Тестовый DEVNET-кошелёк</strong>
|
||||
<p class="meta-muted" id="devnet-topup-sender-address">Адрес: ...</p>
|
||||
<p class="meta-muted" id="devnet-topup-sender-balance">Баланс: ...</p>
|
||||
`;
|
||||
|
||||
const targetBox = document.createElement('div');
|
||||
targetBox.className = 'card stack';
|
||||
targetBox.innerHTML = `
|
||||
<strong>Кошелёк получателя</strong>
|
||||
<p class="meta-muted" style="word-break:break-all;">${targetWallet || 'Не передан параметр wallet'}</p>
|
||||
<p class="meta-muted">Сумма перевода: ${TRANSFER_AMOUNT_SOL} SOL</p>
|
||||
`;
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = 'Готово к пополнению.';
|
||||
|
||||
const fillBtn = document.createElement('button');
|
||||
fillBtn.className = 'primary-btn';
|
||||
fillBtn.type = 'button';
|
||||
fillBtn.textContent = `Пополнить на ${TRANSFER_AMOUNT_SOL} SOL`;
|
||||
|
||||
const backBtn = document.createElement('button');
|
||||
backBtn.className = 'secondary-btn';
|
||||
backBtn.type = 'button';
|
||||
backBtn.textContent = 'Назад';
|
||||
backBtn.addEventListener('click', () => navigate('registration-payment-view'));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.append(fillBtn, backBtn);
|
||||
|
||||
let senderAddress = '';
|
||||
let senderKeypair = null;
|
||||
|
||||
const updateSenderBalance = async () => {
|
||||
if (!senderAddress) return;
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
const balance = await getBalanceSol({ endpoint, address: senderAddress });
|
||||
const senderBalanceEl = senderBox.querySelector('#devnet-topup-sender-balance');
|
||||
if (senderBalanceEl) senderBalanceEl.textContent = `Баланс: ${formatSol(balance.sol, 6)} SOL`;
|
||||
};
|
||||
|
||||
fillBtn.addEventListener('click', async () => {
|
||||
if (!targetWallet) {
|
||||
status.textContent = 'Ошибка: в URL не передан параметр wallet.';
|
||||
return;
|
||||
}
|
||||
if (!senderKeypair) {
|
||||
status.textContent = 'Ошибка: кошелёк отправителя не инициализирован.';
|
||||
return;
|
||||
}
|
||||
|
||||
fillBtn.disabled = true;
|
||||
status.textContent = 'Отправляем перевод...';
|
||||
|
||||
try {
|
||||
const endpoint = state.entrySettings.solanaServer;
|
||||
const tx = await transferSol({
|
||||
endpoint,
|
||||
fromKeypair: senderKeypair,
|
||||
toAddress: targetWallet,
|
||||
amountSol: TRANSFER_AMOUNT_SOL,
|
||||
});
|
||||
await updateSenderBalance();
|
||||
status.textContent = `Готово. Signature: ${tx.signature}`;
|
||||
} catch (error) {
|
||||
status.textContent = `Ошибка перевода: ${error?.message || 'unknown'}`;
|
||||
} finally {
|
||||
fillBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const sender = await createSolanaWalletFromPrivateBase58(SENDER_PRIVATE_32_BASE58);
|
||||
senderAddress = sender.address;
|
||||
senderKeypair = sender.keypair;
|
||||
const senderAddressEl = senderBox.querySelector('#devnet-topup-sender-address');
|
||||
if (senderAddressEl) senderAddressEl.textContent = `Адрес: ${senderAddress}`;
|
||||
await updateSenderBalance();
|
||||
if (!targetWallet) {
|
||||
fillBtn.disabled = true;
|
||||
status.textContent = 'Передайте адрес получателя в параметре wallet.';
|
||||
}
|
||||
} catch (error) {
|
||||
fillBtn.disabled = true;
|
||||
status.textContent = `Ошибка инициализации отправителя: ${error?.message || 'unknown'}`;
|
||||
}
|
||||
})();
|
||||
|
||||
screen.append(
|
||||
renderHeader({
|
||||
title: 'DEVNET пополнение',
|
||||
leftAction: { label: '←', onClick: () => navigate('registration-payment-view') },
|
||||
}),
|
||||
senderBox,
|
||||
targetBox,
|
||||
status,
|
||||
actions,
|
||||
);
|
||||
|
||||
return screen;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { renderHeader } from '../components/header.js';
|
||||
import { authService, clearAuthMessages, state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { precheckLoginClassOnSolana } from '../services/solana-register-service.js';
|
||||
|
||||
export const pageMeta = { id: 'register-view', title: 'Зарегистрироваться', showAppChrome: false };
|
||||
|
||||
@@ -41,7 +42,7 @@ export function render({ navigate }) {
|
||||
<p class="meta-muted">В derivation участвуют и логин, и пароль: одинаковый пароль у разных логинов даёт разные ключи.</p>
|
||||
<p class="meta-muted">Если пароль пустой — используется прежний тестовый режим совместимости (старый детерминированный вариант).</p>
|
||||
<p class="meta-muted">Для тесто оставьте пустой пароль.</p>
|
||||
<p class="meta-muted">Профиль Argon2id сейчас фиксированный: t=3, m=262144 KiB (256 MB), p=1, dkLen=32. Выбор уровня будет добавлен позже.</p>
|
||||
<p class="meta-muted">Профиль Argon2id сейчас фиксированный: t=2, m=65536 KiB (64 MB), p=1, dkLen=32. Выбор уровня будет добавлен позже.</p>
|
||||
`;
|
||||
|
||||
const checkButton = document.createElement('button');
|
||||
@@ -49,6 +50,11 @@ export function render({ navigate }) {
|
||||
checkButton.type = 'button';
|
||||
checkButton.textContent = 'Проверить логин';
|
||||
|
||||
let lastCheckedLogin = '';
|
||||
let lastCheckedFree = false;
|
||||
let lastCheckedClassName = '';
|
||||
let generationRunId = 0;
|
||||
|
||||
async function runAvailabilityCheck() {
|
||||
const login = loginInput.value.trim();
|
||||
if (!login) {
|
||||
@@ -57,15 +63,61 @@ export function render({ navigate }) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (login === lastCheckedLogin) {
|
||||
if (!lastCheckedFree) {
|
||||
statusText.textContent = 'Логин уже занят ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
} else if (lastCheckedClassName === 'free') {
|
||||
statusText.textContent = 'Логин свободен ✅';
|
||||
statusText.className = 'is-available';
|
||||
} else if (lastCheckedClassName === 'premium') {
|
||||
statusText.textContent = 'Логин свободен, но это премиум-логин (покупка через DAO) ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
} else if (lastCheckedClassName === 'company') {
|
||||
statusText.textContent = 'Логин свободен, но относится к компании/бренду (отдельное согласование) ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
} else {
|
||||
statusText.textContent = 'Логин нельзя использовать для обычной регистрации ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
}
|
||||
formError.style.display = 'none';
|
||||
return lastCheckedFree && lastCheckedClassName === 'free';
|
||||
}
|
||||
|
||||
checkButton.disabled = true;
|
||||
checkButton.textContent = 'Проверка...';
|
||||
try {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const isFree = await authService.ensureLoginFree(login);
|
||||
statusText.textContent = isFree ? 'Логин свободен ✅' : 'Логин уже занят ❌';
|
||||
statusText.className = isFree ? 'is-available' : 'is-unavailable';
|
||||
let className = '';
|
||||
if (isFree) {
|
||||
const precheck = await precheckLoginClassOnSolana({
|
||||
login,
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
});
|
||||
className = precheck.className;
|
||||
}
|
||||
lastCheckedLogin = login;
|
||||
lastCheckedFree = isFree;
|
||||
lastCheckedClassName = className;
|
||||
if (!isFree) {
|
||||
statusText.textContent = 'Логин уже занят ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
} else if (className === 'free') {
|
||||
statusText.textContent = 'Логин свободен ✅';
|
||||
statusText.className = 'is-available';
|
||||
} else if (className === 'premium') {
|
||||
statusText.textContent = 'Логин свободен, но это премиум-логин (покупка через DAO) ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
} else if (className === 'company') {
|
||||
statusText.textContent = 'Логин свободен, но относится к компании/бренду (отдельное согласование) ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
} else {
|
||||
statusText.textContent = 'Логин нельзя использовать для обычной регистрации ❌';
|
||||
statusText.className = 'is-unavailable';
|
||||
}
|
||||
formError.style.display = 'none';
|
||||
return isFree;
|
||||
return isFree && className === 'free';
|
||||
} catch (error) {
|
||||
statusText.textContent = toUserMessage(error, 'Не удалось проверить логин');
|
||||
statusText.className = 'is-unavailable';
|
||||
@@ -78,14 +130,6 @@ export function render({ navigate }) {
|
||||
|
||||
checkButton.addEventListener('click', runAvailabilityCheck);
|
||||
|
||||
form.innerHTML = `
|
||||
<label class="stack"><span class="field-label">Логин</span></label>
|
||||
<label class="stack"><span class="field-label">Пароль</span></label>
|
||||
`;
|
||||
form.children[0].append(loginInput);
|
||||
form.children[1].append(passwordInput);
|
||||
form.append(checkButton, statusText, advanced, formError);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'auth-footer-actions';
|
||||
|
||||
@@ -104,47 +148,170 @@ export function render({ navigate }) {
|
||||
const isFree = await runAvailabilityCheck();
|
||||
if (!isFree) return;
|
||||
|
||||
state.registrationDraft.login = loginInput.value.trim();
|
||||
state.registrationDraft.password = passwordInput.value;
|
||||
state.registrationDraft.preGeneratedKeyBundle = null;
|
||||
const prevLogin = String(state.registrationDraft.login || '');
|
||||
const prevPassword = String(state.registrationDraft.password || '');
|
||||
const nextLogin = String(loginInput.value.trim());
|
||||
const nextPassword = String(passwordInput.value || '');
|
||||
const credsChanged = prevLogin !== nextLogin || prevPassword !== nextPassword;
|
||||
|
||||
// Показываем информационный экран пока генерируются ключи
|
||||
state.registrationDraft.login = nextLogin;
|
||||
state.registrationDraft.password = nextPassword;
|
||||
if (credsChanged) {
|
||||
state.registrationDraft.preGeneratedKeyBundle = null;
|
||||
}
|
||||
|
||||
renderSecurityConfirmStage();
|
||||
});
|
||||
|
||||
actions.append(backButton, nextButton);
|
||||
|
||||
function renderInputStage() {
|
||||
form.innerHTML = `
|
||||
<label class="stack"><span class="field-label">Логин</span></label>
|
||||
<label class="stack"><span class="field-label">Пароль</span></label>
|
||||
`;
|
||||
form.children[0].append(loginInput);
|
||||
form.children[1].append(passwordInput);
|
||||
form.append(checkButton, statusText, advanced, formError);
|
||||
actions.innerHTML = '';
|
||||
actions.append(backButton, nextButton);
|
||||
backButton.disabled = false;
|
||||
nextButton.disabled = false;
|
||||
}
|
||||
|
||||
function renderSecurityConfirmStage() {
|
||||
form.innerHTML = '';
|
||||
const infoMsg = document.createElement('p');
|
||||
infoMsg.className = 'auth-copy';
|
||||
infoMsg.textContent =
|
||||
'Из вашего логина и пароля (надеемся, что вы выбрали достаточно длинный и надёжный пароль) ' +
|
||||
'генерируется секрет, из которого получаются root key, blockchain key и device key.';
|
||||
|
||||
const spinnerMsg = document.createElement('p');
|
||||
spinnerMsg.className = 'meta-muted';
|
||||
spinnerMsg.textContent = 'Генерация ключей...';
|
||||
const info = document.createElement('p');
|
||||
info.className = 'auth-copy';
|
||||
info.textContent =
|
||||
'Для повышения безопасности мы генерируем секрет из вашего пароля с помощью Argon2id.';
|
||||
|
||||
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 =
|
||||
'Из этого секрета строятся root key, blockchain key и device key. Это может занять некоторое время.';
|
||||
|
||||
const details3 = document.createElement('p');
|
||||
details3.className = 'meta-muted';
|
||||
details3.textContent = 'Это необходимо, чтобы усложнить подбор пароля и секрета.';
|
||||
|
||||
form.append(info, details, details2, details3);
|
||||
|
||||
const back2 = document.createElement('button');
|
||||
back2.className = 'ghost-btn';
|
||||
back2.type = 'button';
|
||||
back2.textContent = 'Назад';
|
||||
back2.addEventListener('click', renderInputStage);
|
||||
|
||||
const ok = document.createElement('button');
|
||||
ok.className = 'primary-btn';
|
||||
ok.type = 'button';
|
||||
ok.textContent = 'Окей';
|
||||
ok.addEventListener('click', startGenerationStage);
|
||||
|
||||
actions.innerHTML = '';
|
||||
actions.append(back2, ok);
|
||||
}
|
||||
|
||||
async function startGenerationStage() {
|
||||
const runId = ++generationRunId;
|
||||
form.innerHTML = '';
|
||||
|
||||
const title = document.createElement('p');
|
||||
title.className = 'auth-copy';
|
||||
title.textContent = 'Генерация ключей...';
|
||||
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'meta-muted';
|
||||
subtitle.textContent = 'Генерируется секрет из вашего пароля, из которого будут вычислены все ключи.';
|
||||
|
||||
const progressWrap = document.createElement('div');
|
||||
progressWrap.style.width = '100%';
|
||||
progressWrap.style.height = '10px';
|
||||
progressWrap.style.border = '1px solid rgba(180,180,180,.5)';
|
||||
progressWrap.style.borderRadius = '6px';
|
||||
progressWrap.style.overflow = 'hidden';
|
||||
|
||||
const progressBar = document.createElement('div');
|
||||
progressBar.style.height = '100%';
|
||||
progressBar.style.width = '0%';
|
||||
progressBar.style.background = 'rgba(80, 160, 255, 0.9)';
|
||||
progressBar.style.transition = 'width 180ms linear';
|
||||
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(infoMsg, spinnerMsg, genError);
|
||||
nextButton.disabled = true;
|
||||
backButton.disabled = true;
|
||||
form.append(title, subtitle, progressWrap, progressText, genError);
|
||||
|
||||
const cancelBtn = document.createElement('button');
|
||||
cancelBtn.className = 'ghost-btn';
|
||||
cancelBtn.type = 'button';
|
||||
cancelBtn.textContent = 'Отмена';
|
||||
cancelBtn.addEventListener('click', () => {
|
||||
generationRunId += 1;
|
||||
renderSecurityConfirmStage();
|
||||
});
|
||||
actions.innerHTML = '';
|
||||
actions.append(cancelBtn);
|
||||
|
||||
try {
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(
|
||||
state.registrationDraft.login,
|
||||
state.registrationDraft.password,
|
||||
);
|
||||
state.registrationDraft.preGeneratedKeyBundle = keyBundle;
|
||||
navigate('registration-payment-view');
|
||||
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') {
|
||||
renderSecurityConfirmStage();
|
||||
return;
|
||||
}
|
||||
genError.textContent = `Ошибка генерации ключей: ${error?.message || 'неизвестная ошибка'}`;
|
||||
genError.style.display = '';
|
||||
spinnerMsg.style.display = 'none';
|
||||
nextButton.disabled = false;
|
||||
backButton.disabled = false;
|
||||
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', renderSecurityConfirmStage);
|
||||
actions.innerHTML = '';
|
||||
actions.append(goBack, retry);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
actions.append(backButton, nextButton);
|
||||
renderInputStage();
|
||||
|
||||
screen.append(
|
||||
renderHeader({
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
deriveWalletFromPassword,
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getTopupSiteUrl,
|
||||
@@ -107,10 +106,14 @@ export function render({ navigate }) {
|
||||
};
|
||||
|
||||
const deriveUserWalletAddress = async () => {
|
||||
const draftPassword = String(state.registrationDraft.password ?? '');
|
||||
const wallet = await deriveWalletFromPassword(draftPassword);
|
||||
const address = String(wallet?.address || '').trim();
|
||||
if (!address) throw new Error('Не удалось вычислить адрес wallet.key');
|
||||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
if (!keyBundle) throw new Error('Ключи ещё не сгенерированы. Вернитесь на предыдущий шаг.');
|
||||
const { publicKeyB64 } = keyBundle.devicePair;
|
||||
const raw = atob(publicKeyB64);
|
||||
const bytes = new Uint8Array(raw.length);
|
||||
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
||||
const { PublicKey } = await import('https://esm.sh/@solana/web3.js@1.98.4');
|
||||
const address = new PublicKey(bytes).toBase58();
|
||||
state.registrationPayment.walletAddress = address;
|
||||
walletValue.value = address;
|
||||
return address;
|
||||
@@ -176,14 +179,8 @@ export function render({ navigate }) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Используем предсгенерированный keyBundle или генерируем заново
|
||||
let keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
if (!keyBundle) {
|
||||
keyBundle = await authService.derivePasswordKeyBundle(
|
||||
state.registrationDraft.login,
|
||||
state.registrationDraft.password,
|
||||
);
|
||||
}
|
||||
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
|
||||
if (!keyBundle) throw new Error('Ключи не найдены. Вернитесь на предыдущий шаг.');
|
||||
|
||||
// Регистрация на Solana (смарт контракт)
|
||||
submitButton.textContent = 'Регистрация в Solana...';
|
||||
@@ -204,7 +201,7 @@ export function render({ navigate }) {
|
||||
// Регистрация на сервере SHiNE
|
||||
submitButton.textContent = 'Регистрация на сервере...';
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const result = await authService.registerUser(state.registrationDraft.login, state.registrationDraft.password);
|
||||
const result = await authService.registerUserWithKeyBundle(state.registrationDraft.login, keyBundle);
|
||||
state.registrationDraft.flowType = 'registration';
|
||||
state.registrationDraft.sessionId = result.sessionId;
|
||||
state.registrationDraft.storagePwd = result.storagePwd;
|
||||
|
||||
Reference in New Issue
Block a user