Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';

import * as webAuthnHandlers from 'sentry/components/webAuthn/handlers';

Expand All @@ -15,6 +15,7 @@ describe('WebAuthn2FAMethod', () => {
configurable: true,
value: function PublicKeyCredential() {},
});
jest.spyOn(document, 'hasFocus').mockReturnValue(true);
});

afterEach(() => {
Expand Down Expand Up @@ -146,4 +147,38 @@ describe('WebAuthn2FAMethod', () => {
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
expect(handleSign).toHaveBeenCalledTimes(1);
});

it('waits for the document to be focused before requesting an assertion', async () => {
jest.spyOn(document, 'hasFocus').mockReturnValue(false);
const handleSign = jest
.spyOn(webAuthnHandlers, 'handleSign')
.mockReturnValue(new Promise(() => {}));
const challengeRequest = MockApiClient.addMockResponse({
url: '/auth/2fa/challenge/',
method: 'POST',
body: {
method: 'u2f',
challenge: {webAuthnAuthenticationData: 'challenge'},
},
});
render(
<WebAuthn2FAMethod
isActive
isAuthenticating={false}
isProcessing={false}
submissionFailed={false}
onRetrySubmission={jest.fn()}
onSubmit={jest.fn()}
/>
);

await waitFor(() => expect(challengeRequest).toHaveBeenCalledTimes(1));
expect(handleSign).not.toHaveBeenCalled();

act(() => {
window.dispatchEvent(new Event('focus'));
});

await waitFor(() => expect(handleSign).toHaveBeenCalledTimes(1));
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,23 @@ export function WebAuthn2FAMethod({
}
}

void authenticate();
// Browsers like Safari reject navigator.credentials APIs when the document
// is not focused, so defer the WebAuthn prompt until the window has focus.
if (document.hasFocus()) {
void authenticate();
return () => {
cancelled = true;
};
}

const handleFocus = () => {
void authenticate();
};
window.addEventListener('focus', handleFocus, {once: true});

return () => {
cancelled = true;
window.removeEventListener('focus', handleFocus);
};
// oxlint-disable-next-line react/exhaustive-effect-dependencies
}, [attempt, challenge.result, isActive]);
Expand Down
Loading