diff --git a/client/src/components/Settings/ai/aiConnectModel.ts b/client/src/components/Settings/ai/aiConnectModel.ts index 744d601e0..ed7b39265 100644 --- a/client/src/components/Settings/ai/aiConnectModel.ts +++ b/client/src/components/Settings/ai/aiConnectModel.ts @@ -56,6 +56,26 @@ export function repairModeOf(view: AiConnectionView): AiConnectMode | null { return view.kind === 'custom' ? 'custom' : 'key'; } +/** + * Whether a pasted ChatGPT callback ended this sign-in rather than an earlier + * one: its `state` is the one the sign-in address carried. The server takes a + * sign-in only once, so an address from an earlier attempt still on the + * clipboard would use up the one in progress. Without a state on either side + * the server decides. + */ +export function callbackMatchesFlow(callback: string, authorizeUrl: string): boolean { + const stateOf = (address: string) => { + try { + return new URL(address.trim()).searchParams.get('state'); + } catch { + return null; + } + }; + const expected = stateOf(authorizeUrl); + const pasted = stateOf(callback); + return !expected || !pasted || pasted === expected; +} + // The OpenRouter sign-in leaves the page and comes back with a code only; the // flow it belongs to waits here for that one return. Tab-scoped on purpose. const OPENROUTER_FLOW_KEY = 'trek.ai.openrouterFlow'; diff --git a/client/src/components/Settings/ai/useAiConnect.test.ts b/client/src/components/Settings/ai/useAiConnect.test.ts index 9e1ffb0c9..fc7638d91 100644 --- a/client/src/components/Settings/ai/useAiConnect.test.ts +++ b/client/src/components/Settings/ai/useAiConnect.test.ts @@ -1,4 +1,4 @@ -// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-013: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return. +// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-015: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return. import { act, fireEvent, renderHook, waitFor } from '@testing-library/react'; import { createElement, type ReactNode } from 'react'; import { MemoryRouter, useLocation } from 'react-router'; @@ -249,6 +249,52 @@ describe('useChatgptConnect', () => { expect(readText).toHaveBeenCalledTimes(1); input.remove(); }); + + it('FE-HOOK-AI-CONNECT-014: the same address handed in twice at once is sent once, so the sign-in is not used up', async () => { + let answer: (value: unknown) => void = () => undefined; + repo.chatgptFinish.mockImplementationOnce(() => new Promise((resolve) => (answer = resolve))); + const onConnected = vi.fn(); + const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() }); + await waitFor(() => expect(result.current.flow).not.toBeNull()); + act(() => { + result.current.paste(CALLBACK); + result.current.paste(CALLBACK); + }); + await act(async () => answer({})); + await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1)); + expect(repo.chatgptFinish).toHaveBeenCalledTimes(1); + expect(result.current.error).toBeNull(); + }); + + it('FE-HOOK-AI-CONNECT-015: an address from an earlier sign-in is not sent, and the one in progress stays usable', async () => { + repo.chatgptStart.mockResolvedValue({ ...FLOW, authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=s2' }); + const readText = vi.fn(async () => CALLBACK); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { readText } }); + Object.defineProperty(window, 'isSecureContext', { configurable: true, value: true }); + const onConnected = vi.fn(); + const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() }); + await waitFor(() => expect(result.current.flow).not.toBeNull()); + + // Back from the sign-in window with the old address still on the clipboard: nothing is sent. + act(() => result.current.markOpened()); + fireEvent.focus(window); + await waitFor(() => expect(readText).toHaveBeenCalled()); + expect(repo.chatgptFinish).not.toHaveBeenCalled(); + expect(result.current.error).toBeNull(); + + // Pasted by hand it is refused here, and the address this sign-in ended on still goes through. + act(() => { + result.current.paste(CALLBACK); + }); + expect(result.current.error).toEqual({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' }); + const current = CALLBACK.replace('state=s1', 'state=s2'); + act(() => { + result.current.paste(current); + }); + await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1)); + expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: current }); + expect(repo.chatgptStart).toHaveBeenCalledTimes(1); + }); }); describe('OpenRouter', () => { diff --git a/client/src/components/Settings/ai/useAiConnect.ts b/client/src/components/Settings/ai/useAiConnect.ts index dc9c7d49d..f2005c239 100644 --- a/client/src/components/Settings/ai/useAiConnect.ts +++ b/client/src/components/Settings/ai/useAiConnect.ts @@ -5,7 +5,14 @@ import { useTranslation } from '../../../i18n'; import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo'; import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog'; import { useToast } from '../../shared/Toast'; -import { connectErrorKey, httpHostOf, refusalCode, rememberOpenrouterFlow, takeOpenrouterFlow } from './aiConnectModel'; +import { + callbackMatchesFlow, + connectErrorKey, + httpHostOf, + refusalCode, + rememberOpenrouterFlow, + takeOpenrouterFlow, +} from './aiConnectModel'; /** * The ways to connect a provider, one hook each, behind `AiConnectPanel`: a @@ -205,6 +212,10 @@ export function useChatgptConnect({ const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const inputRef = useRef(null); + // Set at once, unlike `busy`: the clipboard read on return and the user's own + // paste can hand in the same address within one render, and the server takes + // a sign-in only once, so the second would come back as expired. + const finishing = useRef(false); useEffect(() => { if (!active) return; @@ -232,8 +243,8 @@ export function useChatgptConnect({ const finish = async (raw: string) => { const url = raw.trim(); - if (!flow || busy) return; - if (!isChatgptCallback(url)) { + if (!flow || finishing.current) return; + if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) { setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' }); return; } @@ -242,6 +253,7 @@ export function useChatgptConnect({ restart(); return; } + finishing.current = true; setBusy(true); setError(null); try { @@ -253,6 +265,7 @@ export function useChatgptConnect({ setError({ messageKey: connectErrorKey(err), code }); if (code === 'expired') restart(); } finally { + finishing.current = false; setBusy(false); } }; @@ -280,10 +293,12 @@ export function useChatgptConnect({ // Back from the sign-in window: the address the user just copied is taken // off the clipboard where the browser allows it, else the field has the cursor. + // An address left over from an earlier sign-in is not sent: it would use up this one. useOnReturnToTab(opened, () => { if (pasted.trim() || busy) return; readClipboard((text) => { - if (!paste(text)) focusField(); + if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField(); + else if (!paste(text)) focusField(); }, focusField); });