Merge pull request #273 from jhd3197/fix/2fa-enrollment-secret-reuse

Reuse the pending 2FA enrollment secret
This commit is contained in:
Juan Denis authored and GitHub committed 2026-11-28 14:07:00 -05:00
commit 70f268a0ef
26 files changed
+226 -40

No files matched your search

+6 -2
View File
@@ -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.',
+18 -6
View File
@@ -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
+68
View File
@@ -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
+6 -1
View File
@@ -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 <form>. 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 (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className={cn('sk-modal', `sk-modal--${size}`, className)}>
<DialogContent className={cn('sk-modal', `sk-modal--${size}`, className)} {...dismissGuards(closeOnDismiss)}>
{title && (
<div className="sk-modal__header">
<DialogTitle>{title}</DialogTitle>
@@ -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 && (
<Modal open={true} onClose={() => setShowSetupModal(false)} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md">
<Modal open={true} onClose={() => setShowSetupModal(false)} closeOnDismiss={false} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md">
<div className="setup-steps" data-walkthrough="two-factor-verify">
<div className="setup-step">
<span className="step-number">1</span>
@@ -494,6 +503,7 @@ Keep these codes in a safe place.`;
autoFocus
/>
{twoFAError && <p className="error-text">{twoFAError}</p>}
{confirmFailed && <p className="form-hint">{t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}</p>}
</div>
</div>
</div>
@@ -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 && (
<div className="tier-warning">
<AlertTriangle size={20} className="tier-warning-icon" />
<div className="tier-warning-text">{error}</div>
<div className="tier-warning-text">
{error}
{confirmFailed && <> {t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}</>}
</div>
</div>
)}
@@ -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 };
}
+1
View File
@@ -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": "قم بتوصيل موفري الهوية الخارجيين بحسابك",
+1
View File
@@ -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": "আপনার অ্যাকাউন্টে বহিরাগত পরিচয় প্রদানকারীকে সংযুক্ত করুন",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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 공급자를 계정에 연결",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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": "Подключите внешних поставщиков удостоверений к своей учетной записи",
+1
View File
@@ -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": "เชื่อมต่อผู้ให้บริการข้อมูลประจำตัวภายนอกกับบัญชีของคุณ",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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": "将外部身份提供商连接到您的帐户",
+1
View File
@@ -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": "將外部身分提供者連線到您的帳戶",
@@ -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);
}
});
+15
View File
@@ -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;
}
};
}