SHA256
376 lines
15 KiB
JavaScript
376 lines
15 KiB
JavaScript
import { t, th } from '../i18n/index.js';
|
|
import { createTopBar } from '../components/topbar.js';
|
|
import {
|
|
authService,
|
|
authorizeSession,
|
|
consumeAuthReturnPage,
|
|
isAddingProfileLogin,
|
|
clearAuthMessages,
|
|
clearBrowserClientData,
|
|
refreshSessions,
|
|
setAuthBusy,
|
|
setAuthError,
|
|
setAuthInfo,
|
|
state,
|
|
terminateCurrentSession,
|
|
} from '../state.js';
|
|
import { showToast } from '../services/channels-ux.js';
|
|
import {
|
|
decryptPairingPayloadFromEnvelope,
|
|
createRequesterPairingMaterial,
|
|
formatPairingShortCode,
|
|
} from '../services/device-pairing-service.js';
|
|
import { clearClientAuthData, saveEncryptedUserSecrets } from '../services/key-vault.js';
|
|
import { clearStoredMessages } from '../services/message-store.js';
|
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
|
|
|
export const pageMeta = { id: 'login-other-device-view', get title() { return t('screens.login_other_device_view.text_001'); }, showAppChrome: false };
|
|
|
|
function formatRemaining(ms) {
|
|
const safe = Math.max(0, Math.ceil(Number(ms || 0) / 1000));
|
|
return `${Math.floor(safe / 60)}:${String(safe % 60).padStart(2, '0')}`;
|
|
}
|
|
|
|
export function render({ navigate }) {
|
|
const screen = document.createElement('section');
|
|
screen.className = 'stack pairing-login';
|
|
let pollTimer = 0;
|
|
let countdownTimer = 0;
|
|
let activePairingId = '';
|
|
let requesterMaterial = null;
|
|
let activeExpiresAtMs = 0;
|
|
let isDisposed = false;
|
|
|
|
clearAuthMessages();
|
|
|
|
const who = document.createElement('p');
|
|
who.className = 'pairing-who';
|
|
|
|
// Код и то, что с ним делать.
|
|
const codeBlock = document.createElement('div');
|
|
codeBlock.className = 'pairing-code-block';
|
|
codeBlock.innerHTML = `
|
|
<div class="pairing-code-card">
|
|
<p class="pairing-code-card__label">${th('screens.login_other_device_view.text_032')}</p>
|
|
<div class="pairing-code" id="pairing-short-code"></div>
|
|
<div class="pairing-timer" aria-live="off">
|
|
<div class="pairing-timer__bar"><span id="pairing-timer-fill"></span></div>
|
|
<span class="pairing-timer__text" id="pairing-timer-text"></span>
|
|
</div>
|
|
<p class="pairing-online" id="pairing-online"></p>
|
|
</div>
|
|
<ol class="pairing-steps">
|
|
<li>${th('screens.login_other_device_view.text_033')}</li>
|
|
<li>${th('screens.login_other_device_view.text_034')}</li>
|
|
<li>${th('screens.login_other_device_view.text_035')}</li>
|
|
</ol>
|
|
<p class="pairing-waiting"><span class="pairing-spinner" aria-hidden="true"></span>${th('screens.login_other_device_view.text_036')}</p>
|
|
`;
|
|
|
|
// Сообщение о ходе дела или об ошибке — вместо кода.
|
|
const notice = document.createElement('div');
|
|
notice.className = 'pairing-notice';
|
|
notice.setAttribute('role', 'status');
|
|
const noticeSpinner = document.createElement('span');
|
|
noticeSpinner.className = 'pairing-spinner';
|
|
noticeSpinner.setAttribute('aria-hidden', 'true');
|
|
const noticeText = document.createElement('p');
|
|
notice.append(noticeSpinner, noticeText);
|
|
|
|
// Дополнительный пароль pairing пока не используется в активном UI.
|
|
|
|
const startBtn = document.createElement('button');
|
|
startBtn.className = 'primary-btn';
|
|
startBtn.type = 'button';
|
|
startBtn.textContent = t('screens.login_other_device_view.text_002');
|
|
|
|
const loginInput = { value: String(state.loginDraft.login || '').trim() };
|
|
who.textContent = loginInput.value ? t('screens.login_other_device_view.text_026', { value1: loginInput.value }) : '';
|
|
const shortCodeEl = codeBlock.querySelector('#pairing-short-code');
|
|
const timerFillEl = codeBlock.querySelector('#pairing-timer-fill');
|
|
const timerTextEl = codeBlock.querySelector('#pairing-timer-text');
|
|
const onlineEl = codeBlock.querySelector('#pairing-online');
|
|
let activeStartedAtMs = 0;
|
|
|
|
// Этапы: creating → code → approving; retry используется для истечения, отклонения и ошибок.
|
|
const showStage = (stage, message = '', { error = false, action = '' } = {}) => {
|
|
codeBlock.hidden = stage !== 'code';
|
|
notice.hidden = stage === 'code';
|
|
noticeSpinner.hidden = !(stage === 'creating' || stage === 'approving');
|
|
noticeText.textContent = message;
|
|
notice.classList.toggle('is-error', error);
|
|
startBtn.hidden = stage !== 'retry';
|
|
if (action) startBtn.textContent = action;
|
|
};
|
|
|
|
const stopPolling = () => {
|
|
if (pollTimer) {
|
|
window.clearTimeout(pollTimer);
|
|
pollTimer = 0;
|
|
}
|
|
};
|
|
|
|
const stopCountdown = () => {
|
|
if (countdownTimer) {
|
|
window.clearInterval(countdownTimer);
|
|
countdownTimer = 0;
|
|
}
|
|
};
|
|
|
|
const updateCountdown = () => {
|
|
const leftMs = activeExpiresAtMs - Date.now();
|
|
if (leftMs <= 0) {
|
|
stopPolling();
|
|
stopCountdown();
|
|
activePairingId = '';
|
|
activeExpiresAtMs = 0;
|
|
startBtn.disabled = false;
|
|
showStage('retry', t('screens.login_other_device_view.text_004'), { error: true, action: t('screens.login_other_device_view.text_013') });
|
|
return;
|
|
}
|
|
const totalMs = Math.max(1, activeExpiresAtMs - activeStartedAtMs);
|
|
timerFillEl.style.width = `${Math.min(100, (leftMs / totalMs) * 100).toFixed(1)}%`;
|
|
timerTextEl.textContent = formatRemaining(leftMs);
|
|
};
|
|
|
|
const startCountdown = (expiresAtMs) => {
|
|
activeExpiresAtMs = Number(expiresAtMs || 0);
|
|
activeStartedAtMs = Date.now();
|
|
stopCountdown();
|
|
updateCountdown();
|
|
countdownTimer = window.setInterval(updateCountdown, 1000);
|
|
};
|
|
|
|
const clearActivePairing = () => {
|
|
stopPolling();
|
|
stopCountdown();
|
|
activePairingId = '';
|
|
activeExpiresAtMs = 0;
|
|
};
|
|
|
|
const finalizeAuthorizedLogin = async (keys, login) => {
|
|
if (!String(keys?.clientKey || '').trim() || !String(keys?.blockchainKey || '').trim()) {
|
|
throw new Error(t('screens.login_other_device_view.text_022'));
|
|
}
|
|
const session = await authService.createSessionFromImportedSecrets(login, keys);
|
|
const addingProfile = isAddingProfileLogin();
|
|
if (!addingProfile) {
|
|
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
|
clearBrowserClientData();
|
|
await clearClientAuthData().catch(() => {});
|
|
}
|
|
await clearStoredMessages(session.login).catch(() => {});
|
|
await saveEncryptedUserSecrets(session.login, session.storagePwd, keys);
|
|
await authService.persistSessionMaterial(session.login, session.sessionMaterial);
|
|
const resumed = await authService.resumeSession(session.login, session.sessionId);
|
|
authorizeSession({
|
|
login: resumed.login || session.login,
|
|
sessionId: resumed.sessionId || session.sessionId,
|
|
storagePwd: resumed.storagePwd || session.storagePwd,
|
|
});
|
|
state.loginDraft.login = resumed.login || session.login;
|
|
state.loginDraft.password = '';
|
|
await refreshSessions();
|
|
setAuthInfo(t('screens.login_other_device_view.text_027', { value1: resumed.login || session.login }));
|
|
showToast(t('screens.login_other_device_view.text_028', { value1: resumed.login || session.login }));
|
|
navigate(consumeAuthReturnPage('profile-view'));
|
|
};
|
|
|
|
const finalizeAuthorizedSessionAttach = async (payloadSession, login, requesterKeys) => {
|
|
const sessionId = String(payloadSession?.sessionId || '').trim();
|
|
const storagePwd = String(payloadSession?.storagePwd || '').trim();
|
|
if (!sessionId || !storagePwd) {
|
|
throw new Error(t('screens.login_other_device_view.text_023'));
|
|
}
|
|
const sessionMaterial = {
|
|
sessionId,
|
|
sessionKey: requesterKeys.sessionKey,
|
|
sessionPrivPkcs8: requesterKeys.sessionPrivPkcs8,
|
|
sessionType: Number(payloadSession?.sessionType || 50) || 50,
|
|
};
|
|
|
|
const addingProfile = isAddingProfileLogin();
|
|
if (!addingProfile) {
|
|
await terminateCurrentSession({ closeServerSession: true, notifySessionReset: false });
|
|
clearBrowserClientData();
|
|
await clearClientAuthData().catch(() => {});
|
|
}
|
|
await clearStoredMessages(login).catch(() => {});
|
|
await authService.persistSessionMaterial(login, sessionMaterial);
|
|
const resumed = await authService.resumeSession(login, sessionId);
|
|
authorizeSession({
|
|
login: resumed.login || login,
|
|
sessionId: resumed.sessionId || sessionId,
|
|
storagePwd: resumed.storagePwd || storagePwd,
|
|
});
|
|
state.loginDraft.login = resumed.login || login;
|
|
state.loginDraft.password = '';
|
|
await refreshSessions();
|
|
setAuthInfo(t('screens.login_other_device_view.text_029', { value1: resumed.login || login }));
|
|
showToast(t('screens.login_other_device_view.text_030', { value1: resumed.login || login }));
|
|
navigate(consumeAuthReturnPage('profile-view'));
|
|
};
|
|
|
|
const schedulePoll = () => {
|
|
stopPolling();
|
|
if (!activePairingId || isDisposed) return;
|
|
pollTimer = window.setTimeout(async () => {
|
|
try {
|
|
const payload = await authService.getTrustedDeviceLoginStatus(activePairingId);
|
|
const stateValue = String(payload?.state || '');
|
|
if (stateValue === 'created') {
|
|
schedulePoll();
|
|
return;
|
|
}
|
|
if (stateValue === 'approved') {
|
|
stopCountdown();
|
|
showStage('approving', t('screens.login_other_device_view.text_005'));
|
|
const decoded = await decryptPairingPayloadFromEnvelope(payload?.encryptedPayload, requesterMaterial);
|
|
const decodedType = String(decoded?.type || '');
|
|
if (decodedType === 'shine-esp-session-attach') {
|
|
await finalizeAuthorizedSessionAttach(decoded.session, decoded.login || loginInput.value, requesterMaterial);
|
|
return;
|
|
}
|
|
if (decodedType !== 'shine-esp-pairing-transfer') {
|
|
throw new Error(t('screens.login_other_device_view.text_024'));
|
|
}
|
|
await finalizeAuthorizedLogin(decoded.keys, decoded.login || loginInput.value);
|
|
return;
|
|
}
|
|
if (stateValue === 'rejected') {
|
|
clearActivePairing();
|
|
startBtn.disabled = false;
|
|
showStage('retry', t('screens.login_other_device_view.text_006'), { error: true, action: t('screens.login_other_device_view.text_014') });
|
|
return;
|
|
}
|
|
if (stateValue === 'canceled') {
|
|
clearActivePairing();
|
|
startBtn.disabled = false;
|
|
showStage('retry', t('screens.login_other_device_view.text_007'), { error: true, action: t('screens.login_other_device_view.text_015') });
|
|
return;
|
|
}
|
|
if (stateValue === 'expired') {
|
|
clearActivePairing();
|
|
startBtn.disabled = false;
|
|
showStage('retry', t('screens.login_other_device_view.text_008'), { error: true, action: t('screens.login_other_device_view.text_016') });
|
|
return;
|
|
}
|
|
schedulePoll();
|
|
} catch (error) {
|
|
clearActivePairing();
|
|
startBtn.disabled = false;
|
|
const message = toUserMessage(error, t('screens.login_other_device_view.text_009'));
|
|
setAuthError(message);
|
|
showStage('retry', message, { error: true, action: t('screens.login_other_device_view.text_017') });
|
|
}
|
|
}, 2200);
|
|
};
|
|
|
|
startBtn.addEventListener('click', async () => {
|
|
const login = String(loginInput.value || '').trim();
|
|
if (!login) {
|
|
navigate('login-view');
|
|
return;
|
|
}
|
|
startBtn.disabled = true;
|
|
setAuthBusy(true);
|
|
setAuthError('');
|
|
setAuthInfo('');
|
|
clearActivePairing();
|
|
showStage('creating', t('screens.login_other_device_view.text_010'));
|
|
|
|
try {
|
|
await authService.reconnect(state.entrySettings.shineServer);
|
|
const resolved = await authService.resolveLoginForAuth(login);
|
|
if (String(resolved?.resolution || '').toUpperCase() !== 'LOCAL') {
|
|
state.loginDraft.login = String(resolved?.login || login).trim();
|
|
navigate('login-view');
|
|
return;
|
|
}
|
|
|
|
requesterMaterial = await createRequesterPairingMaterial();
|
|
const payload = await authService.startTrustedDeviceLogin({
|
|
login,
|
|
// Активный сценарий временно всегда без дополнительного пароля.
|
|
passwordHash: '',
|
|
requesterSessionKey: requesterMaterial.sessionKey,
|
|
payloadType: 2,
|
|
});
|
|
|
|
activePairingId = String(payload?.pairingId || '');
|
|
if (!activePairingId) {
|
|
throw new Error(t('screens.login_other_device_view.text_025'));
|
|
}
|
|
|
|
shortCodeEl.textContent = formatPairingShortCode(payload?.shortCode || '');
|
|
shortCodeEl.setAttribute('aria-label', t('screens.login_other_device_view.text_031', { value1: String(payload?.shortCode || '').split('').join(' ') }));
|
|
const online = !!payload?.trustedSessionOnline;
|
|
onlineEl.textContent = online ? t('screens.login_other_device_view.text_018') : t('screens.login_other_device_view.text_019');
|
|
onlineEl.classList.toggle('is-online', online);
|
|
showStage('code');
|
|
startCountdown(payload?.expiresAtMs);
|
|
state.loginDraft.login = login;
|
|
schedulePoll();
|
|
} catch (error) {
|
|
startBtn.disabled = false;
|
|
if (String(error?.code || '').toUpperCase() === 'PAIRING_PASSWORD_INVALID') {
|
|
showStage(
|
|
'retry',
|
|
t('screens.login_other_device_view.text_011'),
|
|
{ error: true, action: t('screens.login_other_device_view.text_020') },
|
|
);
|
|
} else {
|
|
const message = toUserMessage(error, t('screens.login_other_device_view.text_012'));
|
|
setAuthError(message);
|
|
showStage('retry', message, { error: true, action: t('screens.login_other_device_view.text_021') });
|
|
}
|
|
} finally {
|
|
setAuthBusy(false);
|
|
}
|
|
});
|
|
|
|
const cancelActivePairingAndBack = async () => {
|
|
const pairingId = activePairingId;
|
|
const requesterSessionKey = requesterMaterial?.sessionKey;
|
|
isDisposed = true;
|
|
stopPolling();
|
|
stopCountdown();
|
|
if (pairingId && requesterSessionKey) {
|
|
try {
|
|
await authService.cancelTrustedDeviceLogin(pairingId, requesterSessionKey);
|
|
} catch {
|
|
// Навигацию назад не блокируем из-за ошибки отмены уже созданной заявки.
|
|
}
|
|
}
|
|
navigate('login-view');
|
|
};
|
|
|
|
screen.cleanup = () => {
|
|
isDisposed = true;
|
|
stopPolling();
|
|
stopCountdown();
|
|
if (activePairingId && requesterMaterial?.sessionKey) {
|
|
void authService.cancelTrustedDeviceLogin(activePairingId, requesterMaterial.sessionKey).catch(() => {});
|
|
}
|
|
};
|
|
|
|
screen.append(
|
|
createTopBar({
|
|
title: t('screens.login_other_device_view.text_003'),
|
|
back: { label: '←', onClick: () => { void cancelActivePairingAndBack(); } },
|
|
}),
|
|
who,
|
|
codeBlock,
|
|
notice,
|
|
startBtn,
|
|
);
|
|
|
|
if (!String(loginInput.value || '').trim()) {
|
|
window.setTimeout(() => navigate('login-view'), 0);
|
|
} else {
|
|
// После проверки логина на предыдущем экране код создаётся сразу.
|
|
window.setTimeout(() => startBtn.click(), 0);
|
|
}
|
|
return screen;
|
|
}
|