fix: задача устройству одноразовая и своя на каждую попытку — иначе ответ можно повторить
This commit is contained in:
@@ -215,3 +215,10 @@ h3 { font-size: 14px; margin: 12px 0 4px; }
|
||||
}
|
||||
|
||||
.login-note { margin: 16px 0 0; font-size: 12px; color: #78716c; line-height: 1.5; }
|
||||
|
||||
.login-card .login-face {
|
||||
margin-top: 10px;
|
||||
background: #fff;
|
||||
color: #1c1917;
|
||||
border: 1px solid #d6d3d1;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { faceLoginPossible, loginByFace } from '../lib/passkey';
|
||||
|
||||
/**
|
||||
* Форма входа по корпоративной почте и рабочему паролю.
|
||||
@@ -12,6 +13,13 @@ export function Login({ onDone }: { onDone: () => void }) {
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [faceReady, setFaceReady] = useState(false);
|
||||
|
||||
// кнопка входа по лицу показывается только там, где он вообще возможен:
|
||||
// по имени с доверенным сертификатом либо на localhost
|
||||
useEffect(() => {
|
||||
faceLoginPossible().then(setFaceReady).catch(() => setFaceReady(false));
|
||||
}, []);
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
@@ -72,6 +80,21 @@ export function Login({ onDone }: { onDone: () => void }) {
|
||||
|
||||
{error && <p className="login-error">{error}</p>}
|
||||
|
||||
{faceReady && (
|
||||
<button
|
||||
type="button"
|
||||
className="login-face"
|
||||
onClick={async () => {
|
||||
setError(null);
|
||||
const reason = await loginByFace();
|
||||
if (reason) setError(reason);
|
||||
else onDone();
|
||||
}}
|
||||
>
|
||||
Войти по лицу
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button type="submit" disabled={busy || !login || !password}>
|
||||
{busy ? 'Проверяем...' : 'Войти'}
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Вход по лицу на стороне браузера: заведение ключа и вход им.
|
||||
*
|
||||
* Работает только на защищённом соединении — либо по имени с доверенным
|
||||
* сертификатом, либо на localhost. Пока панель открывают по числовому адресу,
|
||||
* браузер такие ключи заводить не даст, и кнопка не показывается.
|
||||
*/
|
||||
|
||||
const toBytes = (base64url: string): Uint8Array<ArrayBuffer> => {
|
||||
const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));
|
||||
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
|
||||
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const toBase64Url = (buffer: ArrayBufferLike): string => {
|
||||
const binary = String.fromCharCode(...new Uint8Array(buffer as ArrayBuffer));
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
};
|
||||
|
||||
/** Умеет ли это устройство вход по лицу или отпечатку. */
|
||||
export async function faceLoginPossible(): Promise<boolean> {
|
||||
if (!window.PublicKeyCredential || !window.isSecureContext) return false;
|
||||
try {
|
||||
return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Заводит ключ на этом устройстве. Человек уже вошёл паролем. */
|
||||
export async function enrollFace(label: string): Promise<void> {
|
||||
const start = await fetch('/api/passkey/register/start', { method: 'POST' });
|
||||
if (!start.ok) throw new Error('панель не выдала задачу для устройства');
|
||||
const { challenge, rpId, login } = await start.json();
|
||||
|
||||
const credential = await navigator.credentials.create({
|
||||
publicKey: {
|
||||
challenge: toBytes(challenge),
|
||||
rp: { id: rpId ?? undefined, name: 'Панель акционера' },
|
||||
user: { id: toBytes(btoa(login).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')), name: login, displayName: login },
|
||||
pubKeyCredParams: [{ type: 'public-key', alg: -7 }],
|
||||
authenticatorSelection: {
|
||||
authenticatorAttachment: 'platform',
|
||||
userVerification: 'required', // именно лицо или отпечаток, не просто касание
|
||||
residentKey: 'preferred',
|
||||
},
|
||||
// подтверждение подлинности устройства не запрашиваем: во внутренней сети
|
||||
// это лишняя зависимость от внешних списков (решение из AUTH-OPTIONS)
|
||||
attestation: 'none',
|
||||
timeout: 60000,
|
||||
},
|
||||
}) as PublicKeyCredential | null;
|
||||
if (!credential) throw new Error('устройство не завело ключ');
|
||||
|
||||
const answer = credential.response as AuthenticatorAttestationResponse;
|
||||
const finish = await fetch('/api/passkey/register/finish', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
attestationObject: toBase64Url(answer.attestationObject),
|
||||
clientDataJSON: toBase64Url(answer.clientDataJSON),
|
||||
label,
|
||||
}),
|
||||
});
|
||||
if (!finish.ok) {
|
||||
const reason = await finish.json().catch(() => null);
|
||||
throw new Error(reason?.error ?? 'панель не приняла ключ');
|
||||
}
|
||||
}
|
||||
|
||||
/** Вход по лицу. Возвращает текст отказа либо null, если вошли. */
|
||||
export async function loginByFace(): Promise<string | null> {
|
||||
const start = await fetch('/api/passkey/login/start', { method: 'POST' });
|
||||
if (!start.ok) return 'панель не выдала задачу для устройства';
|
||||
const { challenge, rpId, handle } = await start.json();
|
||||
|
||||
let credential: PublicKeyCredential | null;
|
||||
try {
|
||||
credential = await navigator.credentials.get({
|
||||
publicKey: {
|
||||
challenge: toBytes(challenge),
|
||||
rpId: rpId ?? undefined,
|
||||
userVerification: 'required',
|
||||
timeout: 60000,
|
||||
},
|
||||
}) as PublicKeyCredential | null;
|
||||
} catch {
|
||||
// человек закрыл окно устройства или не подтвердил лицо
|
||||
return null;
|
||||
}
|
||||
if (!credential) return 'устройство не ответило';
|
||||
|
||||
const answer = credential.response as AuthenticatorAssertionResponse;
|
||||
const finish = await fetch('/api/passkey/login/finish', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
handle,
|
||||
credentialId: credential.id,
|
||||
authenticatorData: toBase64Url(answer.authenticatorData),
|
||||
clientDataJSON: toBase64Url(answer.clientDataJSON),
|
||||
signature: toBase64Url(answer.signature),
|
||||
}),
|
||||
});
|
||||
if (finish.ok) return null;
|
||||
const reason = await finish.json().catch(() => null);
|
||||
return reason?.error ?? 'Войти не получилось';
|
||||
}
|
||||
@@ -1793,3 +1793,11 @@ button {
|
||||
}
|
||||
|
||||
.login-note { margin: 16px 0 0; font-size: 12px; color: #78716c; line-height: 1.5; }
|
||||
|
||||
/* Вход по лицу — второй способ на том же экране. */
|
||||
.login-card .login-face {
|
||||
margin-top: 10px;
|
||||
background: #fff;
|
||||
color: #1c1917;
|
||||
border: 1px solid #d6d3d1;
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/types.ts","./src/admin/adminapp.tsx","./src/admin/sparkline.tsx","./src/admin/api.ts","./src/admin/blocks.tsx","./src/admin/main.tsx","./src/components/login.tsx","./src/components/periodfilter.tsx","./src/components/russiamap.tsx","./src/components/tooltip.tsx","./src/components/charts.tsx","./src/components/ui.tsx","./src/lib/aggregate.ts","./src/lib/checkdataset.ts","./src/lib/format.ts","./src/lib/session.ts","./src/sections/cash.tsx","./src/sections/datastatus.tsx","./src/sections/deposits.tsx","./src/sections/finance.tsx","./src/sections/people.tsx","./src/sections/taxes.tsx"],"version":"5.9.3"}
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/types.ts","./src/admin/adminapp.tsx","./src/admin/sparkline.tsx","./src/admin/api.ts","./src/admin/blocks.tsx","./src/admin/main.tsx","./src/components/login.tsx","./src/components/periodfilter.tsx","./src/components/russiamap.tsx","./src/components/tooltip.tsx","./src/components/charts.tsx","./src/components/ui.tsx","./src/lib/aggregate.ts","./src/lib/checkdataset.ts","./src/lib/format.ts","./src/lib/passkey.ts","./src/lib/session.ts","./src/sections/cash.tsx","./src/sections/datastatus.tsx","./src/sections/deposits.tsx","./src/sections/finance.tsx","./src/sections/people.tsx","./src/sections/taxes.tsx"],"version":"5.9.3"}
|
||||
+15
-4
@@ -167,6 +167,7 @@ export function installAuth(app, auth, options = {}) {
|
||||
return;
|
||||
}
|
||||
const expected = challenges.get(`create:${session.login}`)?.value;
|
||||
challenges.delete(`create:${session.login}`);
|
||||
try {
|
||||
const result = readRegistration({
|
||||
attestationObject: Buffer.from(String(request.body?.attestationObject ?? ''), 'base64url'),
|
||||
@@ -176,7 +177,6 @@ export function installAuth(app, auth, options = {}) {
|
||||
origin,
|
||||
});
|
||||
auth.addPasskey({ ...result, login: session.login, label: String(request.body?.label ?? '') || null });
|
||||
challenges.delete(`create:${session.login}`);
|
||||
response.json({ ok: true });
|
||||
} catch (error) {
|
||||
response.status(400).json({ error: error.message });
|
||||
@@ -184,13 +184,24 @@ export function installAuth(app, auth, options = {}) {
|
||||
});
|
||||
|
||||
app.post('/api/passkey/login/start', (request, response) => {
|
||||
// Своя задача на каждую попытку: одна общая затиралась бы при двух входах
|
||||
// подряд, а ответ устройства на неё можно было бы повторить.
|
||||
const handle = newChallenge();
|
||||
const challenge = newChallenge();
|
||||
remember('get', challenge);
|
||||
response.json({ challenge, rpId });
|
||||
remember(`get:${handle}`, challenge);
|
||||
response.json({ challenge, rpId, handle });
|
||||
});
|
||||
|
||||
app.post('/api/passkey/login/finish', async (request, response) => {
|
||||
const expected = challenges.get('get')?.value;
|
||||
// Задача одноразовая: забираем и сразу выбрасываем, даже если проверка
|
||||
// не пройдёт. Иначе перехваченный ответ устройства годился бы повторно.
|
||||
const handle = `get:${String(request.body?.handle ?? '')}`;
|
||||
const expected = challenges.get(handle)?.value;
|
||||
challenges.delete(handle);
|
||||
if (!expected) {
|
||||
response.status(400).json({ error: 'задача устарела, попробуйте ещё раз' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await auth.loginByPasskey({
|
||||
credentialId: String(request.body?.credentialId ?? ''),
|
||||
|
||||
@@ -157,3 +157,35 @@ test('без настройки вход не поднимается, а кор
|
||||
assert.equal(createAuthFromEnv({}), null, 'по умолчанию панель работает как прежде');
|
||||
assert.throws(() => createAuthFromEnv({ AUTH_ENABLED: '1', AUTH_KEY: 'коротко' }), /AUTH_KEY/);
|
||||
});
|
||||
|
||||
test('задача для устройства одноразовая: повтор ответа не проходит', async () => {
|
||||
// перехваченный ответ устройства не должен пускать второй раз
|
||||
const panel = await startPanel();
|
||||
const first = await fetch(`${panel.base}/api/passkey/login/start`, { method: 'POST' });
|
||||
const { handle, challenge } = await first.json();
|
||||
assert.ok(handle, 'на каждую попытку выдаётся своя задача');
|
||||
assert.ok(challenge);
|
||||
|
||||
const answer = { handle, credentialId: 'нет-такого', authenticatorData: '', clientDataJSON: '', signature: '' };
|
||||
const attempt = (body) => fetch(`${panel.base}/api/passkey/login/finish`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const once = await attempt(answer);
|
||||
assert.notEqual(once.status, 200);
|
||||
const twice = await attempt(answer);
|
||||
assert.equal(twice.status, 400);
|
||||
assert.match((await twice.json()).error, /устарела/i, 'задача сгорела после первой же попытки');
|
||||
panel.close();
|
||||
});
|
||||
|
||||
test('две попытки входа по лицу подряд получают разные задачи', async () => {
|
||||
const panel = await startPanel();
|
||||
const one = await (await fetch(`${panel.base}/api/passkey/login/start`, { method: 'POST' })).json();
|
||||
const two = await (await fetch(`${panel.base}/api/passkey/login/start`, { method: 'POST' })).json();
|
||||
assert.notEqual(one.handle, two.handle, 'вторая попытка не затирает первую');
|
||||
assert.notEqual(one.challenge, two.challenge);
|
||||
panel.close();
|
||||
});
|
||||
|
||||
+5
-3
@@ -129,9 +129,11 @@ export function readAssertion({
|
||||
if (!verifySignature({ jwk, authData, clientDataJson, signature })) {
|
||||
throw new Error('подпись устройства не сходится');
|
||||
}
|
||||
// Счётчик подписей растёт с каждым входом. Если он не вырос, ключ, возможно,
|
||||
// скопировали - устройства так не делают.
|
||||
if (parsed.signCount !== 0 && parsed.signCount <= lastSignCount) {
|
||||
// Счётчик подписей растёт с каждым входом: если он не вырос, ключ, возможно,
|
||||
// скопировали. Часть устройств счётчик не ведёт вовсе и всегда шлёт ноль -
|
||||
// тогда от повтора защищает одноразовая задача, и только она.
|
||||
const deviceCountsSignatures = parsed.signCount !== 0 || lastSignCount !== 0;
|
||||
if (deviceCountsSignatures && parsed.signCount <= lastSignCount) {
|
||||
throw new Error('счётчик устройства не вырос - ключ мог быть скопирован');
|
||||
}
|
||||
return { signCount: parsed.signCount };
|
||||
|
||||
@@ -181,3 +181,36 @@ test('простое касание без подтверждения лично
|
||||
expectedChallenge: challenge, rpId: RP_ID, origin: ORIGIN,
|
||||
}), /именно вы/i);
|
||||
});
|
||||
|
||||
test('устройство без счётчика подписей: ноль против нуля - пускаем', () => {
|
||||
// часть устройств счётчик не ведёт вовсе и всегда шлёт ноль; от повтора
|
||||
// тогда защищает одноразовая задача, а не счётчик
|
||||
const device = newDevice();
|
||||
const challenge = newChallenge();
|
||||
const authData = makeAuthData({ rpId: RP_ID, signCount: 0 });
|
||||
const clientDataJson = clientData('webauthn.get', challenge);
|
||||
const signature = crypto.sign('sha256',
|
||||
Buffer.concat([authData, crypto.createHash('sha256').update(clientDataJson).digest()]),
|
||||
{ key: device.pair.privateKey, dsaEncoding: 'der' });
|
||||
|
||||
const result = readAssertion({
|
||||
authData, clientDataJson, signature, jwk: device.jwk,
|
||||
expectedChallenge: challenge, rpId: RP_ID, origin: ORIGIN, lastSignCount: 0,
|
||||
});
|
||||
assert.equal(result.signCount, 0);
|
||||
});
|
||||
|
||||
test('устройство считало подписи, а теперь прислало ноль - это подмена', () => {
|
||||
const device = newDevice();
|
||||
const challenge = newChallenge();
|
||||
const authData = makeAuthData({ rpId: RP_ID, signCount: 0 });
|
||||
const clientDataJson = clientData('webauthn.get', challenge);
|
||||
const signature = crypto.sign('sha256',
|
||||
Buffer.concat([authData, crypto.createHash('sha256').update(clientDataJson).digest()]),
|
||||
{ key: device.pair.privateKey, dsaEncoding: 'der' });
|
||||
|
||||
assert.throws(() => readAssertion({
|
||||
authData, clientDataJson, signature, jwk: device.jwk,
|
||||
expectedChallenge: challenge, rpId: RP_ID, origin: ORIGIN, lastSignCount: 9,
|
||||
}), /скопирован/i);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user