fix: задача устройству одноразовая и своя на каждую попытку — иначе ответ можно повторить

This commit is contained in:
anor
2026-08-16 05:05:50 +10:00
parent 620919e5ff
commit 0e38cb4b7e
9 changed files with 235 additions and 9 deletions
+7
View File
@@ -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;
}
+24 -1
View File
@@ -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>
+110
View File
@@ -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 ?? 'Войти не получилось';
}
+8
View File
@@ -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;
}