Skip to content

: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.

fix(auth): keep autofilled 2FA setup codes (#90697)

posthog[bot]c2d377c71e49
diff --git a/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.test.tsx b/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.test.tsx
new file mode 100644
index 000000000000..7040a3f9fb2e
--- /dev/null
+++ b/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.test.tsx
@@ -0,0 +1,54 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render } from '@testing-library/react'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { twoFactorLogic } from './twoFactorLogic'
+import { TwoFactorSetup } from './TwoFactorSetup'
+
+describe('TwoFactorSetup', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ function renderSetup(): HTMLInputElement {
+ const { container } = render(
+ <Provider>
+ <TwoFactorSetup onSuccess={jest.fn()} />
+ </Provider>
+ )
+ return container.querySelector<HTMLInputElement>('input[data-attr="token"]')!
+ }
+
+ // A password manager can fill the field without a React change event, so the store only catches
+ // up when the field commits: blur on a mouse submit, or Enter through the form's implicit submit.
+ const commitTriggers: [string, (input: HTMLInputElement) => void][] = [
+ ['blur', (input) => fireEvent.blur(input)],
+ ['pressing Enter', (input) => fireEvent.keyDown(input, { key: 'Enter' })],
+ ]
+
+ it.each(commitTriggers)('syncs a password-manager autofill into the form on %s', async (_label, commit) => {
+ const input = renderSetup()
+
+ // Set the DOM value directly to mimic the autofill, then commit without a change event.
+ input.value = '123 456'
+ commit(input)
+
+ await expectLogic(twoFactorLogic).toMatchValues({ token: { token: '123456' } })
+ })
+
+ it('strips non-digits as the user types', async () => {
+ const input = renderSetup()
+
+ fireEvent.change(input, { target: { value: '12 34 56' } })
+
+ await expectLogic(twoFactorLogic).toMatchValues({ token: { token: '123456' } })
+ })
+})
diff --git a/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.tsx b/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.tsx
index f0ce544bfcec..e605ade2ab4b 100644
--- a/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.tsx
+++ b/frontend/src/scenes/authentication/two-factor-setup/TwoFactorSetup.tsx
@@ -12,7 +12,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { twoFactorLogic } from './twoFactorLogic'
export function TwoFactorSetup({ onSuccess }: { onSuccess: () => void }): JSX.Element | null {
- const { startSetupLoading, startSetup, generalError } = useValues(twoFactorLogic({ onSuccess }))
+ const { startSetupLoading, startSetup, generalError, isTokenSubmitting } = useValues(twoFactorLogic({ onSuccess }))
if (startSetupLoading) {
return null
}
@@ -49,16 +49,33 @@ export function TwoFactorSetup({ onSuccess }: { onSuccess: () => void }): JSX.El
</div>
{generalError && <LemonBanner type="error">{generalError.detail}</LemonBanner>}
<LemonField name="token" label="Authenticator token">
- <LemonInput
- className="ph-ignore-input"
- autoFocus
- data-attr="token"
- placeholder="123456"
- inputMode="numeric"
- autoComplete="one-time-code"
- />
+ {({ value, onChange, id }) => (
+ <LemonInput
+ id={id}
+ className="ph-ignore-input"
+ autoFocus
+ data-attr="token"
+ placeholder="123456"
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ value={value ?? ''}
+ // Password-manager autofill can set the field without firing a React change event.
+ // Read the value on change, blur, and Enter so the store matches what the field shows.
+ // Enter submits the form without blurring, so sync the value before validation runs.
+ onChange={(newValue) => onChange(newValue.replace(/\D/g, ''))}
+ onBlur={(e) => onChange(e.currentTarget.value.replace(/\D/g, ''))}
+ onPressEnter={(e) => onChange(e.currentTarget.value.replace(/\D/g, ''))}
+ />
+ )}
</LemonField>
- <LemonButton htmlType="submit" data-attr="2fa-setup" fullWidth type="primary" center loading={false}>
+ <LemonButton
+ htmlType="submit"
+ data-attr="2fa-setup"
+ fullWidth
+ type="primary"
+ center
+ loading={isTokenSubmitting}
+ >
Submit
</LemonButton>
</Form>
diff --git a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts
index e271725b05b0..54f7b4e03c0f 100644
--- a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts
+++ b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts
@@ -15,7 +15,7 @@ import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { PreflightStatus, UserType } from '../../../types'
export interface TwoFactorForm {
- token: number | null
+ token: string
}
export interface TwoFactorStatus {
@@ -63,15 +63,27 @@ export interface twoFactorLogicValues {
startSetupLoading: boolean
status: TwoFactorStatus | null
statusLoading: boolean
- token: TwoFactorForm
+ token: {
+ token: string
+ }
tokenAllErrors: Record<string, any>
tokenChanged: boolean
- tokenErrors: DeepPartialMap<TwoFactorForm, ValidationErrorType>
+ tokenErrors: DeepPartialMap<
+ {
+ token: string
+ },
+ ValidationErrorType
+ >
tokenHasErrors: boolean
tokenManualErrors: Record<string, any>
tokenTouched: boolean
tokenTouches: Record<string, boolean>
- tokenValidationErrors: DeepPartialMap<TwoFactorForm, ValidationErrorType>
+ tokenValidationErrors: DeepPartialMap<
+ {
+ token: string
+ },
+ ValidationErrorType
+ >
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -164,8 +176,10 @@ export interface twoFactorLogicActions {
forceOpen: boolean | undefined
}
}
- resetToken: (values?: TwoFactorForm) => {
- values?: TwoFactorForm
+ resetToken: (values?: { token: string }) => {
+ values?: {
+ token: string
+ }
}
setGeneralError: (
code: string,
@@ -187,8 +201,14 @@ export interface twoFactorLogicActions {
name: FieldName
value: any
}
- setTokenValues: (values: DeepPartial<TwoFactorForm>) => {
- values: DeepPartial<TwoFactorForm>
+ setTokenValues: (
+ values: DeepPartial<{
+ token: string
+ }>
+ ) => {
+ values: DeepPartial<{
+ token: string
+ }>
}
submitToken: () => {
value: boolean
@@ -200,11 +220,15 @@ export interface twoFactorLogicActions {
error: Error
errors: Record<string, any>
}
- submitTokenRequest: (token: TwoFactorForm) => {
- token: TwoFactorForm
+ submitTokenRequest: (token: { token: string }) => {
+ token: {
+ token: string
+ }
}
- submitTokenSuccess: (token: TwoFactorForm) => {
- token: TwoFactorForm
+ submitTokenSuccess: (token: { token: string }) => {
+ token: {
+ token: string
+ }
}
toggleBackupCodesModal: (open: boolean) => {
open: boolean
@@ -357,7 +381,7 @@ export const twoFactorLogic = kea<twoFactorLogicType>([
})),
forms(({ actions }) => ({
token: {
- defaults: { token: null } as TwoFactorForm,
+ defaults: { token: '' },
errors: ({ token }) => ({
token: !token ? 'Please enter a token to continue' : undefined,
}),