diff --git a/web/src/features/system-settings/auth/__tests__/passkey-settings.test.tsx b/web/src/features/system-settings/auth/__tests__/passkey-settings.test.tsx new file mode 100644 index 0000000000..473f2b141a --- /dev/null +++ b/web/src/features/system-settings/auth/__tests__/passkey-settings.test.tsx @@ -0,0 +1,302 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +// @vitest-environment-options {"url":"https://console.example.com:8443"} + +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { createInstance, type i18n } from 'i18next' +import { useState } from 'react' +import { I18nextProvider } from 'react-i18next' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import zh from '@/i18n/locales/zh.json' +import { api } from '@/lib/api' + +import { SettingsPageProvider } from '../../components/settings-page-context' +import { PasskeySection } from '../passkey-section' + +const defaults = { + 'passkey.enabled': true, + 'passkey.rp_display_name': 'Example', + 'passkey.rp_id': '', + 'passkey.origins': 'https://example.com,https://api.example.com', + 'passkey.allow_insecure_origin': false, + 'passkey.user_verification': 'preferred' as const, + 'passkey.attachment_preference': '' as const, +} + +let testI18n: i18n + +function Fixture(props: { rpId?: string; origins?: string }) { + const [container, setContainer] = useState(null) + const [client] = useState( + () => + new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + ) + return ( + + +
+ + + + + + ) +} + +beforeEach(async () => { + testI18n = createInstance() + await testI18n.init({ + lng: 'en', + fallbackLng: 'en', + resources: { en: { translation: {} }, zh }, + interpolation: { escapeValue: false }, + }) + localStorage.clear() + vi.spyOn(api, 'get').mockResolvedValue({ + data: { success: true, data: { passkey_rp_id: 'old.example.com' } }, + }) +}) + +describe('Passkey website guidance', () => { + it('marks a blank website field in yellow, explains it on request and restores focus when dismissed', async () => { + const put = vi.spyOn(api, 'put') + const user = userEvent.setup() + render() + const input = screen.getByRole('textbox', { + name: 'Passkey website domain', + }) + expect(input).toHaveValue('') + expect(input).toHaveClass('border-amber-500') + expect(input).toHaveAccessibleDescription( + 'Set the website where users will use their Passkeys.' + ) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect( + screen.queryByText(/Passkeys only work on the website/) + ).not.toBeInTheDocument() + const help = screen.getByRole('button', { name: 'Why set this?' }) + help.focus() + await user.keyboard('{Enter}') + const dialog = screen.getByRole('dialog', { + name: 'Why set a website domain?', + }) + expect(dialog).toHaveAccessibleDescription( + 'Passkeys only work on the website they were created for. This helps prevent other websites from misusing them.' + ) + expect( + await within(dialog).findByText( + 'The system currently uses: old.example.com' + ) + ).toBeVisible() + expect( + within(dialog).getByText( + `For this website, you can enter: ${window.location.hostname}` + ) + ).toBeVisible() + await user.keyboard('{Escape}') + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + ) + expect(help).toHaveFocus() + expect(put).not.toHaveBeenCalled() + }) + + it('fills the domain from the dialog, keeps existing websites and waits for Save Changes', async () => { + const put = vi.spyOn(api, 'put').mockImplementation(async () => { + vi.mocked(api.get).mockResolvedValue({ + data: { + success: true, + data: { passkey_rp_id: window.location.hostname }, + }, + }) + return { data: { success: true } } + }) + const user = userEvent.setup() + render() + await user.click(screen.getByRole('button', { name: 'Why set this?' })) + await user.click( + screen.getByRole('button', { name: 'Fill in this website' }) + ) + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + ) + const input = screen.getByRole('textbox', { + name: 'Passkey website domain', + }) + expect(input).toHaveValue(window.location.hostname) + expect(input).not.toHaveClass('border-amber-500') + expect( + screen.getByRole('textbox', { name: 'Allowed Passkey websites' }) + ).toHaveValue('https://example.com\nhttps://api.example.com') + expect(put).not.toHaveBeenCalled() + await user.click(screen.getByRole('button', { name: 'Save Changes' })) + await waitFor(() => + expect(put).toHaveBeenCalledWith('/api/option/', { + key: 'passkey.rp_id', + value: window.location.hostname, + }) + ) + expect(put).toHaveBeenCalledTimes(1) + await user.click(screen.getByRole('button', { name: 'Why set this?' })) + expect( + await screen.findByText( + `The system currently uses: ${window.location.hostname}` + ) + ).toBeVisible() + }) + + it('explains the effect on existing Passkeys and fills an empty website list including the port', async () => { + const user = userEvent.setup() + render() + await user.click(screen.getByRole('button', { name: 'Why set this?' })) + expect( + screen.getByText( + 'If users already have Passkeys, changing this domain may require them to sign in another way and set up their Passkeys again.' + ) + ).toBeVisible() + await user.click( + screen.getByRole('button', { name: 'Fill in this website' }) + ) + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + ) + expect( + screen.getByRole('textbox', { name: 'Allowed Passkey websites' }) + ).toHaveValue(window.location.origin) + }) + + it.each([ + 'unrelated.example.com', + 'ample.com', + 'https://console.example.com', + ])( + 'marks mismatched domain %s in yellow and clears the warning when corrected', + async (domain) => { + const user = userEvent.setup() + render() + const input = screen.getByRole('textbox', { + name: 'Passkey website domain', + }) + expect(input).not.toHaveClass('border-amber-500') + await user.clear(input) + await user.type(input, domain) + expect(input).toHaveClass( + 'border-amber-500', + 'focus-visible:border-amber-500' + ) + expect(input).toHaveAccessibleDescription( + 'This domain does not match the current website. Passkeys may not work here.' + ) + await user.clear(input) + await user.type(input, window.location.hostname) + expect(input).not.toHaveClass('border-amber-500') + expect( + screen.queryByText( + 'This domain does not match the current website. Passkeys may not work here.' + ) + ).not.toBeInTheDocument() + } + ) + + it('keeps a matching parent domain unmarked and explains a missing website beside the website list', async () => { + render() + expect( + screen.getByRole('textbox', { name: 'Passkey website domain' }) + ).not.toHaveClass('border-amber-500') + const websites = screen.getByRole('textbox', { + name: 'Allowed Passkey websites', + }) + expect(websites).toHaveAccessibleDescription( + `This list does not include the current website. Add ${window.location.origin} if users sign in here.` + ) + const user = userEvent.setup() + await user.type(websites, `\n${window.location.origin}`) + expect(websites).toHaveAccessibleDescription( + 'Enter one website address per line, such as https://example.com. Do not include a page path.' + ) + }) + + it('disables filling while saving and enables it after the save finishes', async () => { + let finishSave!: (value: { data: { success: boolean } }) => void + vi.spyOn(api, 'put').mockImplementation( + () => + new Promise((resolve) => { + finishSave = resolve + }) + ) + const user = userEvent.setup() + render() + await user.type( + screen.getByRole('textbox', { name: 'Passkey website domain' }), + window.location.hostname + ) + await user.click(screen.getByRole('button', { name: 'Save Changes' })) + await user.click(screen.getByRole('button', { name: 'Why set this?' })) + const fill = screen.getByRole('button', { name: 'Fill in this website' }) + expect(fill).toBeDisabled() + finishSave({ data: { success: true } }) + await waitFor(() => expect(fill).toBeEnabled()) + }) + + it('uses everyday Chinese in the field and explanation dialog', async () => { + await testI18n.changeLanguage('zh') + const user = userEvent.setup() + render() + expect( + screen.getByRole('textbox', { name: '通行密钥使用的网站域名' }) + ).toHaveClass('border-amber-500') + await user.click(screen.getByRole('button', { name: '为什么需要设置?' })) + const dialog = screen.getByRole('dialog', { + name: '为什么要填写网站域名?', + }) + expect(dialog).not.toHaveTextContent(/RP ID|Origins?|依赖方/) + expect( + within(dialog).getByRole('button', { name: '填入当前网站' }) + ).toBeVisible() + }) + + it('keeps manual setup available when the current system domain cannot be read', async () => { + vi.mocked(api.get).mockRejectedValue(new Error('Offline')) + const user = userEvent.setup() + render() + await user.click(screen.getByRole('button', { name: 'Why set this?' })) + expect( + await screen.findByText( + 'The current setting could not be loaded. You can still enter the website domain yourself.' + ) + ).toBeVisible() + expect( + screen.getByRole('button', { name: 'Fill in this website' }) + ).toBeEnabled() + }) +}) diff --git a/web/src/features/system-settings/auth/passkey-section.tsx b/web/src/features/system-settings/auth/passkey-section.tsx index c2296196b2..a2ae68cb92 100644 --- a/web/src/features/system-settings/auth/passkey-section.tsx +++ b/web/src/features/system-settings/auth/passkey-section.tsx @@ -17,12 +17,15 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { zodResolver } from '@hookform/resolvers/zod' -import { useEffect, useMemo, useRef } from 'react' -import { useForm } from 'react-hook-form' +import { useQuery } from '@tanstack/react-query' +import { useEffect, useMemo, useRef, useState } from 'react' +import { useForm, useWatch } from 'react-hook-form' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' import * as z from 'zod' +import { Dialog } from '@/components/dialog' +import { Button } from '@/components/ui/button' import { Form, FormControl, @@ -43,6 +46,8 @@ import { } from '@/components/ui/select' import { Switch } from '@/components/ui/switch' import { Textarea } from '@/components/ui/textarea' +import { statusQueryOptions } from '@/lib/status-query' +import { cn } from '@/lib/utils' import { SettingsForm, @@ -139,6 +144,7 @@ interface PasskeySectionProps { export function PasskeySection(props: PasskeySectionProps) { const { t } = useTranslation() const updateOption = useUpdateOption() + const [domainHelpOpen, setDomainHelpOpen] = useState(false) const formDefaults = useMemo( () => buildFormDefaults(props.defaultValues), @@ -150,6 +156,33 @@ export function PasskeySection(props: PasskeySectionProps) { defaultValues: formDefaults, }) + const { data: status, isError: statusError } = useQuery({ + ...statusQueryOptions, + refetchOnMount: 'always', + }) + const rpId = useWatch({ control: form.control, name: 'passkey.rp_id' }) + const origins = useWatch({ control: form.control, name: 'passkey.origins' }) + const currentHostname = window.location.hostname + const currentOrigin = window.location.origin + const canUseCurrentSite = + (window.location.protocol === 'https:' || + (window.location.protocol === 'http:' && + currentHostname === 'localhost')) && + currentHostname !== '' && + !currentHostname.includes(':') && + !/^\d+\.\d+\.\d+\.\d+$/.test(currentHostname) + const serverRPID = + typeof status?.passkey_rp_id === 'string' ? status.passkey_rp_id.trim() : '' + const previewRPID = (rpId.trim() || serverRPID).toLowerCase() + const domainMismatch = + previewRPID !== '' && + currentHostname !== previewRPID && + !currentHostname.endsWith(`.${previewRPID}`) + const hasDomainWarning = rpId.trim() === '' || domainMismatch + const currentOriginMissing = + origins.trim() !== '' && + !origins.split(/[,\n]/).some((origin) => origin.trim() === currentOrigin) + const baselineRef = useRef(props.defaultValues) const baselineSerializedRef = useRef( JSON.stringify(props.defaultValues) @@ -222,7 +255,7 @@ export function PasskeySection(props: PasskeySectionProps) { name='passkey.rp_display_name' render={({ field }) => ( - {t('Relying Party Display Name')} + {t('Passkey display name')} ( - {t('Relying Party ID')} + {t('Passkey website domain')} field.onChange(event.target.value)} @@ -259,11 +296,128 @@ export function PasskeySection(props: PasskeySectionProps) { ref={field.ref} /> - - {t( - 'The effective domain for Passkey registration. Must match the current domain or be its parent domain.' - )} - +
+ + {rpId.trim() === '' && + t('Set the website where users will use their Passkeys.')} + {rpId.trim() !== '' && + domainMismatch && + t( + 'This domain does not match the current website. Passkeys may not work here.' + )} + {!hasDomainWarning && + t('Enter the website domain, such as example.com.')} + + + {t('Why set this?')} + + } + footer={ + <> + + + + } + > +

