Commit 2f990077 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a password step to Telegram linking for two-step verification accounts

/auth/telegram/login now 412s instead of a generic error when the
account has a cloud password enabled. TelegramLink.tsx catches that
specifically and drops into a new password step (submitTelegramPassword)
instead of showing "that code didn't work" for something the code
never had anything to do with.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 58bcf90a
Pipeline #1106 failed with stage
......@@ -54,6 +54,16 @@ export function linkTelegram(phoneNumber: string, phoneCodeHash: string, code: s
})
}
/** linkTelegram() 412s with this when the account has two-step verification enabled - call
* this with the cloud password to finish the same link (the in-progress Telegram auth session
* is kept alive server-side, keyed by phoneNumber). */
export function submitTelegramPassword(phoneNumber: string, password: string) {
return apiFetch<{ status: string; phone_number: string }>('/auth/telegram/password', {
method: 'POST',
json: { phone_number: phoneNumber, password },
})
}
export interface Chat {
id: number
title: string
......
......@@ -43,7 +43,7 @@ const BACKEND_DONE: DoneGroup[] = [
area: 'Auth',
items: [
'Username/password register, login, refresh (rotating), logout (real server-side revoke) - PBKDF2, stdlib only',
'Telegram phone/code account-linking (/auth/telegram/*), attaches to the already-authenticated caller (fixed 2026-08-18 - used to silently create a disconnected identity instead)',
'Telegram phone/code account-linking (/auth/telegram/*), attaches to the already-authenticated caller (fixed 2026-08-18 - used to silently create a disconnected identity instead); handles accounts with two-step verification via a 412 + /auth/telegram/password step',
'Rate limited: login (10 attempts/account/15min, 100/source/hr), Telegram request_code (5/phone/10min, 20/IP/hr) - independent of each other despite sharing a table',
],
},
......@@ -129,7 +129,7 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [
'Login page: username/password + register, toggled in place',
'Route guards redirect to /login when signed out instead of showing a blank page',
'Telegram linking page: phone + code, then browse linked chats and save any found song to the library (tags via /music/tag, one song at a time)',
'Telegram linking page: phone + code (+ two-step verification password if the account has it enabled), then browse linked chats and save any found song to the library (tags via /music/tag, one song at a time)',
],
},
{ area: 'Soundmarks', items: ['Nearby page: dark-themed map, tier-aware display, proposals + voting UI'] },
......@@ -265,8 +265,8 @@ export function Roadmap() {
{[
['9', 'Feature areas'],
['0', 'Critical security gaps'],
['229', 'Backend tests'],
['180', 'Frontend tests'],
['234', 'Backend tests'],
['183', 'Frontend tests'],
['4', 'Pages w/ zero tests'],
].map(([n, l]) => (
<div key={l}>
......
......@@ -103,6 +103,69 @@ describe('TelegramLink', () => {
expect(await screen.findByText('Music Sharing')).toBeInTheDocument()
})
it('moves to the password step when the account has two-step verification enabled', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
vi.spyOn(authApi, 'linkTelegram').mockRejectedValue(new ApiError(412, 'Two-step verification password required', null))
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
expect(await screen.findByLabelText('Telegram password')).toBeInTheDocument()
expect(screen.getByText(/Two-step verification is on/)).toBeInTheDocument()
})
it('submits the two-step password and shows the chat list once linked', async () => {
vi.spyOn(authApi, 'getChats')
.mockRejectedValueOnce(new ApiError(400, 'No linked Telegram session', null))
.mockResolvedValueOnce({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
vi.spyOn(authApi, 'linkTelegram').mockRejectedValue(new ApiError(412, 'Two-step verification password required', null))
const submitTelegramPassword = vi
.spyOn(authApi, 'submitTelegramPassword')
.mockResolvedValue({ status: 'success', phone_number: '+15551234567' })
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
await userEvent.type(await screen.findByLabelText('Telegram password'), 'hunter2')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
expect(submitTelegramPassword).toHaveBeenCalledWith('+15551234567', 'hunter2')
expect(await screen.findByText('Music Sharing')).toBeInTheDocument()
})
it('shows the backend error when the two-step password is wrong', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
vi.spyOn(authApi, 'linkTelegram').mockRejectedValue(new ApiError(412, 'Two-step verification password required', null))
vi.spyOn(authApi, 'submitTelegramPassword').mockRejectedValue(new ApiError(400, 'Invalid password', null))
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
await userEvent.type(await screen.findByLabelText('Telegram password'), 'wrongpass')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
expect(await screen.findByText('Invalid password')).toBeInTheDocument()
})
it('shows the backend error when the code is wrong, without leaving the code step', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
......
......@@ -5,6 +5,7 @@ import {
getChats,
linkTelegram,
requestTelegramCode,
submitTelegramPassword,
type Chat,
type ChatMusic,
} from '../api/auth'
......@@ -16,7 +17,7 @@ import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
type Step = 'checking' | 'phone' | 'code' | 'linked'
type Step = 'checking' | 'phone' | 'code' | 'password' | 'linked'
export function TelegramLink() {
const [step, setStep] = useState<Step>('checking')
......@@ -26,6 +27,7 @@ export function TelegramLink() {
const [phoneNumber, setPhoneNumber] = useState('')
const [phoneCodeHash, setPhoneCodeHash] = useState('')
const [code, setCode] = useState('')
const [password, setPassword] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
......@@ -87,7 +89,26 @@ export function TelegramLink() {
await linkTelegram(phoneNumber.trim(), phoneCodeHash, code.trim())
loadChats()
} catch (err) {
setError(err instanceof ApiError ? err.message : "That code didn't work. Please try again.")
if (err instanceof ApiError && err.status === 412) {
setStep('password')
} else {
setError(err instanceof ApiError ? err.message : "That code didn't work. Please try again.")
}
} finally {
setBusy(false)
}
}
async function handleSubmitPassword(e: React.FormEvent) {
e.preventDefault()
if (!password.trim()) return
setBusy(true)
setError(null)
try {
await submitTelegramPassword(phoneNumber.trim(), password.trim())
loadChats()
} catch (err) {
setError(err instanceof ApiError ? err.message : "That password didn't work. Please try again.")
} finally {
setBusy(false)
}
......@@ -96,6 +117,7 @@ export function TelegramLink() {
function handleChangeNumber() {
setStep('phone')
setCode('')
setPassword('')
setError(null)
}
......@@ -144,18 +166,18 @@ export function TelegramLink() {
)
}
if (step === 'phone' || step === 'code') {
if (step === 'phone' || step === 'code' || step === 'password') {
return (
<Layout title="Link Telegram">
<div className="mx-auto w-full max-w-sm">
<p className="mb-6 text-sm text-neutral-400">
{step === 'phone'
? 'Link your Telegram account to scan your chats for music.'
: `Enter the code sent to ${phoneNumber}.`}
{step === 'phone' && 'Link your Telegram account to scan your chats for music.'}
{step === 'code' && `Enter the code sent to ${phoneNumber}.`}
{step === 'password' && 'Two-step verification is on for this account. Enter your Telegram cloud password.'}
</p>
{chatsError && <p className="mb-4 text-sm text-red-400">{chatsError}</p>}
{step === 'phone' ? (
{step === 'phone' && (
<form onSubmit={handleSendCode} className="space-y-3">
<Input
type="tel"
......@@ -172,7 +194,9 @@ export function TelegramLink() {
{busy ? 'Sending code…' : 'Send code'}
</Button>
</form>
) : (
)}
{step === 'code' && (
<form onSubmit={handleVerifyCode} className="space-y-3">
<Input
type="text"
......@@ -197,6 +221,31 @@ export function TelegramLink() {
</button>
</form>
)}
{step === 'password' && (
<form onSubmit={handleSubmitPassword} className="space-y-3">
<Input
type="password"
autoComplete="current-password"
autoFocus
placeholder="Cloud password"
value={password}
onChange={(e) => setPassword(e.target.value)}
aria-label="Telegram password"
/>
{error && <p className="text-sm text-red-400">{error}</p>}
<Button type="submit" disabled={busy || !password.trim()} className="w-full">
{busy ? 'Verifying…' : 'Verify & link'}
</Button>
<button
type="button"
onClick={handleChangeNumber}
className="w-full text-center text-sm text-neutral-500 transition-colors hover:text-neutral-300"
>
Use a different number
</button>
</form>
)}
</div>
</Layout>
)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment