SHA256
Исправить восстановление входа при занятом WebSocket
This commit is contained in:
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.20.45
|
client.version=1.20.46
|
||||||
server.version=1.16.25
|
server.version=1.16.25
|
||||||
|
|||||||
@@ -175,9 +175,15 @@ export function render({ navigate }) {
|
|||||||
retry.disabled = true;
|
retry.disabled = true;
|
||||||
status.textContent = t('screens.registration_email_view.text_022');
|
status.textContent = t('screens.registration_email_view.text_022');
|
||||||
try {
|
try {
|
||||||
const result = await confirmFreeRegistration(draft.challengeId, code.value.trim());
|
// Подтверждение email идемпотентно на уровне сценария: после первого
|
||||||
|
// успешного ответа повторяем только финальный вход, а не AuthChallenge
|
||||||
|
// регистрации. Иначе предыдущий CreateAuthSession мог оставить сокет
|
||||||
|
// авторизованным, и сервер вернёт ALREADY_AUTHED.
|
||||||
|
if (!draft.dataItemId) {
|
||||||
|
const result = await confirmFreeRegistration(draft.challengeId, code.value.trim());
|
||||||
|
draft.dataItemId = result.dataItemId;
|
||||||
|
}
|
||||||
if (!screen.isConnected || disposed) return;
|
if (!screen.isConnected || disposed) return;
|
||||||
draft.dataItemId = result.dataItemId;
|
|
||||||
status.textContent = t('screens.registration_email_view.text_023');
|
status.textContent = t('screens.registration_email_view.text_023');
|
||||||
await completeRegistrationLogin({ navigate, keyBundle: draft.preGeneratedKeyBundle });
|
await completeRegistrationLogin({ navigate, keyBundle: draft.preGeneratedKeyBundle });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -91,7 +91,9 @@ function clamp(value, min, max) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
export async function completeRegistrationLogin({ navigate, keyBundle }) {
|
||||||
await authService.reconnect(state.entrySettings.shineServer);
|
// Финальный вход регистрации нельзя повторять на сокете, который мог
|
||||||
|
// стать авторизованным после частично успешной предыдущей попытки.
|
||||||
|
authService.resetConnection(state.entrySettings.shineServer, { clearSessionContext: true });
|
||||||
const result = await authService.createSessionForExistingUser(
|
const result = await authService.createSessionForExistingUser(
|
||||||
state.registrationDraft.login,
|
state.registrationDraft.login,
|
||||||
state.registrationDraft.password,
|
state.registrationDraft.password,
|
||||||
|
|||||||
@@ -1151,13 +1151,33 @@ export class AuthService {
|
|||||||
const clientPair = keyBundle?.clientPair;
|
const clientPair = keyBundle?.clientPair;
|
||||||
if (!clientPair) throw new Error('createAuthSession: не передан clientPair');
|
if (!clientPair) throw new Error('createAuthSession: не передан clientPair');
|
||||||
|
|
||||||
|
// Новый вход всегда начинается на анонимном транспорте. Это важно после
|
||||||
|
// частично успешной попытки: сервер хранит авторизацию в ConnectionContext
|
||||||
|
// конкретного WebSocket, поэтому повторный AuthChallenge на нём получает
|
||||||
|
// ALREADY_AUTHED даже для другого логина.
|
||||||
|
if (this.ws.isSessionReady()) {
|
||||||
|
this.resetConnection(this.serverUrl, { clearSessionContext: true });
|
||||||
|
}
|
||||||
|
|
||||||
const sessionPair = await generateEd25519Pair();
|
const sessionPair = await generateEd25519Pair();
|
||||||
const sessionKeyPub = await exportEd25519PublicKeyB64(sessionPair.publicKey);
|
const sessionKeyPub = await exportEd25519PublicKeyB64(sessionPair.publicKey);
|
||||||
const sessionKey = `ed25519/${sessionKeyPub}`;
|
const sessionKey = `ed25519/${sessionKeyPub}`;
|
||||||
const storagePwd = randomBase64(32);
|
const storagePwd = randomBase64(32);
|
||||||
|
|
||||||
const challengeResp = await this.ws.request('AuthChallenge', { login: cleanLogin });
|
let challengeResp;
|
||||||
if (challengeResp.status !== 200) throw opError('AuthChallenge', challengeResp);
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||||
|
challengeResp = await this.ws.request('AuthChallenge', { login: cleanLogin });
|
||||||
|
if (challengeResp.status === 200) break;
|
||||||
|
|
||||||
|
const error = opError('AuthChallenge', challengeResp);
|
||||||
|
if (attempt === 0 && error.code === 'ALREADY_AUTHED') {
|
||||||
|
// Сбрасываем только транспорт. Ключи и данные регистрации остаются
|
||||||
|
// в памяти, после чего повторяем только challenge на новом сокете.
|
||||||
|
this.resetConnection(this.serverUrl, { clearSessionContext: true });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
const authNonce = challengeResp?.payload?.authNonce;
|
const authNonce = challengeResp?.payload?.authNonce;
|
||||||
if (!authNonce) throw new Error('AuthChallenge: сервер не вернул authNonce');
|
if (!authNonce) throw new Error('AuthChallenge: сервер не вернул authNonce');
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ const finish = paymentView.split('export async function completeRegistrationLogi
|
|||||||
test('Solana и Arweave используют единое завершение регистрации', () => {
|
test('Solana и Arweave используют единое завершение регистрации', () => {
|
||||||
assert.match(paymentView, /await completeRegistrationLogin\(\{ navigate, keyBundle \}\)/);
|
assert.match(paymentView, /await completeRegistrationLogin\(\{ navigate, keyBundle \}\)/);
|
||||||
assert.match(emailView, /await completeRegistrationLogin\(\{\s*navigate,\s*keyBundle:\s*draft\.preGeneratedKeyBundle\s*\}\)/);
|
assert.match(emailView, /await completeRegistrationLogin\(\{\s*navigate,\s*keyBundle:\s*draft\.preGeneratedKeyBundle\s*\}\)/);
|
||||||
|
assert.match(emailView, /if \(!draft\.dataItemId\) \{/);
|
||||||
|
assert.match(paymentView, /authService\.resetConnection\(state\.entrySettings\.shineServer, \{ clearSessionContext: true \}\)/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('после авторизации на завершении регистрации создаётся HEADER с актуальными логином и ключом', () => {
|
test('после авторизации на завершении регистрации создаётся HEADER с актуальными логином и ключом', () => {
|
||||||
@@ -22,6 +24,13 @@ test('сбой HEADER не отменяет регистрацию; защита
|
|||||||
assert.match(authService, /if \(!_skipHeaderEnsure && !isHeader\) \{\s*await this\.ensureBlockchainHeader\(cleanLogin, storagePwd\)/);
|
assert.match(authService, /if \(!_skipHeaderEnsure && !isHeader\) \{\s*await this\.ensureBlockchainHeader\(cleanLogin, storagePwd\)/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('новый вход восстанавливается на новом WebSocket после ALREADY_AUTHED', () => {
|
||||||
|
assert.match(authService, /if \(this\.ws\.isSessionReady\(\)\) \{[\s\S]*?this\.resetConnection\(this\.serverUrl, \{ clearSessionContext: true \}\);/);
|
||||||
|
assert.match(authService, /for \(let attempt = 0; attempt < 2; attempt \+= 1\) \{[\s\S]*?challengeResp = await this\.ws\.request\('AuthChallenge'/);
|
||||||
|
assert.match(authService, /attempt === 0 && error\.code === 'ALREADY_AUTHED'/);
|
||||||
|
assert.match(authService, /this\.resetConnection\(this\.serverUrl, \{ clearSessionContext: true \}\);[\s\S]*?continue;/);
|
||||||
|
});
|
||||||
|
|
||||||
// Проверяем выполнение настоящей функции с изолированными зависимостями:
|
// Проверяем выполнение настоящей функции с изолированными зависимостями:
|
||||||
// ошибка HEADER не должна прерывать завершение регистрации.
|
// ошибка HEADER не должна прерывать завершение регистрации.
|
||||||
async function simulateCompletion({ headerFails = false } = {}) {
|
async function simulateCompletion({ headerFails = false } = {}) {
|
||||||
@@ -36,6 +45,7 @@ async function simulateCompletion({ headerFails = false } = {}) {
|
|||||||
};
|
};
|
||||||
const authService = {
|
const authService = {
|
||||||
async reconnect() {},
|
async reconnect() {},
|
||||||
|
resetConnection() {},
|
||||||
async createSessionForExistingUser() {
|
async createSessionForExistingUser() {
|
||||||
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session', sessionMaterial: {} };
|
return { login: 'AlexSmith@shine', storagePwd: 'stored', sessionId: 'test-session', sessionMaterial: {} };
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user