fix: задача устройству одноразовая и своя на каждую попытку — иначе ответ можно повторить
This commit is contained in:
@@ -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 ?? 'Войти не получилось';
|
||||
}
|
||||
Reference in New Issue
Block a user