diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py index 5597ea2e..d231275b 100644 --- a/backend/app/api/two_factor.py +++ b/backend/app/api/two_factor.py @@ -67,7 +67,8 @@ def get_2fa_status(): @jwt_required() def initiate_2fa_setup(): """ - Initiate 2FA setup. Generates a new secret and returns QR code. + Initiate 2FA setup. Reuses the pending unconfirmed secret (or generates + one); JSON {"regenerate": true} forces a fresh secret. User must verify with a code to complete setup. """ current_user_id = get_jwt_identity() @@ -79,8 +80,11 @@ def initiate_2fa_setup(): if user.totp_enabled: return jsonify({'error': '2FA is already enabled'}), 400 + data = json_object(optional=True) + regenerate = data.get('regenerate') is True + setup = TwoFactorSetup(user) - setup_data = setup.initiate_setup() + setup_data = setup.initiate_setup(regenerate=regenerate) return jsonify({ 'message': '2FA setup initiated. Scan the QR code and enter a verification code.', diff --git a/backend/app/services/totp_service.py b/backend/app/services/totp_service.py index 28f9afbf..24a4f351 100644 --- a/backend/app/services/totp_service.py +++ b/backend/app/services/totp_service.py @@ -191,20 +191,32 @@ class TwoFactorSetup: def __init__(self, user): self.user = user - def initiate_setup(self): + def initiate_setup(self, regenerate=False): """ - Start 2FA setup by generating a new secret. + Start 2FA setup, reusing the pending unconfirmed secret if there is one. + + A new secret is minted only when none is pending or ``regenerate`` is + set, so repeated Enable clicks keep the secret the user already scanned. + A confirmed secret is never rotated here. Returns: dict: Setup data including secret and QR code """ from app import db - # Generate new secret (don't enable yet) - secret = TOTPService.generate_secret() - self.user.totp_secret = secret + # Serialize on the user row so concurrent /setup calls see one secret. + # (No-op on SQLite, where writes are already serialized.) + db.session.refresh(self.user, with_for_update=True) - # Don't enable until verified + if self.user.totp_enabled: + from app.exceptions import ConflictError + raise ConflictError('2FA is already enabled') + + secret = self.user.totp_secret + if regenerate or not secret: + secret = TOTPService.generate_secret() + self.user.totp_secret = secret + # Don't enable until verified; commit also releases the row lock. db.session.commit() # Generate QR code diff --git a/backend/tests/test_totp_service.py b/backend/tests/test_totp_service.py index ee248b04..f44f2c85 100644 --- a/backend/tests/test_totp_service.py +++ b/backend/tests/test_totp_service.py @@ -9,6 +9,8 @@ from werkzeug.security import generate_password_hash from app import db from app.models import User from app.services.totp_service import TOTPService, TwoFactorSetup +from app.exceptions import ConflictError +from factories import headers_for @pytest.fixture @@ -172,3 +174,69 @@ def test_regenerate_backup_codes_replaces_old_set(user): assert ok and len(new) == 10 assert not old_hashes & set(user.get_backup_codes()) assert setup.regenerate_backup_codes('abc') == (False, 'Invalid verification code') + + +def test_qr_code_is_built_from_the_provisioning_uri(secret, monkeypatch): + from app.services import totp_service + if not totp_service.HAS_QRCODE: + pytest.skip('qrcode not installed') + added = [] + real = totp_service.qrcode.QRCode + + class Spy(real): + def add_data(self, data, *a, **kw): + added.append(data) + return super().add_data(data, *a, **kw) + + monkeypatch.setattr(totp_service.qrcode, 'QRCode', Spy) + TOTPService.generate_qr_code_base64(secret, 'me@example.com') + assert added == [TOTPService.get_provisioning_uri(secret, 'me@example.com')] + parsed = urlparse(added[0]) + assert parsed.scheme == 'otpauth' and parsed.netloc == 'totp' + assert parse_qs(parsed.query) == {'secret': [secret], 'issuer': ['ServerKit']} + + +def test_second_initiate_reuses_pending_secret_and_confirm_works(user): + setup = TwoFactorSetup(user) + first = setup.initiate_setup() + second = TwoFactorSetup(user).initiate_setup() + assert second['secret'] == first['secret'] == user.totp_secret + assert second['uri'] == first['uri'] and second['issuer'] == 'ServerKit' + assert not user.totp_enabled + ok, _ = setup.confirm_setup(TOTPService.get_current_code(first['secret'])) + assert ok and user.totp_enabled + + +def test_regenerate_mints_new_secret_only_while_unconfirmed(user): + setup = TwoFactorSetup(user) + first = setup.initiate_setup()['secret'] + second = setup.initiate_setup(regenerate=True)['secret'] + assert second != first and user.totp_secret == second + setup.confirm_setup(TOTPService.get_current_code(second)) + with pytest.raises(ConflictError): + setup.initiate_setup(regenerate=True) + assert user.totp_secret == second + + +def test_setup_endpoint_reuses_secret_until_regenerate(client, user): + url = '/api/v1/auth/2fa/setup' + a = client.post(url, headers=headers_for(user)).get_json() + b = client.post(url, headers=headers_for(user)).get_json() + assert a['secret'] == b['secret'] and a['uri'] == b['uri'] + assert client.get('/api/v1/auth/2fa/status', headers=headers_for(user)).get_json()['enabled'] is False + c = client.post(url, json={'regenerate': True}, headers=headers_for(user)).get_json() + assert c['secret'] != a['secret'] + confirm = client.post(url + '/confirm', headers=headers_for(user), + json={'code': TOTPService.get_current_code(c['secret'])}) + assert confirm.status_code == 200 + + +def test_setup_endpoint_rejects_confirmed_user_without_rotating(client, user): + TwoFactorSetup(user).initiate_setup() + secret = user.totp_secret + TwoFactorSetup(user).confirm_setup(TOTPService.get_current_code(secret)) + for body in (None, {'regenerate': True}): + r = client.post('/api/v1/auth/2fa/setup', json=body, headers=headers_for(user)) + assert r.status_code == 400 + db.session.refresh(user) + assert user.totp_secret == secret and user.totp_enabled diff --git a/frontend/src/components/Modal.jsx b/frontend/src/components/Modal.jsx index 28516053..c962bb7a 100644 --- a/frontend/src/components/Modal.jsx +++ b/frontend/src/components/Modal.jsx @@ -1,5 +1,6 @@ import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'; import { cn } from '@/lib/utils'; +import { dismissGuards } from '@/components/ui/dismissGuards'; // Generic modal built on the Radix Dialog primitive. SCSS owns all geometry // (styles/components/_ui.scss → .sk-modal*). `size` picks a max-width on @@ -12,6 +13,9 @@ import { cn } from '@/lib/utils'; // to the bottom of the scrolling body, and a nested .modal-body adds no extra // padding or scroller. Two-column .form-row stacks in narrow modals. // +// closeOnDismiss={false}: overlay click and Escape no longer close the modal +// (for flows that would lose in-progress state); explicit buttons still do. +// // Form mode: pass `onSubmit` and the body AND footer // are wrapped in one
. This exists because a submit button must live // inside the form it submits — without it, every modal with a form had to @@ -27,6 +31,7 @@ export default function Modal({ onSubmit, className = '', size = 'md', + closeOnDismiss = true, }) { const body = ( <> @@ -42,7 +47,7 @@ export default function Modal({ return ( !v && onClose()}> - + {title && (
{title} diff --git a/frontend/src/components/settings/SecuritySettingsTab.jsx b/frontend/src/components/settings/SecuritySettingsTab.jsx index dc6c7874..92033443 100644 --- a/frontend/src/components/settings/SecuritySettingsTab.jsx +++ b/frontend/src/components/settings/SecuritySettingsTab.jsx @@ -1,10 +1,11 @@ -import { useState, useEffect, useId } from 'react'; +import { useState, useEffect, useId, useRef } from 'react'; import { useAuth } from '../../contexts/useAuth.js'; import api from '../../services/api'; import useSettingFocus from '../../hooks/useSettingFocus'; import TwoFactorPolicyCard from './TwoFactorPolicyCard'; import SSOProviderIcon from '../SSOProviderIcon'; import Modal from '../Modal'; +import { createSingleFlight } from '@/utils/singleFlight'; import ErrorState from '../ErrorState'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -155,6 +156,8 @@ const SecuritySettingsTab = () => { const [backupCodes, setBackupCodes] = useState([]); const [twoFAError, setTwoFAError] = useState(''); const [twoFALoadError, setTwoFALoadError] = useState(null); + const [confirmFailed, setConfirmFailed] = useState(false); + const initiateFlight = useRef(createSingleFlight()).current; useEffect(() => { load2FAStatus(); @@ -204,21 +207,25 @@ const SecuritySettingsTab = () => { } } - async function handleInitiate2FA() { - setTwoFAError(''); - setTwoFALoading(true); - try { - const data = await api.initiate2FASetup(); - setSetupData(data); - setShowSetupModal(true); - window.dispatchEvent(new CustomEvent('serverkit:walkthrough-signal', { - detail: { type: 'two-factor-setup-started' }, - })); - } catch (err) { - setTwoFAError(err.message); - } finally { - setTwoFALoading(false); - } + // The ref lock refuses a double-click before `twoFALoading` flushes. + function handleInitiate2FA() { + return initiateFlight(async () => { + setTwoFAError(''); + setConfirmFailed(false); + setTwoFALoading(true); + try { + const data = await api.initiate2FASetup(); + setSetupData(data); + setShowSetupModal(true); + window.dispatchEvent(new CustomEvent('serverkit:walkthrough-signal', { + detail: { type: 'two-factor-setup-started' }, + })); + } catch (err) { + setTwoFAError(err.message); + } finally { + setTwoFALoading(false); + } + }); } async function handleConfirm2FA() { @@ -229,6 +236,7 @@ const SecuritySettingsTab = () => { setTwoFALoading(true); setTwoFAError(''); + setConfirmFailed(false); try { const result = await api.confirm2FASetup(verificationCode); setBackupCodes(result.backup_codes); @@ -240,6 +248,7 @@ const SecuritySettingsTab = () => { detail: { type: 'two-factor-enabled' }, })); } catch (err) { + setConfirmFailed(true); setTwoFAError(err.message || t('auth.codeMismatch', "That code didn't match. Enter the current 6-digit code from your authenticator app.")); } finally { setTwoFALoading(false); @@ -455,7 +464,7 @@ Keep these codes in a safe place.`; {/* 2FA Setup Modal */} {showSetupModal && setupData && ( - setShowSetupModal(false)} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md"> + setShowSetupModal(false)} closeOnDismiss={false} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md">
1 @@ -494,6 +503,7 @@ Keep these codes in a safe place.`; autoFocus /> {twoFAError &&

{twoFAError}

} + {confirmFailed &&

{t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}

}
diff --git a/frontend/src/components/setup/SetupStepSecurity.jsx b/frontend/src/components/setup/SetupStepSecurity.jsx index 601da5db..9835df0e 100644 --- a/frontend/src/components/setup/SetupStepSecurity.jsx +++ b/frontend/src/components/setup/SetupStepSecurity.jsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { ShieldCheck, Download, AlertTriangle, Check, Loader } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -7,6 +7,7 @@ import CopyField from '../CopyField'; import { downloadBlob } from '@/utils/downloadBlob'; import { useTranslation } from 'react-i18next'; import InfoTip from '@/components/InfoTip'; +import { createSingleFlight } from '@/utils/singleFlight'; // Enrolment is a three-beat flow. Offer is the default so someone who just // wants a dashboard is one click from moving on — 2FA is offered here because @@ -28,6 +29,8 @@ const SetupStepSecurity = ({ onComplete }) => { const [savedCodes, setSavedCodes] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); + const [confirmFailed, setConfirmFailed] = useState(false); + const enableFlight = useRef(createSingleFlight()).current; // Stepping back to Capacity and forward again re-mounts this step, but the // enrolment already landed server-side — re-offering it would just 400. @@ -45,18 +48,22 @@ const SetupStepSecurity = ({ onComplete }) => { }; }, []); - async function handleEnable() { - setBusy(true); - setError(''); - try { - const data = await api.initiate2FASetup(); - setSetupData(data); - setStage(STAGE_ENROLL); - } catch (err) { - setError(err.message || 'Could not start two-factor setup.'); - } finally { - setBusy(false); - } + // The ref lock refuses a double-click before `busy` flushes. + function handleEnable() { + return enableFlight(async () => { + setBusy(true); + setError(''); + setConfirmFailed(false); + try { + const data = await api.initiate2FASetup(); + setSetupData(data); + setStage(STAGE_ENROLL); + } catch (err) { + setError(err.message || 'Could not start two-factor setup.'); + } finally { + setBusy(false); + } + }); } async function handleConfirm() { @@ -66,11 +73,13 @@ const SetupStepSecurity = ({ onComplete }) => { } setBusy(true); setError(''); + setConfirmFailed(false); try { const result = await api.confirm2FASetup(code); setBackupCodes(result.backup_codes || []); setStage(STAGE_CODES); } catch (err) { + setConfirmFailed(true); setError(err.message || 'That code did not match. Try the next one.'); } finally { setBusy(false); @@ -221,7 +230,10 @@ const SetupStepSecurity = ({ onComplete }) => { {error && (
-
{error}
+
+ {error} + {confirmFailed && <> {t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}} +
)} diff --git a/frontend/src/components/ui/dismissGuards.js b/frontend/src/components/ui/dismissGuards.js new file mode 100644 index 00000000..71e6f624 --- /dev/null +++ b/frontend/src/components/ui/dismissGuards.js @@ -0,0 +1,9 @@ +// Radix Dialog props that stop overlay click / Escape from closing a dialog. +// Explicit close buttons (Cancel, the header X) still work. +const block = (event) => event.preventDefault(); + +export function dismissGuards(closeOnDismiss = true) { + return closeOnDismiss + ? {} + : { onPointerDownOutside: block, onInteractOutside: block, onEscapeKeyDown: block }; +} diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json index 0b5df0ce..fefd1f07 100644 --- a/frontend/src/i18n/locales/ar.json +++ b/frontend/src/i18n/locales/ar.json @@ -5265,6 +5265,7 @@ "changePassword": "تغيير كلمة المرور", "changing": "جارٍ التغيير…", "codeFromAuthenticatorOrBackupCode": "رمز من المصادقة أو رمز النسخ الاحتياطي", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "تأكيد كلمة المرور الجديدة", "confirmNewPassword2": "تأكيد كلمة المرور الجديدة", "connectExternalIdentityProvidersToYour": "قم بتوصيل موفري الهوية الخارجيين بحسابك", diff --git a/frontend/src/i18n/locales/bn.json b/frontend/src/i18n/locales/bn.json index ff8d184d..1cd7be17 100644 --- a/frontend/src/i18n/locales/bn.json +++ b/frontend/src/i18n/locales/bn.json @@ -5265,6 +5265,7 @@ "changePassword": "পাসওয়ার্ড পরিবর্তন করুন", "changing": "পরিবর্তন করা হচ্ছে…", "codeFromAuthenticatorOrBackupCode": "প্রমাণীকরণকারী বা ব্যাকআপ কোড থেকে কোড", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "নতুন পাসওয়ার্ড নিশ্চিত করুন", "confirmNewPassword2": "নতুন পাসওয়ার্ড নিশ্চিত করুন", "connectExternalIdentityProvidersToYour": "আপনার অ্যাকাউন্টে বহিরাগত পরিচয় প্রদানকারীকে সংযুক্ত করুন", diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json index fd22a483..b70c40bc 100644 --- a/frontend/src/i18n/locales/de.json +++ b/frontend/src/i18n/locales/de.json @@ -5265,6 +5265,7 @@ "changePassword": "Passwort ändern", "changing": "Wird geändert…", "codeFromAuthenticatorOrBackupCode": "Code vom Authentifikator oder Backup-Code", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Bestätigen Sie das neue Passwort", "confirmNewPassword2": "Neues Passwort bestätigen", "connectExternalIdentityProvidersToYour": "Verbinden Sie externe Identitätsanbieter mit Ihrem Konto", diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 7d5e3e2b..4812f927 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -5500,6 +5500,7 @@ "changePassword": "Change password", "changing": "Changing…", "codeFromAuthenticatorOrBackupCode": "Code from authenticator or backup code", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirm new password", "confirmNewPassword2": "Confirm new password", "connectExternalIdentityProvidersToYour": "Connect external identity providers to your account", diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json index c0c120c6..4db43646 100644 --- a/frontend/src/i18n/locales/es.json +++ b/frontend/src/i18n/locales/es.json @@ -5266,6 +5266,7 @@ "changePassword": "Cambiar contraseña", "changing": "Cambiando…", "codeFromAuthenticatorOrBackupCode": "Código de la app de autenticación o código de recuperación", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirmar nueva contraseña", "confirmNewPassword2": "Confirma la nueva contraseña", "connectExternalIdentityProvidersToYour": "Conecta proveedores de identidad externos a tu cuenta", diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json index f52b4065..c64dbbd7 100644 --- a/frontend/src/i18n/locales/fr.json +++ b/frontend/src/i18n/locales/fr.json @@ -5265,6 +5265,7 @@ "changePassword": "Changer le mot de passe", "changing": "Modification…", "codeFromAuthenticatorOrBackupCode": "Code de l'authentificateur ou code de sauvegarde", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirmer le nouveau mot de passe", "confirmNewPassword2": "Confirmer le nouveau mot de passe", "connectExternalIdentityProvidersToYour": "Connectez des fournisseurs d'identité externes à votre compte", diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index b0257724..5671cbca 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -5265,6 +5265,7 @@ "changePassword": "Ubah Kata Sandi", "changing": "Mengubah…", "codeFromAuthenticatorOrBackupCode": "Kode dari pengautentikasi atau kode cadangan", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Konfirmasi Kata Sandi Baru", "confirmNewPassword2": "Konfirmasikan kata sandi baru", "connectExternalIdentityProvidersToYour": "Hubungkan penyedia identitas eksternal ke akun Anda", diff --git a/frontend/src/i18n/locales/it.json b/frontend/src/i18n/locales/it.json index 5f425bf8..9c30a8d0 100644 --- a/frontend/src/i18n/locales/it.json +++ b/frontend/src/i18n/locales/it.json @@ -5265,6 +5265,7 @@ "changePassword": "Cambiare la password", "changing": "Modifica…", "codeFromAuthenticatorOrBackupCode": "Codice dall'autenticatore o codice di backup", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Conferma nuova password", "confirmNewPassword2": "Conferma la nuova password", "connectExternalIdentityProvidersToYour": "Connetti i provider di identità esterni al tuo account", diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json index 732fb643..a8e119d1 100644 --- a/frontend/src/i18n/locales/ko.json +++ b/frontend/src/i18n/locales/ko.json @@ -5265,6 +5265,7 @@ "changePassword": "비밀번호 변경", "changing": "변경 중…", "codeFromAuthenticatorOrBackupCode": "인증자의 코드 또는 백업 코드", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "새 비밀번호 확인", "confirmNewPassword2": "새 비밀번호 확인", "connectExternalIdentityProvidersToYour": "외부 ID 공급자를 계정에 연결", diff --git a/frontend/src/i18n/locales/pl.json b/frontend/src/i18n/locales/pl.json index e5523fd9..9db6a6fd 100644 --- a/frontend/src/i18n/locales/pl.json +++ b/frontend/src/i18n/locales/pl.json @@ -5265,6 +5265,7 @@ "changePassword": "Zmień hasło", "changing": "Zmienianie…", "codeFromAuthenticatorOrBackupCode": "Kod z uwierzytelniacza lub kod zapasowy", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Potwierdź nowe hasło", "confirmNewPassword2": "Potwierdź nowe hasło", "connectExternalIdentityProvidersToYour": "Połącz zewnętrznych dostawców tożsamości ze swoim kontem", diff --git a/frontend/src/i18n/locales/pt.json b/frontend/src/i18n/locales/pt.json index eacf9acb..7dd30cdc 100644 --- a/frontend/src/i18n/locales/pt.json +++ b/frontend/src/i18n/locales/pt.json @@ -5265,6 +5265,7 @@ "changePassword": "Alterar senha", "changing": "Alterando…", "codeFromAuthenticatorOrBackupCode": "Código do autenticador ou código de backup", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirme a nova senha", "confirmNewPassword2": "Confirme a nova senha", "connectExternalIdentityProvidersToYour": "Conecte provedores de identidade externos à sua conta", diff --git a/frontend/src/i18n/locales/ru.json b/frontend/src/i18n/locales/ru.json index e19f0759..6220132a 100644 --- a/frontend/src/i18n/locales/ru.json +++ b/frontend/src/i18n/locales/ru.json @@ -5265,6 +5265,7 @@ "changePassword": "Изменить пароль", "changing": "Изменение…", "codeFromAuthenticatorOrBackupCode": "Код из аутентификатора или резервный код", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Подтвердите новый пароль", "confirmNewPassword2": "Подтвердите новый пароль", "connectExternalIdentityProvidersToYour": "Подключите внешних поставщиков удостоверений к своей учетной записи", diff --git a/frontend/src/i18n/locales/th.json b/frontend/src/i18n/locales/th.json index f37fbf74..72316914 100644 --- a/frontend/src/i18n/locales/th.json +++ b/frontend/src/i18n/locales/th.json @@ -5265,6 +5265,7 @@ "changePassword": "เปลี่ยนรหัสผ่าน", "changing": "กำลังเปลี่ยน…", "codeFromAuthenticatorOrBackupCode": "รหัสจากตัวตรวจสอบสิทธิ์หรือรหัสสำรอง", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "ยืนยันรหัสผ่านใหม่", "confirmNewPassword2": "ยืนยันรหัสผ่านใหม่", "connectExternalIdentityProvidersToYour": "เชื่อมต่อผู้ให้บริการข้อมูลประจำตัวภายนอกกับบัญชีของคุณ", diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json index a3c5af47..2f676879 100644 --- a/frontend/src/i18n/locales/tr.json +++ b/frontend/src/i18n/locales/tr.json @@ -5265,6 +5265,7 @@ "changePassword": "Şifre değiştir", "changing": "Değiştiriliyor…", "codeFromAuthenticatorOrBackupCode": "Kimlik doğrulayıcıdan veya yedek koddan gelen kod", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Yeni Şifreyi Onayla", "confirmNewPassword2": "Yeni şifreyi onayla", "connectExternalIdentityProvidersToYour": "Harici kimlik sağlayıcılarını hesabınıza bağlayın", diff --git a/frontend/src/i18n/locales/vi.json b/frontend/src/i18n/locales/vi.json index c6914af5..a57db882 100644 --- a/frontend/src/i18n/locales/vi.json +++ b/frontend/src/i18n/locales/vi.json @@ -5265,6 +5265,7 @@ "changePassword": "Thay đổi mật khẩu", "changing": "Đang thay đổi…", "codeFromAuthenticatorOrBackupCode": "Mã từ trình xác thực hoặc mã dự phòng", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Xác nhận mật khẩu mới", "confirmNewPassword2": "Xác nhận mật khẩu mới", "connectExternalIdentityProvidersToYour": "Kết nối nhà cung cấp danh tính bên ngoài với tài khoản của bạn", diff --git a/frontend/src/i18n/locales/zh-Hans.json b/frontend/src/i18n/locales/zh-Hans.json index 232ba85f..e8230970 100644 --- a/frontend/src/i18n/locales/zh-Hans.json +++ b/frontend/src/i18n/locales/zh-Hans.json @@ -5265,6 +5265,7 @@ "changePassword": "更改密码", "changing": "正在更改…", "codeFromAuthenticatorOrBackupCode": "来自验证器或备份代码的代码", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "确认新密码", "confirmNewPassword2": "确认新密码", "connectExternalIdentityProvidersToYour": "将外部身份提供商连接到您的帐户", diff --git a/frontend/src/i18n/locales/zh-Hant.json b/frontend/src/i18n/locales/zh-Hant.json index f939350d..2017bd5f 100644 --- a/frontend/src/i18n/locales/zh-Hant.json +++ b/frontend/src/i18n/locales/zh-Hant.json @@ -5265,6 +5265,7 @@ "changePassword": "更改密碼", "changing": "正在變更…", "codeFromAuthenticatorOrBackupCode": "驗證器或備用驗證碼", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "確認新密碼", "confirmNewPassword2": "確認新密碼", "connectExternalIdentityProvidersToYour": "將外部身分提供者連線到您的帳戶", diff --git a/frontend/src/utils/__tests__/singleFlight.test.mjs b/frontend/src/utils/__tests__/singleFlight.test.mjs new file mode 100644 index 00000000..bc566f90 --- /dev/null +++ b/frontend/src/utils/__tests__/singleFlight.test.mjs @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createSingleFlight } from '../singleFlight.js'; +import { dismissGuards } from '../../components/ui/dismissGuards.js'; + +test('single flight refuses a second call before the first settles', async () => { + const run = createSingleFlight(); + let calls = 0; + let release; + const first = run(() => { calls += 1; return new Promise((r) => { release = r; }); }); + assert.equal(await run(() => { calls += 1; }), undefined); + release('done'); + assert.equal(await first, 'done'); + assert.equal(calls, 1); + await run(() => { calls += 1; }); + assert.equal(calls, 2); +}); + +test('single flight unlocks after a failure', async () => { + const run = createSingleFlight(); + await assert.rejects(run(() => { throw new Error('x'); })); + assert.equal(await run(() => 'ok'), 'ok'); +}); + +test('dismiss guards only block overlay and Escape when asked', () => { + assert.deepEqual(dismissGuards(), {}); + const g = dismissGuards(false); + for (const key of ['onPointerDownOutside', 'onInteractOutside', 'onEscapeKeyDown']) { + let prevented = false; + g[key]({ preventDefault: () => { prevented = true; } }); + assert.ok(prevented, key); + } +}); diff --git a/frontend/src/utils/singleFlight.js b/frontend/src/utils/singleFlight.js new file mode 100644 index 00000000..b64afa2b --- /dev/null +++ b/frontend/src/utils/singleFlight.js @@ -0,0 +1,15 @@ +// Drops a call while a previous one is still running. Backed by a plain +// object (hold it in a useRef) so a double-click is refused synchronously, +// before React has flushed any `disabled` state. +export function createSingleFlight() { + let busy = false; + return async function run(fn) { + if (busy) return undefined; + busy = true; + try { + return await fn(); + } finally { + busy = false; + } + }; +}