feat(auth): вход по ключу доступа (passkeys, WebAuthn)
Фаза 7, AGENT.md 7.1: регистрация ключа в настройках безопасности с обязательным step-up, вход по ключу без пароля (в т.ч. без ввода почты — обнаруживаемый ключ), несколько ключей на аккаунт, отзыв и переименование, события безопасности и аудит. Сервер: github.com/go-webauthn/webauthn (BSD-3-Clause), RP ID и Origin берутся из конфига домена; если домен — IP-адрес (стенд без домена), passkeys честно выключены (auth.passkey_unsupported). Церемонии живут в памяти процесса 5 минут и одноразовые: повторная отправка challenge отклоняется. Миграция 00018 пересобирает неиспользуемую таблицу webauthn_credentials под полную запись credential в JSON. Новые ручки входа ограничены по IP (10/мин). Клиент: тонкая обёртка над navigator.credentials без тяжёлых SDK, раздел «Ключи доступа» в настройках безопасности и кнопка «Войти по ключу» на экране входа; понятные сообщения для браузеров без поддержки WebAuthn и при отмене диалога. Тесты: Go — регистрация/вход с эмулятором аутентификатора (реальная проверка подписи P-256), отказ при чужом challenge, одноразовость церемонии, обязательный step-up при управлении ключами, запрет входа забаненному, ограничение allowCredentials при входе с почтой, лимит и валидация имени; web — 12 vitest с моком navigator.credentials; Playwright — живой сценарий с виртуальным аутентификатором Chromium.
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { request } from './client';
|
||||
import {
|
||||
createPasskey,
|
||||
getPasskeyAssertion,
|
||||
type AssertionCredentialJSON,
|
||||
type PublicKeyCredentialCreationOptionsJSON,
|
||||
type PublicKeyCredentialRequestOptionsJSON,
|
||||
type RegistrationCredentialJSON,
|
||||
} from '@/lib/webauthn';
|
||||
import type { User } from './types';
|
||||
|
||||
/** Ключ доступа в списке настроек (AGENT.md 7.1, Фаза 7). */
|
||||
export interface Passkey {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
last_used_at?: string;
|
||||
sign_count: number;
|
||||
}
|
||||
|
||||
export const passkeysQueryKey = ['auth', 'passkeys'] as const;
|
||||
|
||||
interface BeginResponse<T> {
|
||||
options: { publicKey: T };
|
||||
ceremony: string;
|
||||
expires_in_sec: number;
|
||||
}
|
||||
|
||||
export async function fetchPasskeys(signal?: AbortSignal): Promise<Passkey[]> {
|
||||
const payload = await request<{ passkeys: Passkey[] }>(
|
||||
'/auth/passkeys',
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
return payload.passkeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрация ключа: сервер требует step-up, поэтому пароль (и код 2FA)
|
||||
* передаются дважды — на begin и на finish.
|
||||
*/
|
||||
export async function registerPasskey(
|
||||
name: string,
|
||||
stepUpPassword: string,
|
||||
stepUpTOTP?: string,
|
||||
): Promise<Passkey> {
|
||||
const stepUpBody: { password: string; totp_code?: string } = { password: stepUpPassword };
|
||||
if (stepUpTOTP !== undefined && stepUpTOTP !== '') {
|
||||
stepUpBody.totp_code = stepUpTOTP;
|
||||
}
|
||||
const begin = await request<BeginResponse<PublicKeyCredentialCreationOptionsJSON>>(
|
||||
'/auth/passkeys/register/begin',
|
||||
{ method: 'POST', body: stepUpBody },
|
||||
);
|
||||
const credential: RegistrationCredentialJSON = await createPasskey(begin.options.publicKey);
|
||||
const finish = await request<{ passkey: Passkey }>('/auth/passkeys/register/finish', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
ceremony: begin.ceremony,
|
||||
name,
|
||||
credential,
|
||||
step_up_password: stepUpPassword,
|
||||
step_up_totp: stepUpTOTP ?? '',
|
||||
},
|
||||
});
|
||||
return finish.passkey;
|
||||
}
|
||||
|
||||
/** Вход по ключу: email необязателен — браузер покажет выбор аккаунта. */
|
||||
export async function loginWithPasskey(email?: string): Promise<{ user: User }> {
|
||||
const body = email !== undefined && email !== '' ? { email } : {};
|
||||
const begin = await request<BeginResponse<PublicKeyCredentialRequestOptionsJSON>>(
|
||||
'/auth/passkeys/login/begin',
|
||||
{ method: 'POST', body },
|
||||
);
|
||||
const credential: AssertionCredentialJSON = await getPasskeyAssertion(begin.options.publicKey);
|
||||
return request<{ user: User }>('/auth/passkeys/login/finish', {
|
||||
method: 'POST',
|
||||
body: { ceremony: begin.ceremony, credential },
|
||||
});
|
||||
}
|
||||
|
||||
export function renamePasskey(passkeyId: string, name: string): Promise<{ ok: true }> {
|
||||
return request<{ ok: true }>(`/auth/passkeys/${passkeyId}`, { method: 'PATCH', body: { name } });
|
||||
}
|
||||
|
||||
/** Отзыв ключа: требует свежего step-up (клиент вызывает его заранее). */
|
||||
export function deletePasskey(passkeyId: string): Promise<{ ok: true }> {
|
||||
return request<{ ok: true }>(`/auth/passkeys/${passkeyId}`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -75,6 +75,12 @@
|
||||
"auth.email_taken": "This email is already registered.",
|
||||
"auth.weak_password": "The password is too weak. Use at least 8 characters.",
|
||||
"auth.too_many_attempts": "Too many attempts. Try again later.",
|
||||
"auth.passkey_unsupported": "Passkeys are unavailable: a domain and HTTPS are required.",
|
||||
"auth.passkey_challenge_invalid": "The request expired. Retry passkey sign-in.",
|
||||
"auth.passkey_verification_failed": "The key did not match or the signature failed. Try another key.",
|
||||
"auth.passkey_unknown": "This key is not registered on the account.",
|
||||
"auth.passkey_name_invalid": "Enter a key name (up to 64 characters).",
|
||||
"auth.passkey_limit": "The account reached its passkey limit.",
|
||||
"permissions.denied": "You do not have permission for this action.",
|
||||
"instance.admin_required": "This action is available to the instance admin only.",
|
||||
"guild.not_found": "Server not found.",
|
||||
@@ -166,7 +172,11 @@
|
||||
"forgot": "Forgot your password? Ask the instance admin.",
|
||||
"instanceStatus": "Instance status",
|
||||
"registrationDisabled": "Registration on this instance is disabled by the admin.",
|
||||
"totpRequired": "Enter the 2FA or recovery code — sign-in needs it."
|
||||
"totpRequired": "Enter the 2FA or recovery code — sign-in needs it.",
|
||||
"passkeySubmit": "Sign in with a passkey",
|
||||
"passkeyPending": "Waiting for the key…",
|
||||
"passkeyCancelled": "Passkey sign-in was cancelled or timed out. Try again.",
|
||||
"passkeyUnsupported": "This browser does not support passkeys. Sign in with your password."
|
||||
},
|
||||
"register": {
|
||||
"title": "Create account",
|
||||
@@ -793,7 +803,32 @@
|
||||
"twoFactorEnabledDone": "2FA is enabled. Save your recovery codes.",
|
||||
"recoveryTitle": "Recovery codes",
|
||||
"recoveryHint": "Every code works once. They are shown only once.",
|
||||
"recoveryCopyAll": "Copy all codes"
|
||||
"recoveryCopyAll": "Copy all codes",
|
||||
"passkeysTitle": "Passkeys",
|
||||
"passkeysDescription": "Passwordless sign-in with a fingerprint, Face ID or a hardware key. You can add several keys and revoke any of them.",
|
||||
"passkeysEmpty": "No keys yet. Add the first one to sign in without a password.",
|
||||
"passkeysAddTitle": "Add a key",
|
||||
"passkeysAddHint": "Pick a name (for example “Laptop”) and confirm your identity: managing keys requires a fresh check.",
|
||||
"passkeysName": "Key name",
|
||||
"passkeysNamePlaceholder": "Laptop, phone, YubiKey…",
|
||||
"passkeysAdd": "Create key",
|
||||
"passkeysAdded": "Key “{{name}}” was added.",
|
||||
"passkeysRemoved": "The key was revoked.",
|
||||
"passkeysRenamed": "The key name was updated.",
|
||||
"passkeysRemove": "Revoke",
|
||||
"passkeysRename": "Rename",
|
||||
"passkeysRenamePrompt": "New key name",
|
||||
"passkeysRemoveConfirm": "Revoke the key “{{name}}”? Sign-in with it will stop working.",
|
||||
"passkeysRemoveConfirmButton": "Revoke key",
|
||||
"passkeysCreated": "Added {{date}}",
|
||||
"passkeysNeverUsed": "never used",
|
||||
"passkeysLastUsed": "last sign-in {{date}}",
|
||||
"passkeysUnsupported": "This browser does not support passkeys (WebAuthn). A modern browser and a secure connection (HTTPS) are required.",
|
||||
"passkeysCancelled": "Key creation was cancelled or timed out.",
|
||||
"passkeysTimeout": "The authenticator did not respond in time. Try again.",
|
||||
"passkeysAlreadyRegistered": "This key is already registered on the account.",
|
||||
"passkeysFailed": "Could not create the key. Try another authenticator.",
|
||||
"passkeysNameRequired": "Enter a key name (up to 64 characters)."
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Appearance",
|
||||
|
||||
@@ -75,6 +75,12 @@
|
||||
"auth.email_taken": "Такая почта уже зарегистрирована.",
|
||||
"auth.weak_password": "Пароль слишком простой. Используйте не менее 8 символов.",
|
||||
"auth.too_many_attempts": "Слишком много попыток. Попробуйте позже.",
|
||||
"auth.passkey_unsupported": "Ключи доступа недоступны: нужен домен и HTTPS.",
|
||||
"auth.passkey_challenge_invalid": "Запрос устарел. Повторите вход по ключу.",
|
||||
"auth.passkey_verification_failed": "Ключ не подошёл или подпись не совпала. Попробуйте другой ключ.",
|
||||
"auth.passkey_unknown": "Этот ключ не зарегистрирован на аккаунте.",
|
||||
"auth.passkey_name_invalid": "Укажите название ключа (до 64 символов).",
|
||||
"auth.passkey_limit": "Достигнут предел числа ключей на аккаунте.",
|
||||
"permissions.denied": "Недостаточно прав для этого действия.",
|
||||
"instance.admin_required": "Действие доступно только администратору инстанса.",
|
||||
"guild.not_found": "Сервер не найден.",
|
||||
@@ -166,7 +172,11 @@
|
||||
"forgot": "Пароль забыт? Обратитесь к администратору инстанса.",
|
||||
"instanceStatus": "Состояние инстанса",
|
||||
"registrationDisabled": "Регистрация на этом инстансе выключена администратором.",
|
||||
"totpRequired": "Введите код 2FA или резервный код — без него вход невозможен."
|
||||
"totpRequired": "Введите код 2FA или резервный код — без него вход невозможен.",
|
||||
"passkeySubmit": "Войти по ключу доступа",
|
||||
"passkeyPending": "Ждём ключ…",
|
||||
"passkeyCancelled": "Вход по ключу отменён или истёк таймаут. Попробуйте снова.",
|
||||
"passkeyUnsupported": "Браузер не поддерживает ключи доступа. Войдите с паролем."
|
||||
},
|
||||
"register": {
|
||||
"title": "Регистрация",
|
||||
@@ -793,7 +803,32 @@
|
||||
"twoFactorEnabledDone": "2FA включена. Сохраните коды восстановления.",
|
||||
"recoveryTitle": "Коды восстановления",
|
||||
"recoveryHint": "Каждый код одноразовый. Они показываются только один раз.",
|
||||
"recoveryCopyAll": "Скопировать все коды"
|
||||
"recoveryCopyAll": "Скопировать все коды",
|
||||
"passkeysTitle": "Ключи доступа (passkeys)",
|
||||
"passkeysDescription": "Вход без пароля по отпечатку, Face ID или аппаратному ключу. Можно добавить несколько ключей и отозвать любой из них.",
|
||||
"passkeysEmpty": "Ключей пока нет. Добавьте первый — и сможете входить без пароля.",
|
||||
"passkeysAddTitle": "Добавить ключ",
|
||||
"passkeysAddHint": "Придумайте имя (например, «Ноутбук») и подтвердите личность: управление ключами требует свежей проверки.",
|
||||
"passkeysName": "Название ключа",
|
||||
"passkeysNamePlaceholder": "Ноутбук, телефон, YubiKey…",
|
||||
"passkeysAdd": "Создать ключ",
|
||||
"passkeysAdded": "Ключ «{{name}}» добавлен.",
|
||||
"passkeysRemoved": "Ключ отозван.",
|
||||
"passkeysRenamed": "Название ключа обновлено.",
|
||||
"passkeysRemove": "Отозвать",
|
||||
"passkeysRename": "Переименовать",
|
||||
"passkeysRenamePrompt": "Новое название ключа",
|
||||
"passkeysRemoveConfirm": "Отозвать ключ «{{name}}»? Вход по нему станет невозможен.",
|
||||
"passkeysRemoveConfirmButton": "Отозвать ключ",
|
||||
"passkeysCreated": "Добавлен {{date}}",
|
||||
"passkeysNeverUsed": "ещё не использовался",
|
||||
"passkeysLastUsed": "последний вход {{date}}",
|
||||
"passkeysUnsupported": "Этот браузер не поддерживает ключи доступа (WebAuthn). Нужен современный браузер и защищённое соединение (HTTPS).",
|
||||
"passkeysCancelled": "Создание ключа отменено или истёк таймаут.",
|
||||
"passkeysTimeout": "Аутентификатор не ответил вовремя. Попробуйте снова.",
|
||||
"passkeysAlreadyRegistered": "Этот ключ уже зарегистрирован на аккаунте.",
|
||||
"passkeysFailed": "Не удалось создать ключ. Попробуйте другой аутентификатор.",
|
||||
"passkeysNameRequired": "Укажите название ключа (до 64 символов)."
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Внешний вид",
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Обёртка над `navigator.credentials` для passkeys (WebAuthn).
|
||||
*
|
||||
* Тяжёлые SDK не используем (AGENT.md 5.2): сервер отдаёт обычный JSON
|
||||
* WebAuthn, здесь он переводится в ArrayBuffer и обратно. Все ошибки
|
||||
* приводятся к `WebAuthnClientError` с понятным кодом, чтобы UI показал
|
||||
* человеческое сообщение, а не `NotAllowedError`.
|
||||
*/
|
||||
|
||||
/** Коды ошибок клиента: используются в i18n (`errors.auth.passkey_*`). */
|
||||
export type WebAuthnClientErrorCode =
|
||||
'unsupported' | 'cancelled' | 'timeout' | 'invalid_state' | 'not_allowed' | 'failed';
|
||||
|
||||
export class WebAuthnClientError extends Error {
|
||||
readonly code: WebAuthnClientErrorCode;
|
||||
|
||||
constructor(code: WebAuthnClientErrorCode, message?: string) {
|
||||
super(message ?? code);
|
||||
this.name = 'WebAuthnClientError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/** Публичные опции, как их отдаёт сервер (base64url-строки). */
|
||||
export interface PublicKeyCredentialCreationOptionsJSON {
|
||||
challenge: string;
|
||||
rp: { id?: string; name: string };
|
||||
user: { id: string; name: string; displayName: string };
|
||||
pubKeyCredParams: PublicKeyCredentialParameters[];
|
||||
timeout?: number;
|
||||
attestation?: AttestationConveyancePreference;
|
||||
authenticatorSelection?: AuthenticatorSelectionCriteria;
|
||||
excludeCredentials?: { id: string; type: 'public-key'; transports?: string[] }[];
|
||||
extensions?: AuthenticationExtensionsClientInputs;
|
||||
}
|
||||
|
||||
export interface PublicKeyCredentialRequestOptionsJSON {
|
||||
challenge: string;
|
||||
timeout?: number;
|
||||
rpId?: string;
|
||||
allowCredentials?: { id: string; type: 'public-key'; transports?: string[] }[];
|
||||
userVerification?: UserVerificationRequirement;
|
||||
}
|
||||
|
||||
/** Ответ аутентификатора в JSON-виде — ровно то, что ждёт сервер. */
|
||||
export interface RegistrationCredentialJSON {
|
||||
id: string;
|
||||
rawId: string;
|
||||
type: 'public-key';
|
||||
response: {
|
||||
clientDataJSON: string;
|
||||
attestationObject: string;
|
||||
transports?: string[];
|
||||
};
|
||||
clientExtensionResults: Record<string, unknown>;
|
||||
authenticatorAttachment?: string;
|
||||
}
|
||||
|
||||
export interface AssertionCredentialJSON {
|
||||
id: string;
|
||||
rawId: string;
|
||||
type: 'public-key';
|
||||
response: {
|
||||
clientDataJSON: string;
|
||||
authenticatorData: string;
|
||||
signature: string;
|
||||
userHandle?: string;
|
||||
};
|
||||
clientExtensionResults: Record<string, unknown>;
|
||||
authenticatorAttachment?: string;
|
||||
}
|
||||
|
||||
/** base64url → ArrayBuffer (браузер не умеет декодировать сам). */
|
||||
export function base64URLToBuffer(value: string): ArrayBuffer {
|
||||
const padded = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const pad = padded.length % 4 === 0 ? '' : '='.repeat(4 - (padded.length % 4));
|
||||
const binary = atob(padded + pad);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/** ArrayBuffer → base64url без паддинга. */
|
||||
export function bufferToBase64URL(buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (const byte of bytes) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Поддерживает ли браузер passkeys. Проверяем и наличие API, и защищённый
|
||||
* контекст: без HTTPS (кроме localhost) WebAuthn недоступен.
|
||||
*/
|
||||
export function isPasskeySupported(): boolean {
|
||||
if (typeof window === 'undefined' || typeof navigator === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
if (typeof window.PublicKeyCredential === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
typeof navigator.credentials?.create === 'function' &&
|
||||
typeof navigator.credentials?.get === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/** Приводит произвольную ошибку браузера к понятному коду. */
|
||||
export function mapCredentialsError(error: unknown): WebAuthnClientError {
|
||||
if (error instanceof WebAuthnClientError) {
|
||||
return error;
|
||||
}
|
||||
const name = error instanceof Error ? error.name : '';
|
||||
switch (name) {
|
||||
case 'NotAllowedError':
|
||||
// Пользователь отменил диалог или истёк таймаут: браузер не различает их.
|
||||
return new WebAuthnClientError('cancelled', name);
|
||||
case 'AbortError':
|
||||
return new WebAuthnClientError('cancelled', name);
|
||||
case 'TimeoutError':
|
||||
return new WebAuthnClientError('timeout', name);
|
||||
case 'InvalidStateError':
|
||||
// Ключ уже зарегистрирован на этом устройстве.
|
||||
return new WebAuthnClientError('invalid_state', name);
|
||||
case 'NotSupportedError':
|
||||
case 'SecurityError':
|
||||
return new WebAuthnClientError('unsupported', name);
|
||||
default:
|
||||
return new WebAuthnClientError('failed', name);
|
||||
}
|
||||
}
|
||||
|
||||
/** Дескриптор ключа в формате браузера: id — ArrayBuffer. */
|
||||
function toDescriptors(
|
||||
descriptors: { id: string; type: 'public-key'; transports?: string[] }[] | undefined,
|
||||
): PublicKeyCredentialDescriptor[] | undefined {
|
||||
if (descriptors === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return descriptors.map((descriptor) => ({
|
||||
id: base64URLToBuffer(descriptor.id),
|
||||
type: descriptor.type,
|
||||
...(descriptor.transports === undefined
|
||||
? {}
|
||||
: { transports: descriptor.transports as AuthenticatorTransport[] }),
|
||||
}));
|
||||
}
|
||||
|
||||
function requireSupport(): void {
|
||||
if (!isPasskeySupported()) {
|
||||
throw new WebAuthnClientError('unsupported');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт ключ доступа и возвращает ответ для сервера.
|
||||
* `options` — поле `publicKey` из ответа `/auth/passkeys/register/begin`.
|
||||
*/
|
||||
export async function createPasskey(
|
||||
options: PublicKeyCredentialCreationOptionsJSON,
|
||||
): Promise<RegistrationCredentialJSON> {
|
||||
requireSupport();
|
||||
const excludeCredentials = toDescriptors(options.excludeCredentials);
|
||||
// Поля собираем поимённо: JSON-вариант содержит строковые id, и простой
|
||||
// спред перенёс бы их в браузерный тип, где нужен ArrayBuffer.
|
||||
const publicKey: PublicKeyCredentialCreationOptions = {
|
||||
challenge: base64URLToBuffer(options.challenge),
|
||||
rp: options.rp,
|
||||
user: { ...options.user, id: base64URLToBuffer(options.user.id) },
|
||||
pubKeyCredParams: options.pubKeyCredParams,
|
||||
...(options.timeout === undefined ? {} : { timeout: options.timeout }),
|
||||
...(options.attestation === undefined ? {} : { attestation: options.attestation }),
|
||||
...(options.authenticatorSelection === undefined
|
||||
? {}
|
||||
: { authenticatorSelection: options.authenticatorSelection }),
|
||||
...(options.extensions === undefined ? {} : { extensions: options.extensions }),
|
||||
...(excludeCredentials === undefined ? {} : { excludeCredentials }),
|
||||
};
|
||||
try {
|
||||
const credential = (await navigator.credentials.create({
|
||||
publicKey,
|
||||
})) as PublicKeyCredential | null;
|
||||
if (credential === null) {
|
||||
throw new WebAuthnClientError('cancelled');
|
||||
}
|
||||
const response = credential.response as AuthenticatorAttestationResponse;
|
||||
const result: RegistrationCredentialJSON = {
|
||||
id: credential.id,
|
||||
rawId: bufferToBase64URL(credential.rawId),
|
||||
type: 'public-key',
|
||||
response: {
|
||||
clientDataJSON: bufferToBase64URL(response.clientDataJSON),
|
||||
attestationObject: bufferToBase64URL(response.attestationObject),
|
||||
},
|
||||
clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,
|
||||
};
|
||||
if (typeof response.getTransports === 'function') {
|
||||
const transports = response.getTransports();
|
||||
if (transports.length > 0) {
|
||||
result.response.transports = transports;
|
||||
}
|
||||
}
|
||||
if (credential.authenticatorAttachment !== null) {
|
||||
result.authenticatorAttachment = credential.authenticatorAttachment;
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw mapCredentialsError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Подписывает challenge существующим ключом.
|
||||
* `options` — поле `publicKey` из ответа `/auth/passkeys/login/begin`.
|
||||
*/
|
||||
export async function getPasskeyAssertion(
|
||||
options: PublicKeyCredentialRequestOptionsJSON,
|
||||
): Promise<AssertionCredentialJSON> {
|
||||
requireSupport();
|
||||
const allowCredentials = toDescriptors(options.allowCredentials);
|
||||
const publicKey: PublicKeyCredentialRequestOptions = {
|
||||
challenge: base64URLToBuffer(options.challenge),
|
||||
...(options.timeout === undefined ? {} : { timeout: options.timeout }),
|
||||
...(options.rpId === undefined ? {} : { rpId: options.rpId }),
|
||||
...(options.userVerification === undefined
|
||||
? {}
|
||||
: { userVerification: options.userVerification }),
|
||||
...(allowCredentials === undefined ? {} : { allowCredentials }),
|
||||
};
|
||||
try {
|
||||
const credential = (await navigator.credentials.get({
|
||||
publicKey,
|
||||
})) as PublicKeyCredential | null;
|
||||
if (credential === null) {
|
||||
throw new WebAuthnClientError('cancelled');
|
||||
}
|
||||
const response = credential.response as AuthenticatorAssertionResponse;
|
||||
const result: AssertionCredentialJSON = {
|
||||
id: credential.id,
|
||||
rawId: bufferToBase64URL(credential.rawId),
|
||||
type: 'public-key',
|
||||
response: {
|
||||
clientDataJSON: bufferToBase64URL(response.clientDataJSON),
|
||||
authenticatorData: bufferToBase64URL(response.authenticatorData),
|
||||
signature: bufferToBase64URL(response.signature),
|
||||
},
|
||||
clientExtensionResults: credential.getClientExtensionResults() as Record<string, unknown>,
|
||||
};
|
||||
if (response.userHandle !== null) {
|
||||
result.response.userHandle = bufferToBase64URL(response.userHandle);
|
||||
}
|
||||
if (credential.authenticatorAttachment !== null) {
|
||||
result.authenticatorAttachment = credential.authenticatorAttachment;
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw mapCredentialsError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link, useLocation, useNavigate, useSearchParams } from 'react-router';
|
||||
|
||||
import { login } from '@/api/auth';
|
||||
import { fetchMeta, metaQueryKey } from '@/api/meta';
|
||||
import { loginWithPasskey } from '@/api/passkeys';
|
||||
import { ErrorNotice } from '@/components/ui/ErrorNotice';
|
||||
import { Field } from '@/components/ui/Field';
|
||||
import { Button, Card } from '@/components/ui/primitives';
|
||||
import { getQueryClient } from '@/lib/queryClient';
|
||||
import { useInstance } from '@/lib/hooks';
|
||||
import { errorCode } from '@/lib/format';
|
||||
import { isPasskeySupported, WebAuthnClientError } from '@/lib/webauthn';
|
||||
import { useGatewayStore } from '@/stores/gateway';
|
||||
|
||||
interface LocationState {
|
||||
@@ -20,6 +23,8 @@ interface LocationState {
|
||||
* Форма входа. Поле кода 2FA показывается всегда: сервер принимает и код из
|
||||
* приложения (6 цифр), и резервный код вида `a8eh-pshp-t8st`, а при попытке
|
||||
* входа без кода отвечает `auth.2fa_required` — тогда подсказываем про код.
|
||||
*
|
||||
* Дополнительно (Фаза 7): вход по ключу доступа (passkeys).
|
||||
*/
|
||||
export default function LoginPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -39,19 +44,30 @@ export default function LoginPage() {
|
||||
const stateFrom = (location.state as LocationState | null)?.from ?? null;
|
||||
const from = next !== null && next.startsWith('/') ? next : (stateFrom ?? '/app');
|
||||
|
||||
// Признак доступности passkeys берём из меты инстанса: на IP-адресе (стенд
|
||||
// без домена) WebAuthn невозможен, и кнопку показывать нельзя.
|
||||
const meta = useQuery({
|
||||
queryKey: metaQueryKey,
|
||||
queryFn: ({ signal }) => fetchMeta(signal),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const passkeySupported = isPasskeySupported() && meta.data?.features.passkeys_enabled === true;
|
||||
|
||||
const finishLogin = async (): Promise<void> => {
|
||||
// Профиль перечитываем заново: cookie уже выставлена сервером. Признак
|
||||
// отозванной сессии снимаем — иначе AuthGuard увёл бы обратно на /login.
|
||||
useGatewayStore.getState().reset();
|
||||
await getQueryClient().invalidateQueries();
|
||||
void navigate(from === '/login' ? '/app' : from, { replace: true });
|
||||
};
|
||||
|
||||
const submit = useMutation({
|
||||
mutationFn: () => {
|
||||
// Пустое поле — вход без кода: сервер сам скажет, нужен ли он.
|
||||
const code = totpCode.trim();
|
||||
return login(code === '' ? { email, password } : { email, password, totp_code: code });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
// Профиль перечитываем заново: cookie уже выставлена сервером. Признак
|
||||
// отозванной сессии снимаем — иначе AuthGuard увёл бы обратно на /login.
|
||||
useGatewayStore.getState().reset();
|
||||
await getQueryClient().invalidateQueries();
|
||||
void navigate(from === '/login' ? '/app' : from, { replace: true });
|
||||
},
|
||||
onSuccess: finishLogin,
|
||||
onError: (error: unknown) => {
|
||||
if (errorCode(error) === 'auth.2fa_required') {
|
||||
// Логин, пароль и уже введённый код остаются в форме.
|
||||
@@ -60,6 +76,11 @@ export default function LoginPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const passkey = useMutation({
|
||||
mutationFn: () => loginWithPasskey(email.trim() === '' ? undefined : email.trim()),
|
||||
onSuccess: finishLogin,
|
||||
});
|
||||
|
||||
const onSubmit = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
setNeedsTotp(false);
|
||||
@@ -68,6 +89,14 @@ export default function LoginPage() {
|
||||
|
||||
const registrationEnabled = instance.data?.registration_enabled === true;
|
||||
|
||||
// Ошибка клиента WebAuthn важнее серверной: она объясняет, что делать.
|
||||
const passkeyErrorKey =
|
||||
passkey.error instanceof WebAuthnClientError && passkey.error.code === 'cancelled'
|
||||
? 'auth.login.passkeyCancelled'
|
||||
: passkey.error instanceof WebAuthnClientError && passkey.error.code === 'unsupported'
|
||||
? 'auth.login.passkeyUnsupported'
|
||||
: null;
|
||||
|
||||
return (
|
||||
<main className="gl-page mx-auto flex min-h-full w-full max-w-md flex-col justify-center gap-5 px-4 py-10">
|
||||
<header>
|
||||
@@ -120,6 +149,29 @@ export default function LoginPage() {
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{passkeySupported ? (
|
||||
<div className="mt-4 flex flex-col gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
data-testid="passkey-login"
|
||||
disabled={passkey.isPending}
|
||||
onClick={() => {
|
||||
setNeedsTotp(false);
|
||||
passkey.mutate();
|
||||
}}
|
||||
>
|
||||
{t(passkey.isPending ? 'auth.login.passkeyPending' : 'auth.login.passkeySubmit')}
|
||||
</Button>
|
||||
{passkeyErrorKey === null ? (
|
||||
<ErrorNotice error={passkey.error} />
|
||||
) : (
|
||||
<p className="text-sm text-danger" role="alert" data-testid="passkey-error">
|
||||
{t(passkeyErrorKey)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<p className="mt-4 text-sm text-fg-muted">
|
||||
{t('auth.login.noAccount')}{' '}
|
||||
{registrationEnabled ? (
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { stepUp } from '@/api/auth';
|
||||
import {
|
||||
deletePasskey,
|
||||
fetchPasskeys,
|
||||
passkeysQueryKey,
|
||||
registerPasskey,
|
||||
renamePasskey,
|
||||
type Passkey,
|
||||
} from '@/api/passkeys';
|
||||
import { ErrorNotice } from '@/components/ui/ErrorNotice';
|
||||
import { Field } from '@/components/ui/Field';
|
||||
import { Button, Card } from '@/components/ui/primitives';
|
||||
import { errorCode } from '@/lib/format';
|
||||
import { isPasskeySupported, WebAuthnClientError } from '@/lib/webauthn';
|
||||
|
||||
/** Ключ i18n для ошибки клиента WebAuthn (AGENT.md 7.1, Фаза 7). */
|
||||
function passkeyErrorKey(error: unknown): string | null {
|
||||
if (error instanceof WebAuthnClientError) {
|
||||
switch (error.code) {
|
||||
case 'unsupported':
|
||||
return 'settings.security.passkeysUnsupported';
|
||||
case 'cancelled':
|
||||
return 'settings.security.passkeysCancelled';
|
||||
case 'timeout':
|
||||
return 'settings.security.passkeysTimeout';
|
||||
case 'invalid_state':
|
||||
return 'settings.security.passkeysAlreadyRegistered';
|
||||
default:
|
||||
return 'settings.security.passkeysFailed';
|
||||
}
|
||||
}
|
||||
if (errorCode(error) === 'auth.passkey_name_invalid') {
|
||||
return 'settings.security.passkeysNameRequired';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ключи доступа (passkeys): список, добавление, переименование и отзыв.
|
||||
* Управление ключами — чувствительное действие, поэтому сервер требует
|
||||
* свежий step-up: пароль (и код 2FA) спрашиваем прямо в разделе.
|
||||
*
|
||||
* Если браузер не поддерживает WebAuthn, раздел честно сообщает об этом и не
|
||||
* показывает форму добавления (AGENT.md 7.1: понятные ошибки для браузеров
|
||||
* без поддержки).
|
||||
*/
|
||||
export function PasskeysSection({ twoFactorEnabled }: { twoFactorEnabled: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const supported = isPasskeySupported();
|
||||
const [name, setName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [removeTarget, setRemoveTarget] = useState<Passkey | null>(null);
|
||||
|
||||
const passkeys = useQuery({
|
||||
queryKey: passkeysQueryKey,
|
||||
queryFn: ({ signal }) => fetchPasskeys(signal),
|
||||
enabled: supported,
|
||||
});
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
void queryClient.invalidateQueries({ queryKey: passkeysQueryKey });
|
||||
}, [queryClient]);
|
||||
|
||||
const clearCredentials = useCallback(() => {
|
||||
setPassword('');
|
||||
setCode('');
|
||||
}, []);
|
||||
|
||||
const add = useMutation({
|
||||
mutationFn: () => registerPasskey(name.trim(), password, twoFactorEnabled ? code : undefined),
|
||||
onSuccess: (passkey) => {
|
||||
setNotice(t('settings.security.passkeysAdded', { name: passkey.name }));
|
||||
setName('');
|
||||
clearCredentials();
|
||||
refresh();
|
||||
},
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (removeTarget === null) {
|
||||
return;
|
||||
}
|
||||
// Свежий step-up, затем отзыв ключа.
|
||||
await stepUp(password, twoFactorEnabled ? code : undefined);
|
||||
await deletePasskey(removeTarget.id);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setNotice(t('settings.security.passkeysRemoved'));
|
||||
setRemoveTarget(null);
|
||||
clearCredentials();
|
||||
refresh();
|
||||
},
|
||||
});
|
||||
|
||||
const rename = useMutation({
|
||||
mutationFn: (payload: { passkey: Passkey; next: string }) =>
|
||||
renamePasskey(payload.passkey.id, payload.next),
|
||||
onSuccess: () => {
|
||||
setNotice(t('settings.security.passkeysRenamed'));
|
||||
refresh();
|
||||
},
|
||||
});
|
||||
|
||||
const errorKey = passkeyErrorKey(add.error ?? remove.error ?? rename.error);
|
||||
const canSubmit = supported && name.trim() !== '' && password !== '' && !add.isPending;
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<h2 className="text-lg font-semibold">{t('settings.security.passkeysTitle')}</h2>
|
||||
<p className="mt-1 text-sm text-fg-muted">{t('settings.security.passkeysDescription')}</p>
|
||||
|
||||
{!supported ? (
|
||||
<p className="mt-3 text-sm text-warning" role="status" data-testid="passkeys-unsupported">
|
||||
{t('settings.security.passkeysUnsupported')}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="mt-4 flex flex-col gap-2" data-testid="passkeys-list">
|
||||
{(passkeys.data ?? []).map((passkey) => (
|
||||
<li
|
||||
key={passkey.id}
|
||||
className="flex flex-wrap items-center justify-between gap-2 rounded-[var(--radius-md)] border border-border/60 bg-surface-2/60 p-3"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium" data-testid="passkey-name">
|
||||
{passkey.name}
|
||||
</p>
|
||||
<p className="text-xs text-fg-muted">
|
||||
{t('settings.security.passkeysCreated', {
|
||||
date: new Date(passkey.created_at).toLocaleDateString(),
|
||||
})}
|
||||
{passkey.last_used_at === undefined
|
||||
? ` · ${t('settings.security.passkeysNeverUsed')}`
|
||||
: ` · ${t('settings.security.passkeysLastUsed', {
|
||||
date: new Date(passkey.last_used_at).toLocaleString(),
|
||||
})}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
const next = window.prompt(
|
||||
t('settings.security.passkeysRenamePrompt'),
|
||||
passkey.name,
|
||||
);
|
||||
if (next !== null && next.trim() !== '') {
|
||||
rename.mutate({ passkey, next: next.trim() });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('settings.security.passkeysRename')}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => setRemoveTarget(passkey)}>
|
||||
{t('settings.security.passkeysRemove')}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
{passkeys.data !== undefined && passkeys.data.length === 0 ? (
|
||||
<li className="text-sm text-fg-muted" data-testid="passkeys-empty">
|
||||
{t('settings.security.passkeysEmpty')}
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
|
||||
<form
|
||||
className="mt-4 flex flex-col gap-3 rounded-[var(--radius-md)] border border-border/60 p-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
setNotice(null);
|
||||
if (canSubmit) {
|
||||
add.mutate();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<h3 className="text-sm font-semibold">{t('settings.security.passkeysAddTitle')}</h3>
|
||||
<p className="text-xs text-fg-muted">{t('settings.security.passkeysAddHint')}</p>
|
||||
<Field
|
||||
label={t('settings.security.passkeysName')}
|
||||
name="passkey_name"
|
||||
maxLength={64}
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder={t('settings.security.passkeysNamePlaceholder')}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label={t('settings.security.stepUpPassword')}
|
||||
type="password"
|
||||
name="passkey_step_up_password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
/>
|
||||
{twoFactorEnabled ? (
|
||||
<Field
|
||||
label={t('auth.login.totp')}
|
||||
hint={t('auth.login.totpHint')}
|
||||
name="passkey_step_up_totp"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={8}
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
/>
|
||||
) : null}
|
||||
{notice === null ? null : (
|
||||
<p className="text-sm text-success" role="status">
|
||||
{notice}
|
||||
</p>
|
||||
)}
|
||||
{errorKey === null ? (
|
||||
<ErrorNotice error={add.error ?? remove.error ?? rename.error} />
|
||||
) : (
|
||||
<p className="text-sm text-danger" role="alert" data-testid="passkeys-error">
|
||||
{t(errorKey)}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={!canSubmit}>
|
||||
{t(add.isPending ? 'common.saving' : 'settings.security.passkeysAdd')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{removeTarget === null ? null : (
|
||||
<div className="mt-3 rounded-[var(--radius-md)] border border-warning/50 bg-warning/10 p-3">
|
||||
<p className="text-sm">
|
||||
{t('settings.security.passkeysRemoveConfirm', { name: removeTarget.name })}
|
||||
</p>
|
||||
<div className="mt-2 flex justify-end gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setRemoveTarget(null);
|
||||
remove.reset();
|
||||
}}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={remove.isPending || password === ''}
|
||||
onClick={() => {
|
||||
setNotice(null);
|
||||
remove.mutate();
|
||||
}}
|
||||
>
|
||||
{t('settings.security.passkeysRemoveConfirmButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,14 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { currentUserQueryKey, fetchCurrentUser } from '@/api/users';
|
||||
import { PasskeysSection } from '@/pages/settings/PasskeysSection';
|
||||
import { PasswordSection } from '@/pages/settings/PasswordSection';
|
||||
import { SessionsSection } from '@/pages/settings/SessionsSection';
|
||||
import { TwoFactorSection } from '@/pages/settings/TwoFactorSection';
|
||||
|
||||
/**
|
||||
* Безопасность: смена пароля со step-up, список сессий с выходом на всех
|
||||
* устройствах и включение 2FA с показом секрета и кодов восстановления.
|
||||
* устройствах, включение 2FA и ключи доступа (passkeys, Фаза 7).
|
||||
*
|
||||
* Состояние 2FA берём из профиля (`totp_enabled`), обновляя запрос после
|
||||
* включения: от него зависит, требовать ли код при step-up.
|
||||
@@ -35,6 +36,7 @@ export default function SecuritySettingsPage() {
|
||||
void currentUser.refetch();
|
||||
}}
|
||||
/>
|
||||
<PasskeysSection twoFactorEnabled={twoFactorEnabled} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user