:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): prevent Safari freeze from auto-triggered passkey login (#65990)
Eleftheria Trivyzakifee9f62bd8fe
diff --git a/frontend/src/lib/utils/dom.ts b/frontend/src/lib/utils/dom.tsindex 707a9802d670..64c55d40b46e 100644--- a/frontend/src/lib/utils/dom.ts+++ b/frontend/src/lib/utils/dom.ts@@ -63,6 +63,12 @@ export function isMac(): boolean {return navigator.platform.includes('Mac')}+export function isWebKitBrowser(): boolean {+ // macOS Safari reports the Apple vendor. iOS forces every browser onto WebKit,+ // so also treat any iOS user agent as WebKit regardless of the vendor string it reports.+ return navigator.vendor === 'Apple Computer, Inc.' || /iPad|iPhone|iPod/.test(navigator.userAgent)+}+export function platformCommandControlKey(modifier: string): string {return `${isMac() ? '⌘' : 'Ctrl + '}${modifier}`}diff --git a/frontend/src/scenes/authentication/login/Login.tsx b/frontend/src/scenes/authentication/login/Login.tsxindex 91f0810113e3..e4d1fec98412 100644--- a/frontend/src/scenes/authentication/login/Login.tsx+++ b/frontend/src/scenes/authentication/login/Login.tsx@@ -1,6 +1,8 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'import { SceneExport } from 'scenes/sceneTypes'import { authFlowVariantRegistry } from '../authFlowVariantRegistry'@@ -14,6 +16,14 @@ export const scene: SceneExport = {export function Login(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)+ const { startConditionalPasskeyLogin } = useActions(passkeyLogic)const { Login: VariantLogin } = authFlowVariantRegistry[resolveAuthFlowVariant(featureFlags)]++ // WebKit (Safari/iOS) can't open the passkey modal without a user gesture, so we show+ // passkeys via the email field's autofill instead. Other browsers keep the auto-modal.+ useEffect(() => {+ startConditionalPasskeyLogin()+ }, [startConditionalPasskeyLogin])+return <VariantLogin />}diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.tsindex a73f34467a56..2366fa32a8db 100644--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts@@ -1,12 +1,25 @@+import { startAuthentication } from '@simplewebauthn/browser'import { router } from 'kea-router'-import { testUtilsPlugin } from 'kea-test-utils'+import { expectLogic, testUtilsPlugin } from 'kea-test-utils'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { handleLoginRedirect, loginLogic } from 'scenes/authentication/login/loginLogic'+import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'import { initKea } from '~/initKea'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+jest.mock('@simplewebauthn/browser', () => ({ startAuthentication: jest.fn() }))++// isWebKitBrowser() reads navigator.vendor: "Apple Computer, Inc." on WebKit, "Google Inc." on Chromium.+const WEBKIT_VENDOR = 'Apple Computer, Inc.'+const CHROMIUM_VENDOR = 'Google Inc.'++function setVendor(vendor: string): void {+ Object.defineProperty(window.navigator, 'vendor', { value: vendor, configurable: true })+}+describe('loginLogic', () => {describe('redirect vulnerability', () => {beforeEach(() => {@@ -62,4 +75,100 @@ describe('loginLogic', () => {})}})++ describe('passkey auto-trigger after precheck', () => {+ let logic: ReturnType<typeof loginLogic.build>+ let beginHandler: jest.Mock+ const originalVendor = window.navigator.vendor++ beforeEach(() => {+ setVendor(CHROMIUM_VENDOR)+ // Treat the passkey prompt as a user cancellation so it resolves without a page reload.+ ;(startAuthentication as jest.Mock).mockRejectedValue(+ Object.assign(new Error('cancelled'), { name: 'AbortError' })+ )+ beginHandler = jest.fn(() => [+ 200,+ {+ challenge: 'abc',+ timeout: 60000,+ rpId: 'localhost',+ allowCredentials: [],+ userVerification: 'preferred',+ },+ ])+ useMocks({+ get: { '/api/users/@me/': () => [200, {}] },+ post: {+ '/api/login/precheck': () => [+ 200,+ { saml_available: false, webauthn_credentials: [{ id: 'cred-1', type: 'public-key' }] },+ ],+ '/api/webauthn/login/begin/': beginHandler,+ },+ })+ initKeaTests()+ router.actions.push('/login')+ logic = loginLogic()+ logic.mount()+ passkeyLogic().mount()+ })++ afterEach(() => {+ passkeyLogic().unmount()+ logic.unmount()+ setVendor(originalVendor)+ jest.clearAllMocks()+ })++ it('auto-triggers the passkey prompt on non-WebKit browsers', async () => {+ logic.actions.precheck({ email: '[email protected]' })+ // Drain the whole passkey flow (begin request included) so nothing leaks into the next test.+ await expectLogic(passkeyLogic)+ .toDispatchActions(['beginPasskeyLogin', 'startPasskeyAuthenticationSuccess'])+ .toFinishAllListeners()+ expect(beginHandler).toHaveBeenCalledTimes(1)+ })++ it('does not auto-trigger the passkey modal on WebKit (Safari)', async () => {+ setVendor(WEBKIT_VENDOR)+ logic.actions.precheck({ email: '[email protected]' })+ await expectLogic(logic).toDispatchActions(['precheckSuccess']).toFinishAllListeners()+ expect(beginHandler).not.toHaveBeenCalled()+ })+ })++ describe('precheck dedupe', () => {+ let logic: ReturnType<typeof loginLogic.build>+ let precheckHandler: jest.Mock+ const originalVendor = window.navigator.vendor++ beforeEach(() => {+ setVendor(WEBKIT_VENDOR) // skip passkey auto-trigger, isolate precheck+ precheckHandler = jest.fn(() => [200, { saml_available: false }])+ useMocks({ post: { '/api/login/precheck': precheckHandler } })+ initKeaTests()+ router.actions.push('/login')+ logic = loginLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ setVendor(originalVendor)+ jest.clearAllMocks()+ })++ it('skips a redundant precheck for an already-resolved email but re-runs for a new one', async () => {+ logic.actions.precheck({ email: '[email protected]' })+ await expectLogic(logic).toDispatchActions(['precheckSuccess'])+ logic.actions.precheck({ email: '[email protected]' })+ await expectLogic(logic).toDispatchActions(['precheckSuccess'])+ expect(precheckHandler).toHaveBeenCalledTimes(1)++ logic.actions.precheck({ email: '[email protected]' })+ await expectLogic(logic).toDispatchActions(['precheckSuccess'])+ expect(precheckHandler).toHaveBeenCalledTimes(2)+ })+ })})diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.tsindex d91d01b16fc4..5e25bf18e300 100644--- a/frontend/src/scenes/authentication/login/loginLogic.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.ts@@ -8,6 +8,7 @@ import { router } from 'kea-router'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { isWebKitBrowser } from 'lib/utils/dom'import { getRelativeNextPath } from 'lib/utils/url'import { devLoginLogic } from 'scenes/authentication/shared/devLoginLogic'import { twoFactorResetLogic } from 'scenes/authentication/two-factor-reset/twoFactorResetLogic'@@ -29,6 +30,8 @@ export interface PrecheckResponseType {saml_available: booleanstatus: 'pending' | 'completed'webauthn_credentials?: PublicKeyCredentialDescriptorJSON[]+ // The email this precheck resolved for, used to dedupe redundant prechecks.+ email?: string}// Routes that should be handled by Django, not the React router@@ -100,7 +103,7 @@ export const loginLogic = kea<loginLogicType>([},],}),- loaders(() => ({+ loaders(({ values }) => ({precheckResponse: [{ status: 'pending' } as PrecheckResponseType,{@@ -116,9 +119,16 @@ export const loginLogic = kea<loginLogicType>([return { status: 'pending' }}+ // The autofill effect and the email field's onBlur can both fire for the same+ // value — skip the redundant network call (and the duplicate passkey trigger it+ // would cause) when we've already resolved this email.+ if (email === values.precheckResponse.email && values.precheckResponse.status === 'completed') {+ return values.precheckResponse+ }+breakpoint()const response = await api.create<any>('api/login/precheck', { email })- return { status: 'completed', ...response }+ return { status: 'completed', ...response, email }},},],@@ -203,11 +213,13 @@ export const loginLogic = kea<loginLogicType>([},precheckSuccess: async (_, breakpoint) => {const { precheckResponse } = values- // Auto-trigger passkey prompt if user has passkeys and SSO is not enforced+ // Auto-trigger the modal passkey prompt if the user has passkeys and SSO isn't enforced.+ // Skip on WebKit, it freezes Safari when triggered without a user gesture.if (precheckResponse.webauthn_credentials &&precheckResponse.webauthn_credentials.length > 0 &&- !precheckResponse.sso_enforcement+ !precheckResponse.sso_enforcement &&+ !isWebKitBrowser()) {breakpoint()// Dynamic import to avoid circular dependencydiff --git a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsxindex 22e90c60bbf7..5f851b8c7ddc 100644--- a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx+++ b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx@@ -15,6 +15,7 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonField } from 'lib/lemon-ui/LemonField'import { Link } from 'lib/lemon-ui/Link'import { Skeleton } from 'lib/ui/quill'+import { isWebKitBrowser } from 'lib/utils/dom'import { isEmail } from 'lib/utils/url'import { AuthShell } from 'scenes/authentication/shared/AuthShell'import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'@@ -174,6 +175,9 @@ function Login(): JSX.Element {data-attr="login-email"placeholder="[email protected]"type="email"+ // The `webauthn` token enables passkey autofill (conditional UI), which+ // we only offer on WebKit; elsewhere the auto-modal handles passkeys.+ autoComplete={isWebKitBrowser() ? 'username webauthn' : undefined}onBlur={() => precheck({ email: login.email })}onPressEnter={(e) => {if (isPasswordHidden) {diff --git a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsxindex a371219f1043..b72ef591f7be 100644--- a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx+++ b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx@@ -10,6 +10,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'import { Link } from 'lib/lemon-ui/Link'+import { isWebKitBrowser } from 'lib/utils/dom'import { isEmail } from 'lib/utils/url'import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'import { OtherRegionHint } from 'scenes/authentication/shared/OtherRegionHint'@@ -137,7 +138,9 @@ function Login(): JSX.Element {type="email"autoFocusplaceholder="[email protected]"- autoComplete="email"+ // The `webauthn` token enables passkey autofill (conditional UI),+ // which we only offer on WebKit; elsewhere the auto-modal handles passkeys.+ autoComplete={isWebKitBrowser() ? 'username webauthn' : 'email'}value={value ?? ''}onChange={onChange}onBlur={() => precheck({ email: login.email })}diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.test.tsnew file mode 100644index 000000000000..9c7a6be38b0b--- /dev/null+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts@@ -0,0 +1,99 @@+import { browserSupportsWebAuthnAutofill, startAuthentication } from '@simplewebauthn/browser'+import { expectLogic } from 'kea-test-utils'++import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++jest.mock('@simplewebauthn/browser', () => ({+ startAuthentication: jest.fn(),+ browserSupportsWebAuthnAutofill: jest.fn(),+}))++// isWebKitBrowser() reads navigator.vendor: "Apple Computer, Inc." on WebKit, "Google Inc." on Chromium.+const WEBKIT_VENDOR = 'Apple Computer, Inc.'+const CHROMIUM_VENDOR = 'Google Inc.'++function setVendor(vendor: string): void {+ Object.defineProperty(window.navigator, 'vendor', { value: vendor, configurable: true })+}++describe('passkeyLogic', () => {+ describe('startConditionalPasskeyLogin (WebKit-only passkey autofill)', () => {+ let logic: ReturnType<typeof passkeyLogic.build>+ let beginHandler: jest.Mock+ const originalVendor = window.navigator.vendor++ beforeEach(() => {+ setVendor(WEBKIT_VENDOR)+ ;(browserSupportsWebAuthnAutofill as jest.Mock).mockResolvedValue(true)+ // Resolve the passkey prompt as a cancellation so it settles without a page reload.+ ;(startAuthentication as jest.Mock).mockRejectedValue(+ Object.assign(new Error('cancelled'), { name: 'AbortError' })+ )+ beginHandler = jest.fn(() => [+ 200,+ {+ challenge: 'abc',+ timeout: 60000,+ rpId: 'localhost',+ allowCredentials: [{ id: 'cred-1', type: 'public-key' }],+ userVerification: 'required',+ },+ ])+ useMocks({+ get: { '/api/users/@me/': () => [200, {}] },+ post: { '/api/webauthn/login/begin/': beginHandler },+ })+ initKeaTests()+ logic = passkeyLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ setVendor(originalVendor)+ jest.clearAllMocks()+ })++ it('on WebKit, requests a passkey via browser autofill with no credential constraint', async () => {+ logic.actions.startConditionalPasskeyLogin()+ await expectLogic(logic).toFinishAllListeners()++ expect(beginHandler).toHaveBeenCalledTimes(1)+ const options = (startAuthentication as jest.Mock).mock.calls[0][0]+ expect(options.useBrowserAutofill).toBe(true)+ // Conditional UI must not constrain credentials — the browser offers all discoverable passkeys.+ expect(options.optionsJSON.allowCredentials).toEqual([])+ })++ it('does nothing on a non-WebKit browser (those use the auto-modal instead)', async () => {+ setVendor(CHROMIUM_VENDOR)++ logic.actions.startConditionalPasskeyLogin()+ await expectLogic(logic).toFinishAllListeners()++ expect(beginHandler).not.toHaveBeenCalled()+ expect(startAuthentication).not.toHaveBeenCalled()+ })++ it('does nothing when the browser does not support autofill', async () => {+ ;(browserSupportsWebAuthnAutofill as jest.Mock).mockResolvedValue(false)++ logic.actions.startConditionalPasskeyLogin()+ await expectLogic(logic).toFinishAllListeners()++ expect(beginHandler).not.toHaveBeenCalled()+ expect(startAuthentication).not.toHaveBeenCalled()+ })++ it('starts only one passkey request when triggered repeatedly', async () => {+ logic.actions.startConditionalPasskeyLogin()+ logic.actions.startConditionalPasskeyLogin()+ await expectLogic(logic).toFinishAllListeners()++ expect(beginHandler).toHaveBeenCalledTimes(1)+ })+ })+})diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.tsindex 8135b3255e6b..431b494022d5 100644--- a/frontend/src/scenes/authentication/shared/passkeyLogic.ts+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.ts@@ -1,10 +1,15 @@-import { type PublicKeyCredentialDescriptorJSON, startAuthentication } from '@simplewebauthn/browser'+import {+ browserSupportsWebAuthnAutofill,+ type PublicKeyCredentialDescriptorJSON,+ startAuthentication,+} from '@simplewebauthn/browser'import { actions, connect, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import api from 'lib/api'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'+import { isWebKitBrowser } from 'lib/utils/dom'import { handleLoginRedirect, loginLogic } from 'scenes/authentication/login/loginLogic'import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'import { userLogic } from 'scenes/userLogic'@@ -43,6 +48,7 @@ export const passkeyLogic = kea<passkeyLogicType>([params?: BeginPasskeyLoginParams) => ({ allowCredentials, params }),startPasskeyAuthentication: true,+ startConditionalPasskeyLogin: true,passkeyAuthenticationCancelled: true,reset: true,}),@@ -127,11 +133,55 @@ export const passkeyLogic = kea<passkeyLogicType>([},],})),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({beginPasskeyLogin: () => {+ // Don't start a second passkey sign-in while one is already in flight (e.g. a+ // double-clicked passkey button) — concurrent WebAuthn requests hang WebKit.+ if (values.loginWithPasskeyLoading) {+ return+ }// After setting credentials in reducer, start the authenticationactions.startPasskeyAuthentication()},+ startConditionalPasskeyLogin: async () => {+ // WebKit-only. Safari/iOS freeze on the auto-modal, so there we offer passkeys via the+ // email field's autofill instead+ if (!isWebKitBrowser()) {+ return+ }+ // Latch synchronously before the first await so a repeat trigger can't race past the guard.+ if (cache.passkeyAutofillStarted) {+ return+ }+ cache.passkeyAutofillStarted = true+ if (!(await browserSupportsWebAuthnAutofill())) {+ return+ }+ try {+ const beginResponse = await api.create<PasskeyLoginBeginResponse>('api/webauthn/login/begin/')+ const assertion = await startAuthentication({+ optionsJSON: {+ challenge: beginResponse.challenge,+ timeout: beginResponse.timeout,+ rpId: beginResponse.rpId,+ // Conditional UI must not constrain credentials — the browser offers whatever+ // discoverable passkeys exist for this site.+ allowCredentials: [],+ userVerification: beginResponse.userVerification as UserVerificationRequirement,+ },+ useBrowserAutofill: true,+ })+ await api.create('api/webauthn/login/complete/', assertion)+ handleLoginRedirect()+ window.location.reload()+ } catch (e: unknown) {+ // The autofill passkey prompt is routinely dismissed — the user types a password+ // instead, or navigates away. Swallow those; surface anything genuinely wrong.+ if (!isWebAuthnCancellation(e)) {+ actions.setGeneralError('passkey_error', getPasskeyErrorMessage(e))+ }+ }+ },startPasskeyAuthenticationSuccess: async () => {// The loader returns null on user cancellation to avoid surfacing// the DOMException to global error capture. Skip the post-login