+ {t( + 'If left blank, the system may use a different website address and Passkey sign-in can fail here.' + )} +

+
+

+ {t('Current site: {{origin}}', { + origin: currentOrigin, + })} +

+

+ {t('For this website, you can enter: {{domain}}', { + domain: currentHostname, + })} +

+ {serverRPID && !statusError && ( +

+ {t('The system currently uses: {{domain}}', { + domain: serverRPID, + })} +

+ )} +
+ {statusError && ( +

+ {t( + 'The current setting could not be loaded. You can still enter the website domain yourself.' + )} +

+ )} +

+ {t( + 'Enter only the domain, such as example.com, without https://, a port or a page path. If you use both example.com and api.example.com, you can enter example.com.' + )} +

+

+ {t( + 'If users already have Passkeys, changing this domain may require them to sign in another way and set up their Passkeys again.' + )} +

+ {!canUseCurrentSite && ( +

+ {t( + 'Use an HTTPS domain (or localhost for development) to configure Passkey.' + )} +

+ )} +

+ {t( + 'The button fills in this website and keeps any existing website addresses. Save changes on the settings page to apply.' + )} +

+
+
)} @@ -383,11 +537,11 @@ export function PasskeySection(props: PasskeySectionProps) { name='passkey.origins' render={({ field }) => ( - {t('Allowed Origins')} + {t('Allowed Passkey websites')}