SHA256
Улучшить ввод пароля при входе и регистрации
This commit is contained in:
+1
-1
@@ -1,2 +1,2 @@
|
||||
client.version=1.20.65
|
||||
client.version=1.20.66
|
||||
server.version=1.16.32
|
||||
|
||||
@@ -103,3 +103,10 @@ await confirmDialog({
|
||||
Английские формулировки являются первым черновым переводом и требуют редакторской вычитки. Часть русских строк в служебном коде и отдельных нестандартных сценариях остаётся вне словарей; данные пользователей и протокольные значения переводить нельзя. При отсутствии ключа сохраняется русский fallback.
|
||||
|
||||
Проверка `node --test shine-UI/tests/i18n-completeness.test.mjs` требует одинаковых ключей и параметров в двух словарях и проверяет статические обращения `t()`/`th()` в JavaScript. После правок запускать также весь набор `node --test shine-UI/tests/*.test.mjs`, проверку синтаксиса JS и `python3 scripts/check_docs.py`.
|
||||
|
||||
## Пароль и генерация ключей в регистрации и входе (21.11.2026)
|
||||
|
||||
- На экране регистрации показывается разъяснение, что логин и пароль используются для локальной генерации криптографических ключей, а сервер не хранит пароль или приватные ключи. Пользователю рекомендуются 12–16+ символов или длинная парольная фраза. В тестовом периоде обязательный минимум **1 символ**, максимум **256**. Счётчик символов (`N / 256`) находится **только на регистрации**.
|
||||
- Для ввода пароля и при регистрации, и при входе используется расширяющееся поле до **трёх строк** (дальше прокрутка), по умолчанию видимое. В каждой строке на достаточно широком экране помещается **32 моноширинных символа**, на узких экранах длина строки адаптивна (приоритет — читаемость и отсутствие горизонтального выхода за экран). Автоматический перенос визуальный и не вставляет `\n` в пароль. Кнопка-глаз скрывает содержимое даже в многострочном поле; обычный Enter отправляет форму, Shift+Enter вставляет перенос строки. Перенос строки, введённый вручную, является частью пароля и влияет на ключи. После успешной генерации ключей при регистрации и после успешной авторизации при входе видимое поле сразу очищается, включая маску (секрет для следующих шагов регистрации остаётся в оперативном состоянии до окончания процесса). При возврате на шаг пароля ранее введённое значение не подставляется обратно.
|
||||
- Пока вычисляются ключи, оба экрана используют один экран ожидания с анимацией и подписями «Генерируем ваши цифровые ключи…» / «Генерируем их из вашего логина и пароля непосредственно на этом устройстве.». Проценты и индикатор хода работы **не показываются**; алгоритмы получения ключей и запросы API не изменены.
|
||||
- Подписи находятся в словарях `ru.json` и `en.json` (`components.secret_generation_overlay.*`, `screens.register_view.*`).
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/** Общий экран ожидания локальной генерации ключей. Без ложного процента выполнения. */
|
||||
export function createSecretGenerationOverlay() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'secret-generation-overlay';
|
||||
overlay.hidden = true;
|
||||
overlay.setAttribute('role', 'status');
|
||||
overlay.setAttribute('aria-live', 'polite');
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'secret-generation-card stack';
|
||||
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'secret-generation-spinner';
|
||||
spinner.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'secret-generation-title';
|
||||
title.textContent = t('components.secret_generation_overlay.title');
|
||||
|
||||
const description = document.createElement('p');
|
||||
description.className = 'secret-generation-description';
|
||||
description.textContent = t('components.secret_generation_overlay.description');
|
||||
|
||||
card.append(spinner, title, description);
|
||||
overlay.append(card);
|
||||
return {
|
||||
overlay,
|
||||
show() { overlay.hidden = false; },
|
||||
hide() { overlay.hidden = true; },
|
||||
};
|
||||
}
|
||||
@@ -1,30 +1,101 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/** The password is intentionally visible initially on both auth screens. */
|
||||
/**
|
||||
* Native password inputs are single-line only. A textarea allows long phrases to
|
||||
* wrap across up to three lines. Masking uses a non-interactive bullet mirror so
|
||||
* it also works in browsers without CSS text-security support.
|
||||
*/
|
||||
export function createExpandablePasswordTextarea() {
|
||||
const input = document.createElement('textarea');
|
||||
input.className = 'input auth-password-field__textarea';
|
||||
input.rows = 1;
|
||||
// 32 visible monospace characters per line on screens wide enough.
|
||||
// Soft wrap only: never add newline characters to the actual password.
|
||||
input.cols = 32;
|
||||
input.wrap = 'soft';
|
||||
input.autocapitalize = 'off';
|
||||
input.spellcheck = false;
|
||||
input.setAttribute('autocorrect', 'off');
|
||||
|
||||
const resize = () => {
|
||||
const computed = window.getComputedStyle(input);
|
||||
const lineHeight = Number.parseFloat(computed.lineHeight) || 24;
|
||||
const extras = (Number.parseFloat(computed.paddingTop) || 0)
|
||||
+ (Number.parseFloat(computed.paddingBottom) || 0)
|
||||
+ (Number.parseFloat(computed.borderTopWidth) || 0)
|
||||
+ (Number.parseFloat(computed.borderBottomWidth) || 0);
|
||||
input.style.height = `${lineHeight + extras}px`;
|
||||
input.style.height = `${Math.min(input.scrollHeight, 3 * lineHeight + extras)}px`;
|
||||
};
|
||||
input.addEventListener('input', resize);
|
||||
// Initial value may be restored from a registration draft before mounting.
|
||||
input.resizePasswordField = resize;
|
||||
input.clearPasswordField = () => {
|
||||
input.value = '';
|
||||
input.updatePasswordMask?.();
|
||||
resize();
|
||||
};
|
||||
return input;
|
||||
}
|
||||
|
||||
/** Passwords are deliberately visible initially on registration and sign-in. */
|
||||
export function createVisiblePasswordField(input) {
|
||||
input.type = 'text';
|
||||
const multiline = input.tagName === 'TEXTAREA';
|
||||
if (!multiline) input.type = 'text';
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'auth-password-field';
|
||||
wrap.className = multiline ? 'auth-password-field auth-password-field--multiline' : 'auth-password-field';
|
||||
|
||||
let mask = null;
|
||||
let visible = true;
|
||||
if (multiline) {
|
||||
mask = document.createElement('div');
|
||||
mask.className = 'auth-password-field__mask';
|
||||
mask.setAttribute('aria-hidden', 'true');
|
||||
mask.hidden = true;
|
||||
const updateMask = () => {
|
||||
// Preserve explicit line breaks while not copying actual password text.
|
||||
mask.textContent = Array.from(input.value, char => char === '\n' ? '\n' : '•').join('');
|
||||
mask.scrollTop = input.scrollTop;
|
||||
mask.scrollLeft = input.scrollLeft;
|
||||
};
|
||||
input.addEventListener('input', updateMask);
|
||||
input.addEventListener('scroll', () => {
|
||||
mask.scrollTop = input.scrollTop;
|
||||
mask.scrollLeft = input.scrollLeft;
|
||||
});
|
||||
input.updatePasswordMask = updateMask;
|
||||
}
|
||||
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'auth-password-field__toggle';
|
||||
function updateToggle() {
|
||||
const visible = input.type !== 'password';
|
||||
toggle.innerHTML = iconHtml(visible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
|
||||
toggle.setAttribute('aria-label', visible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
|
||||
toggle.setAttribute('title', visible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
|
||||
toggle.setAttribute('aria-pressed', String(!visible));
|
||||
const isVisible = multiline ? visible : input.type !== 'password';
|
||||
toggle.innerHTML = iconHtml(isVisible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
|
||||
toggle.setAttribute('aria-label', isVisible ? t('screens.visible_password_field.text_001') : t('screens.visible_password_field.text_002'));
|
||||
toggle.setAttribute('title', isVisible ? t('screens.visible_password_field.text_003') : t('screens.visible_password_field.text_004'));
|
||||
toggle.setAttribute('aria-pressed', String(!isVisible));
|
||||
}
|
||||
toggle.addEventListener('click', () => {
|
||||
const start = input.selectionStart;
|
||||
const end = input.selectionEnd;
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
if (multiline) {
|
||||
visible = !visible;
|
||||
wrap.classList.toggle('auth-password-field--masked', !visible);
|
||||
mask.hidden = visible;
|
||||
input.updatePasswordMask();
|
||||
input.resizePasswordField();
|
||||
} else {
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
}
|
||||
updateToggle();
|
||||
input.focus();
|
||||
try { if (start !== null && end !== null) input.setSelectionRange(start, end); } catch { /* unsupported input method */ }
|
||||
});
|
||||
updateToggle();
|
||||
wrap.append(input, toggle);
|
||||
wrap.append(input);
|
||||
if (mask) wrap.append(mask);
|
||||
wrap.append(toggle);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
"test_mint_missing": "Token is not configured on Devnet",
|
||||
"devnet_disclaimer": "Official USDT does not exist on Devnet. Testing requires a separate 6-decimal SPL token.",
|
||||
"jupiter_external": "Swap on Jupiter ↗",
|
||||
"jupiter_warning": "Jupiter opens externally. Your built-in SHiNE wallet is not automatically connected; swapping requires an external compatible wallet. Real USDT swaps are unavailable on Devnet."
|
||||
"jupiter_warning": "Jupiter opens externally. Your built-in SHiNE wallet is not automatically connected; swapping requires an external compatible wallet. Real USDT swaps are unavailable on Devnet.",
|
||||
"uncertain": "Transfer status is uncertain; it may have succeeded. Check Solana history before sending again.",
|
||||
"receive_hint": "This address receives SOL and USDT on Solana. Do not send tokens from other blockchains."
|
||||
},
|
||||
"chat_links": {
|
||||
"title": "External link",
|
||||
@@ -1009,6 +1011,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"secret_generation_overlay": {"title": "Generating your digital keys…", "description": "Generating them from your login and password directly on this device."}
|
||||
},
|
||||
"screens": {
|
||||
"dm_attachments": {
|
||||
"text_001": "Download",
|
||||
@@ -1541,7 +1546,7 @@
|
||||
"text_018": "There's no namespace available yet.",
|
||||
"text_019": "In a free account, password change is not available. After switching to a full account, it will be possible to change it.",
|
||||
"text_016": "Create a password",
|
||||
"text_017": "On your device, cryptographic access keys are created from the username and password. Private keys are not stored on the server.",
|
||||
"text_017": "Your password is the foundation of your digital keys.",
|
||||
"text_022": "Your username changed. Press “Continue” again.",
|
||||
"text_023": "That login's already taken. Try another one.",
|
||||
"text_015": "This name will remain forever and will be displayed exactly as you choose now. You can't change it later.",
|
||||
@@ -1556,11 +1561,12 @@
|
||||
"text_030": "Minimum login length: {value1} characters.",
|
||||
"text_031": "Password (from 1 to {value1} characters)",
|
||||
"text_032": "Enter a password between 1 and {value1} characters.",
|
||||
"text_034": "The best password is the one you remember.",
|
||||
"text_037": "Don't lose your password!",
|
||||
"text_038": "We cannot recover it or your keys. If access to keys on all devices is lost, encrypted personal correspondence may not be available.",
|
||||
"text_035": "Any non-empty password will do. For reliability, it is better to choose your long phrase or random code. Do not use known quotes or obvious sequences.",
|
||||
"text_036": "On a familiar device, you usually do not have to enter a password every time you sign in: work keys are stored locally. To sign in from a new device, the password is your backup access method.",
|
||||
"text_034": "🔐 Your password is your digital key",
|
||||
"text_037": "🔒 Your keys belong to you alone.",
|
||||
"text_038": "Our server does not store your password or private keys and cannot recover them. If you lose your password, access to your keys and encrypted conversations will be lost forever. Keep your password somewhere safe!",
|
||||
"text_035": "Private cryptographic keys are generated from your username and password directly on your device. They are stored only on your devices and provide access to your account, private messages, and digital wallets.",
|
||||
"text_036": "Choose a strong password: we recommend 12–16 characters or more. You can use a long, memorable phrase combining words, numbers, and special characters.",
|
||||
"password_counter": "Characters: {value1} / {value2}",
|
||||
"text_039": "Warning: The wallet is already full. Changing your login or password will create a different wallet! The funds will remain at the old address, and the old password will be required to access them. Continue?"
|
||||
},
|
||||
"network_view": {
|
||||
@@ -4698,6 +4704,9 @@
|
||||
},
|
||||
"app": {
|
||||
"error_sent_to_server_login_time": "Error sent to server · {login} · {time}",
|
||||
"error_report_pending": "Sending error report…",
|
||||
"error_report_received": "Error report received · {id}",
|
||||
"error_report_not_sent": "Could not send error report",
|
||||
"message_from_login": "Message from {login}",
|
||||
"connecting": "Connecting…",
|
||||
"connecting_tap_to_retry_now": "Connecting… Tap to retry now",
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
"test_mint_missing": "Токен не настроен в Devnet",
|
||||
"devnet_disclaimer": "На Devnet настоящий USDT отсутствует. Для тестирования нужен отдельный SPL-токен с 6 знаками.",
|
||||
"jupiter_external": "Обменять на Jupiter ↗",
|
||||
"jupiter_warning": "Jupiter откроется на внешнем сайте. Встроенный кошелёк SHiNE там не подключается автоматически: для обмена потребуется совместимый внешний кошелёк. На Devnet реального обмена USDT нет."
|
||||
"jupiter_warning": "Jupiter откроется на внешнем сайте. Встроенный кошелёк SHiNE там не подключается автоматически: для обмена потребуется совместимый внешний кошелёк. На Devnet реального обмена USDT нет.",
|
||||
"uncertain": "Не удалось однозначно подтвердить перевод. Он мог пройти! Проверьте историю Solana перед повторной отправкой.",
|
||||
"receive_hint": "Этот адрес используется для SOL и USDT в сети Solana. Не отправляйте сюда токены из других блокчейнов."
|
||||
},
|
||||
"chat_links": {
|
||||
"title": "Внешняя ссылка",
|
||||
@@ -1009,6 +1011,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"secret_generation_overlay": {"title": "Генерируем ваши цифровые ключи…", "description": "Генерируем их из вашего логина и пароля непосредственно на этом устройстве."}
|
||||
},
|
||||
"screens": {
|
||||
"dm_attachments": {
|
||||
"text_001": "Скачать",
|
||||
@@ -1539,7 +1544,7 @@
|
||||
"text_014": "Введите логин",
|
||||
"text_015": "Это имя навсегда сохранится и будет отображаться именно так, как вы выберете сейчас. Позже изменить его нельзя.",
|
||||
"text_016": "Придумайте пароль",
|
||||
"text_017": "На вашем устройстве из логина и пароля создаются криптографические ключи доступа. Приватные ключи не хранятся на сервере.",
|
||||
"text_017": "Ваш пароль — основа ваших цифровых ключей.",
|
||||
"text_018": "Пока нет доступного пространства имён",
|
||||
"text_019": "В бесплатном аккаунте смена пароля недоступна. После перехода на полноценный аккаунт появится возможность его менять.",
|
||||
"text_020": "Для полноценного аккаунта поддерживается смена пароля: необходимые зашифрованные сообщения перешифровываются на вашем устройстве, а не на сервере.",
|
||||
@@ -1556,11 +1561,12 @@
|
||||
"text_031": "Пароль (от 1 до {value1} символов)",
|
||||
"text_032": "Введите пароль длиной от 1 до {value1} символов.",
|
||||
"text_033": "Не удалось загрузить пространства имён: {value1}",
|
||||
"text_034": "Лучший пароль — тот, который вы точно помните.",
|
||||
"text_035": "Подойдёт любой непустой пароль. Для надёжности лучше выбрать свою длинную фразу или случайный код. Не используйте известные цитаты и очевидные последовательности.",
|
||||
"text_036": "На привычном устройстве обычно не придётся вводить пароль при каждом входе: рабочие ключи сохраняются локально. Для входа с нового устройства пароль — ваш резервный способ доступа.",
|
||||
"text_037": "Не теряйте пароль!",
|
||||
"text_038": "Мы не можем восстановить его или ваши ключи. Если доступ к ключам на всех устройствах утрачен, зашифрованная личная переписка может оказаться недоступна.",
|
||||
"text_034": "🔐 Ваш пароль — ваш цифровой ключ",
|
||||
"text_035": "Из вашего логина и пароля прямо на устройстве генерируются приватные криптографические ключи. Они хранятся только на ваших устройствах и обеспечивают доступ к аккаунту, личной переписке и цифровым кошелькам.",
|
||||
"text_036": "Придумайте надёжный пароль: рекомендуем 12–16 символов или больше. Можно использовать длинную запоминающуюся фразу со словами, цифрами и специальными символами.",
|
||||
"text_037": "🔒 Ваши ключи принадлежат только вам.",
|
||||
"text_038": "Наш сервер не хранит ваш пароль и приватные ключи и не может восстановить их. Если вы потеряете пароль, доступ к вашим ключам и зашифрованной переписке будет утрачен навсегда. Сохраните пароль в надёжном месте!",
|
||||
"password_counter": "Символов: {value1} / {value2}",
|
||||
"text_039": "Внимание: кошелёк уже пополнен. Изменение логина или пароля создаст другой кошелёк! Средства останутся на старом адресе, и для доступа к ним потребуется прежний пароль. Продолжить?"
|
||||
},
|
||||
"network_view": {
|
||||
@@ -2393,15 +2399,15 @@
|
||||
},
|
||||
"chat_view": {
|
||||
"security_notice": {
|
||||
"title": "Безопасность личной переписки",
|
||||
"encryption": "Сообщения в этом чате шифруются на устройствах участников.",
|
||||
"servers": "Сервер доставляет зашифрованные данные, но не должен видеть содержимое переписки.",
|
||||
"derivation": "Ключи переписки производятся из ключей аккаунта и хранятся на устройствах.",
|
||||
"rotation": "При смене ключей часть сообщений может потребовать повторного получения ключей.",
|
||||
"source": "Перед отправкой проверьте, что вы общаетесь с нужным пользователем и сервером.",
|
||||
"title": "Ваша переписка защищена сквозным шифрованием",
|
||||
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
|
||||
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
|
||||
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
|
||||
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
|
||||
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
|
||||
"warning_label": "Важно:",
|
||||
"warning": "не передавайте приватные ключи и пароль аккаунта другим людям.",
|
||||
"recovery": "Восстановление доступа зависит от сохранённых ключей и пароля. Храните их безопасно."
|
||||
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
|
||||
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
|
||||
},
|
||||
"text_001": "Чат",
|
||||
"text_002": "Без звука",
|
||||
@@ -4698,6 +4704,9 @@
|
||||
},
|
||||
"app": {
|
||||
"error_sent_to_server_login_time": "Ошибка отправлена на сервер · {login} · {time}",
|
||||
"error_report_pending": "Отправляем отчёт об ошибке…",
|
||||
"error_report_received": "Отчёт об ошибке получен · {id}",
|
||||
"error_report_not_sent": "Не удалось отправить отчёт об ошибке",
|
||||
"message_from_login": "Сообщение от {login}",
|
||||
"connecting": "Соединяюсь…",
|
||||
"connecting_tap_to_retry_now": "Соединяюсь… Нажмите, чтобы попробовать сразу",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createVisiblePasswordField } from '../components/visible-password-field.js';
|
||||
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
|
||||
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
@@ -24,31 +25,6 @@ function setStatus(statusEl, message) {
|
||||
statusEl.style.display = message ? '' : 'none';
|
||||
}
|
||||
|
||||
function createSecretOverlay() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'secret-generation-overlay';
|
||||
overlay.style.display = 'none';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'secret-generation-card stack';
|
||||
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'secret-generation-spinner';
|
||||
spinner.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'secret-generation-title';
|
||||
title.textContent = t('screens.login_password_view.text_002');
|
||||
|
||||
const progress = document.createElement('div');
|
||||
progress.className = 'secret-generation-progress';
|
||||
progress.textContent = '';
|
||||
|
||||
card.append(spinner, title, progress);
|
||||
overlay.append(card);
|
||||
return { overlay, progress };
|
||||
}
|
||||
|
||||
export function render({ navigate }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack auth-screen auth-screen--lower';
|
||||
@@ -70,9 +46,7 @@ export function render({ navigate }) {
|
||||
const passwordField = document.createElement('label');
|
||||
passwordField.className = 'stack';
|
||||
|
||||
const passwordInput = document.createElement('input');
|
||||
passwordInput.className = 'input';
|
||||
passwordInput.type = 'text';
|
||||
const passwordInput = createExpandablePasswordTextarea();
|
||||
passwordInput.name = 'shine-login-password';
|
||||
passwordInput.autocomplete = 'current-password';
|
||||
passwordInput.autocapitalize = 'off';
|
||||
@@ -96,7 +70,7 @@ export function render({ navigate }) {
|
||||
actions.className = 'auth-footer-actions';
|
||||
actions.append(enterButton);
|
||||
|
||||
const { overlay, progress } = createSecretOverlay();
|
||||
const keyGeneration = createSecretGenerationOverlay();
|
||||
|
||||
const submit = async () => {
|
||||
const currentLogin = String(state.loginDraft.login || '').trim();
|
||||
@@ -131,14 +105,10 @@ export function render({ navigate }) {
|
||||
return;
|
||||
}
|
||||
|
||||
overlay.style.display = 'grid';
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password, {
|
||||
onProgress: ({ percent }) => {
|
||||
const value = Math.max(0, Math.min(100, Number(percent) || 0));
|
||||
progress.textContent = value > 0 && value < 100 ? `${Math.round(value)}%` : '';
|
||||
},
|
||||
});
|
||||
overlay.style.display = 'none';
|
||||
keyGeneration.show();
|
||||
await new Promise(resolve => setTimeout(resolve, 40));
|
||||
const keyBundle = await authService.derivePasswordKeyBundle(currentLogin, password);
|
||||
keyGeneration.hide();
|
||||
|
||||
enterButton.textContent = t('screens.login_password_view.text_006');
|
||||
const result = await authService.createAuthSession(currentLogin, keyBundle);
|
||||
@@ -156,6 +126,8 @@ export function render({ navigate }) {
|
||||
});
|
||||
state.loginDraft.login = result.login;
|
||||
state.loginDraft.password = '';
|
||||
// Clear the actual textarea as soon as login succeeds, before route change.
|
||||
passwordInput.clearPasswordField();
|
||||
state.loginDraft.passwordMode = 'single';
|
||||
state.loginDraft.passwordWords = emptyPasswordWords();
|
||||
resetRegistrationFlow();
|
||||
@@ -164,7 +136,7 @@ export function render({ navigate }) {
|
||||
setAuthInfo(t('screens.login_password_view.text_010', { value1: result.login }));
|
||||
navigate(consumeAuthReturnPage('profile-view'));
|
||||
} catch (error) {
|
||||
overlay.style.display = 'none';
|
||||
keyGeneration.hide();
|
||||
const message = toUserMessage(error, t('screens.login_password_view.text_008'));
|
||||
setAuthError(message);
|
||||
setStatus(status, message);
|
||||
@@ -178,7 +150,7 @@ export function render({ navigate }) {
|
||||
|
||||
enterButton.addEventListener('click', submit);
|
||||
passwordInput.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
@@ -192,9 +164,9 @@ export function render({ navigate }) {
|
||||
back: { label: '←', onClick: () => navigate('login-view') },
|
||||
}),
|
||||
panel,
|
||||
overlay,
|
||||
keyGeneration.overlay,
|
||||
);
|
||||
|
||||
window.setTimeout(() => passwordInput.focus(), 0);
|
||||
window.setTimeout(() => { passwordInput.resizePasswordField(); passwordInput.focus(); }, 0);
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createVisiblePasswordField } from '../components/visible-password-field.js';
|
||||
import { createVisiblePasswordField, createExpandablePasswordTextarea } from '../components/visible-password-field.js';
|
||||
import { createSecretGenerationOverlay } from '../components/secret-generation-overlay.js';
|
||||
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
|
||||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||||
import { authService, clearAuthMessages, clearRegistrationDraft, state } from '../state.js';
|
||||
@@ -18,7 +19,8 @@ export function render({ navigate }) {
|
||||
const body = document.createElement('div');
|
||||
body.className = 'card stack registration-form signup-wizard__body';
|
||||
const header = createTopBar({ title: t('screens.register_view.text_002'), back: { label: '←', onClick: goBack } });
|
||||
screen.append(header, body);
|
||||
const keyGeneration = createSecretGenerationOverlay();
|
||||
screen.append(header, body, keyGeneration.overlay);
|
||||
|
||||
let namespaces = [];
|
||||
let isLoading = true;
|
||||
@@ -143,14 +145,21 @@ export function render({ navigate }) {
|
||||
const labelText = document.createElement('span');
|
||||
labelText.className = 'field-label';
|
||||
labelText.textContent = t('screens.register_view.text_031', { value1: PASSWORD_MAX_LENGTH });
|
||||
const input = document.createElement('input');
|
||||
input.className = 'input';
|
||||
input.type = 'text';
|
||||
const input = createExpandablePasswordTextarea();
|
||||
input.autocomplete = 'new-password';
|
||||
input.maxLength = PASSWORD_MAX_LENGTH;
|
||||
input.placeholder = t('screens.register_view.text_009');
|
||||
input.value = draft.password || '';
|
||||
label.append(labelText, createVisiblePasswordField(input));
|
||||
// Never repopulate a successfully submitted secret on returning to this step.
|
||||
input.value = '';
|
||||
const passwordCount = document.createElement('span');
|
||||
passwordCount.className = 'password-length-hint';
|
||||
passwordCount.setAttribute('aria-live', 'off');
|
||||
const refreshPasswordCount = () => {
|
||||
passwordCount.textContent = t('screens.register_view.password_counter', { value1: input.value.length, value2: PASSWORD_MAX_LENGTH });
|
||||
};
|
||||
label.append(labelText, createVisiblePasswordField(input), passwordCount);
|
||||
refreshPasswordCount();
|
||||
requestAnimationFrame(() => input.resizePasswordField());
|
||||
const guidance = document.createElement('div');
|
||||
guidance.className = 'signup-guidance';
|
||||
guidance.innerHTML = `
|
||||
@@ -167,7 +176,13 @@ export function render({ navigate }) {
|
||||
next.className = 'primary-btn signup-next';
|
||||
next.type = 'button';
|
||||
next.textContent = t('screens.register_view.text_010');
|
||||
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; });
|
||||
input.addEventListener('input', () => { inputRevision++; status.textContent = ''; refreshPasswordCount(); });
|
||||
input.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault();
|
||||
next.click();
|
||||
}
|
||||
});
|
||||
next.addEventListener('click', async () => {
|
||||
const value = input.value;
|
||||
if (value.length < 1 || value.length > PASSWORD_MAX_LENGTH) {
|
||||
@@ -188,9 +203,13 @@ export function render({ navigate }) {
|
||||
}
|
||||
const revision = inputRevision;
|
||||
const thisRequest = ++requestId;
|
||||
const needsGeneration = draft.password !== value || !draft.preGeneratedKeyBundle;
|
||||
next.disabled = true;
|
||||
status.textContent = t('screens.register_view.text_013');
|
||||
status.textContent = '';
|
||||
if (needsGeneration) keyGeneration.show();
|
||||
try {
|
||||
// Дать браузеру отрисовать заставку до тяжёлого KDF.
|
||||
if (needsGeneration) await new Promise(resolve => setTimeout(resolve, 40));
|
||||
const changed = draft.password !== value;
|
||||
draft.password = value;
|
||||
if (changed) draft.preGeneratedKeyBundle = null;
|
||||
@@ -198,10 +217,14 @@ export function render({ navigate }) {
|
||||
if (!screen.isConnected || thisRequest !== requestId) return;
|
||||
if (revision !== inputRevision) throw new Error(t('screens.register_view.text_027'));
|
||||
draft.preGeneratedKeyBundle = bundle;
|
||||
// Hide the password before navigation to prevent a visible flash.
|
||||
input.clearPasswordField();
|
||||
refreshPasswordCount();
|
||||
navigate(flowType === 'free' ? 'registration-email-view' : 'registration-payment-view');
|
||||
} catch (error) {
|
||||
if (screen.isConnected && thisRequest === requestId) status.textContent = error.message || t('screens.register_view.text_028');
|
||||
} finally {
|
||||
keyGeneration.hide();
|
||||
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -898,6 +898,7 @@
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 12000;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: var(--surface);
|
||||
@@ -906,9 +907,12 @@
|
||||
}
|
||||
|
||||
|
||||
.secret-generation-overlay[hidden] { display: none; }
|
||||
|
||||
.secret-generation-card {
|
||||
width: min(100%, 290px);
|
||||
width: min(100%, 350px);
|
||||
place-items: center;
|
||||
gap: 16px;
|
||||
padding: 28px 24px;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 18%, transparent);
|
||||
border-radius: 20px;
|
||||
@@ -930,15 +934,16 @@
|
||||
|
||||
.secret-generation-title {
|
||||
color: var(--preauth-ivory, var(--text-primary));
|
||||
font-size: 18px;
|
||||
font-weight: 650;
|
||||
font-size: 21px;
|
||||
line-height: 1.3;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
|
||||
.secret-generation-progress {
|
||||
min-height: 20px;
|
||||
color: var(--preauth-muted, var(--accent));
|
||||
font-size: 13px;
|
||||
.secret-generation-description {
|
||||
margin: 0;
|
||||
color: var(--preauth-muted, var(--text-secondary));
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
@@ -1593,6 +1598,12 @@
|
||||
width: 100%;
|
||||
padding-right: 50px;
|
||||
}
|
||||
/* Keep input, eye button and mask aligned at 32 monospaced characters. */
|
||||
.auth-password-field--multiline {
|
||||
width: min(100%, calc(32ch + 64px));
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 16px;
|
||||
}
|
||||
.auth-password-field__toggle {
|
||||
position: absolute;
|
||||
right: 2px;
|
||||
@@ -1619,3 +1630,55 @@
|
||||
width: 21px;
|
||||
height: 21px;
|
||||
}
|
||||
|
||||
/* Адаптивная парольная фраза: от одной до трёх строк, при любом количестве символов. */
|
||||
.auth-password-field > .input.auth-password-field__textarea {
|
||||
display: block;
|
||||
/* 32 characters when space allows; on narrow screens the field shrinks. */
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
height: auto;
|
||||
padding: 10px 50px 10px 12px;
|
||||
resize: none;
|
||||
overflow-y: auto;
|
||||
/* A scrollbar would steal one character column and misalign the bullet mirror. */
|
||||
scrollbar-width: none;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-all;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.auth-password-field__textarea::-webkit-scrollbar { display: none; }
|
||||
.auth-password-field__mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 12px;
|
||||
padding: 10px 50px 10px 12px;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-all;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
color: var(--text-primary);
|
||||
text-align: start;
|
||||
}
|
||||
.auth-password-field__mask[hidden] { display: none; }
|
||||
.auth-password-field--masked > .auth-password-field__textarea {
|
||||
color: transparent;
|
||||
-webkit-text-fill-color: transparent;
|
||||
caret-color: var(--accent);
|
||||
}
|
||||
.auth-password-field__textarea:focus + .auth-password-field__mask {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.auth-password-field > .auth-password-field__textarea + .auth-password-field__mask + .auth-password-field__toggle {
|
||||
top: 2px;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const read = file => fs.readFileSync(new URL(file, import.meta.url), 'utf8');
|
||||
const registration = read('../js/pages/register-view.js');
|
||||
const login = read('../js/pages/login-password-view.js');
|
||||
const field = read('../js/components/visible-password-field.js');
|
||||
const overlay = read('../js/components/secret-generation-overlay.js');
|
||||
const ru = JSON.parse(read('../js/i18n/locales/ru.json'));
|
||||
const en = JSON.parse(read('../js/i18n/locales/en.json'));
|
||||
|
||||
test('регистрация: один символ разрешён, счётчик только здесь, максимум 256', () => {
|
||||
assert.match(registration, /value\.length < 1/);
|
||||
assert.doesNotMatch(registration, /value\.length < (?:10|12)/);
|
||||
assert.match(registration, /screens\.register_view\.password_counter/);
|
||||
assert.doesNotMatch(login, /password_counter/);
|
||||
assert.match(read('../js/services/password-words.js'), /PASSWORD_MAX_LENGTH = 256/);
|
||||
});
|
||||
|
||||
test('обе формы используют многострочное парольное поле с видимостью', () => {
|
||||
assert.match(registration, /createExpandablePasswordTextarea\(\)/);
|
||||
assert.match(login, /createExpandablePasswordTextarea\(\)/);
|
||||
assert.match(field, /input\.rows = 1/);
|
||||
assert.match(field, /3 \* lineHeight/);
|
||||
assert.match(field, /auth-password-field--masked/);
|
||||
assert.match(field, /input\.updatePasswordMask\(\)/);
|
||||
});
|
||||
|
||||
test('одна заставка, без процента и прогресса в обоих сценариях', () => {
|
||||
assert.match(login, /createSecretGenerationOverlay\(\)/);
|
||||
assert.match(registration, /createSecretGenerationOverlay\(\)/);
|
||||
assert.match(registration, /keyGeneration\.show\(\)/);
|
||||
assert.match(login, /keyGeneration\.show\(\)/);
|
||||
assert.doesNotMatch(login, /onProgress|percent|\.progress/);
|
||||
assert.doesNotMatch(overlay, /percent|progress/);
|
||||
assert.equal(ru.components.secret_generation_overlay.title, 'Генерируем ваши цифровые ключи…');
|
||||
assert.match(ru.components.secret_generation_overlay.description, /логина и пароля/);
|
||||
assert.ok(en.components.secret_generation_overlay.title);
|
||||
});
|
||||
|
||||
test('32 символа на строку без реального перевода строки в пароле', () => {
|
||||
assert.match(field, /input\.cols = 32/);
|
||||
assert.match(field, /input\.wrap = 'soft'/);
|
||||
assert.match(field, /auth-password-field--multiline/);
|
||||
const css = read('../styles/features/preauth.css');
|
||||
assert.match(css, /32ch \+ 64px/);
|
||||
assert.match(css, /auth-password-field--multiline/);
|
||||
});
|
||||
|
||||
test('после успеха очищается видимое поле, не рабочие ключи', () => {
|
||||
assert.match(field, /input\.clearPasswordField = \(\) =>/);
|
||||
assert.match(field, /input\.updatePasswordMask\?\.\(\)/);
|
||||
assert.match(registration, /draft\.preGeneratedKeyBundle = bundle;[\s\S]*?input\.clearPasswordField\(\);[\s\S]*?navigate\(/);
|
||||
assert.match(registration, /input\.value = ''/);
|
||||
assert.doesNotMatch(registration, /input\.value = draft\.password/);
|
||||
assert.match(login, /state\.loginDraft\.password = '';[\s\S]*?passwordInput\.clearPasswordField\(\)/);
|
||||
assert.match(ru.components.secret_generation_overlay.description, /на этом устройстве/);
|
||||
assert.match(en.components.secret_generation_overlay.description, /on this device/);
|
||||
});
|
||||
|
||||
test('текст регистрации на двух языках и определённое предупреждение', () => {
|
||||
assert.match(ru.screens.register_view.text_038, /будет утрачен навсегда/);
|
||||
assert.doesNotMatch(ru.screens.register_view.text_038, /может быть утрачен/);
|
||||
assert.match(ru.screens.register_view.text_036, /12–16/);
|
||||
assert.match(ru.screens.register_view.text_035, /кошелькам/);
|
||||
assert.match(en.screens.register_view.text_038, /lost forever/);
|
||||
});
|
||||
@@ -26,7 +26,10 @@ test('пароль допускает один символ, а email можно
|
||||
const email = read('../js/pages/registration-email-view.js');
|
||||
assert.match(registration, /value\.length < 1/);
|
||||
assert.doesNotMatch(registration, /value\.length < 12/);
|
||||
assert.match(registration, /input\.type = 'text'/);
|
||||
assert.match(registration, /createExpandablePasswordTextarea\(\)/);
|
||||
const passwordField = read('../js/components/visible-password-field.js');
|
||||
assert.match(passwordField, /createExpandablePasswordTextarea/);
|
||||
assert.match(passwordField, /input\.tagName === 'TEXTAREA'/);
|
||||
assert.match(email, /let emailRequestId = 0/);
|
||||
assert.match(email, /requestId !== emailRequestId/);
|
||||
assert.match(email, /emailRequestId \+= 1/);
|
||||
|
||||
Reference in New Issue
Block a user