mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
fix(ai): say why ChatGPT refused a sign-in, and start a fresh one after any refusal
Every refusal of the code by OpenAI's token endpoint came back as "The sign-in took too long", and the endpoint's own error was dropped without a log line. Only invalid_grant means the code ran out or was used already; any other refusal (invalid_client, a redirect or resource mismatch) now names its OAuth error in the answer and in a warning with the endpoint's description, so an admin can see what went wrong. The server takes a sign-in once whatever it answers, but the panel only started a fresh one after "expired", so the next try after any other refusal used a spent sign-in. It now starts a fresh one after every refusal the server sent; offline and a wrong address keep the one in progress, as neither reached it. The address the sign-in window ends on is also taken without http://, the way the hint under the field and the address bar show it. Closes #3196
This commit is contained in:
@@ -111,11 +111,23 @@ export const CHATGPT_USAGE_URL = 'https://chatgpt.com/settings/usage';
|
||||
* error page and the user pastes its address back; only the port may differ.
|
||||
*/
|
||||
export function isChatgptCallback(text: string): boolean {
|
||||
return chatgptCallbackUrl(text) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pasted callback as the server reads it, or null when it is something
|
||||
* else. The address bar and the hint under the field show it without `http://`,
|
||||
* so an address pasted that way gets the scheme put back.
|
||||
*/
|
||||
export function chatgptCallbackUrl(text: string): string | null {
|
||||
const trimmed = text.trim();
|
||||
const address = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(text.trim());
|
||||
url = new URL(address);
|
||||
} catch {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
|
||||
const ok = url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
|
||||
return ok ? address : null;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// 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.
|
||||
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-017: 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';
|
||||
@@ -20,6 +20,7 @@ vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
const { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterReturn, useOpenrouterStart } =
|
||||
await import('./useAiConnect');
|
||||
const { rememberOpenrouterFlow } = await import('./aiConnectModel');
|
||||
const { OnlineOnlyError } = await import('../../../repo/onlineOnly');
|
||||
|
||||
function wrapperAt(url = '/settings') {
|
||||
return ({ children }: { children: ReactNode }) =>
|
||||
@@ -207,7 +208,7 @@ describe('useChatgptConnect', () => {
|
||||
expect(repo.chatgptFinish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so and keeps the flow', async () => {
|
||||
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so, and the next try is a fresh sign-in', async () => {
|
||||
repo.chatgptFinish.mockRejectedValueOnce(refused('not_eligible'));
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||
@@ -216,7 +217,50 @@ describe('useChatgptConnect', () => {
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error).toEqual({ messageKey: 'assistant.error.notEligible', code: 'not_eligible' });
|
||||
expect(onConnected).not.toHaveBeenCalled();
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
|
||||
// The server took the sign-in when it refused it.
|
||||
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-016: any refusal the server sent starts exactly one fresh sign-in; offline and a wrong address keep this one', async () => {
|
||||
const generic = Object.assign(new Error('generic'), {
|
||||
response: { status: 400, data: { error: 'ChatGPT refused the sign-in (invalid_client)', code: 'generic' } },
|
||||
});
|
||||
repo.chatgptFinish.mockRejectedValueOnce(generic).mockRejectedValueOnce(new OnlineOnlyError());
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('generic');
|
||||
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('offline');
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
|
||||
|
||||
// The server refuses a wrong address before it takes the sign-in, so the right one still works.
|
||||
repo.chatgptFinish.mockRejectedValueOnce(refused('wrong_url'));
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('wrong_url');
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-017: the address pasted without http://, as the hint shows it, is taken and sent with it', async () => {
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
const bare = CALLBACK.replace('http://', '');
|
||||
let taken = false;
|
||||
act(() => {
|
||||
taken = result.current.paste(` ${bare} `);
|
||||
});
|
||||
expect(taken).toBe(true);
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: CALLBACK });
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-013: the clipboard fills the field where the browser lets it be read, else the field gets the cursor', async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
||||
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { chatgptCallbackUrl, detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import {
|
||||
callbackMatchesFlow,
|
||||
@@ -243,9 +243,9 @@ export function useChatgptConnect({
|
||||
};
|
||||
|
||||
const finish = async (raw: string) => {
|
||||
const url = raw.trim();
|
||||
const url = chatgptCallbackUrl(raw);
|
||||
if (!flow || finishing.current) return;
|
||||
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) {
|
||||
if (!url || !callbackMatchesFlow(url, flow.authorizeUrl)) {
|
||||
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
||||
return;
|
||||
}
|
||||
@@ -264,7 +264,9 @@ export function useChatgptConnect({
|
||||
} catch (err) {
|
||||
const code = refusalCode(err);
|
||||
setError({ messageKey: connectErrorKey(err), code });
|
||||
if (code === 'expired') restart();
|
||||
// The server takes a sign-in once, whatever it answers: any refusal it sent
|
||||
// used this one up. Offline the request never left, and a wrong address is refused before the flow is taken.
|
||||
if (code !== null && code !== 'offline' && code !== 'wrong_url') restart();
|
||||
} finally {
|
||||
finishing.current = false;
|
||||
setBusy(false);
|
||||
@@ -298,7 +300,7 @@ export function useChatgptConnect({
|
||||
useOnReturnToTab(opened, () => {
|
||||
if (pasted.trim() || busy) return;
|
||||
readClipboard((text) => {
|
||||
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField();
|
||||
if (flow && !callbackMatchesFlow(chatgptCallbackUrl(text) ?? text, flow.authorizeUrl)) focusField();
|
||||
else if (!paste(text)) focusField();
|
||||
}, focusField);
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { AiConnectionRow, AiConnectionsRepository } from '../../db/reposito
|
||||
import { readCappedJson } from '../../utils/cappedFetch';
|
||||
import { decodeJson, encodeJson } from '../../utils/json-column';
|
||||
import { safeFetch } from '../../utils/ssrfGuard';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { OidcService } from '../oidc/oidc.service';
|
||||
import { AI_AUTH_FLOW_TTL_MS, AiAuthFlowStore } from './ai-auth-flow.store';
|
||||
import { aiRefusal, providerRefusal } from './ai-connections.constants';
|
||||
@@ -64,16 +65,24 @@ const tokenResponseSchema = z.object({
|
||||
});
|
||||
type TokenResponse = z.infer<typeof tokenResponseSchema>;
|
||||
|
||||
/** The token endpoint said no, with its HTTP status and its error code. */
|
||||
/** The token endpoint said no, with its HTTP status, its error code and the reason it gave. */
|
||||
class TokenEndpointError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string | undefined,
|
||||
readonly description?: string,
|
||||
) {
|
||||
super(`token endpoint ${status}${code ? ` (${code})` : ''}`);
|
||||
super(`token endpoint ${status}${code ? ` (${code})` : ''}${description ? `: ${description}` : ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The OAuth `error_description` of a refusal, cut to one log line. */
|
||||
function errorDescriptionOf(body: unknown): string | undefined {
|
||||
if (!body || typeof body !== 'object') return undefined;
|
||||
const text = (body as Record<string, unknown>).error_description;
|
||||
return typeof text === 'string' && text ? text.slice(0, 300) : undefined;
|
||||
}
|
||||
|
||||
function randomToken(): string {
|
||||
return randomBytes(32).toString('base64url');
|
||||
}
|
||||
@@ -348,11 +357,14 @@ export class ChatgptAuthService {
|
||||
resource: RESOURCE,
|
||||
});
|
||||
} catch (err) {
|
||||
// A code that is refused has expired or was used already: the sign-in starts over.
|
||||
if (err instanceof TokenEndpointError && err.status === 400) {
|
||||
throw aiRefusal('expired', 'The sign-in took too long; start it again');
|
||||
if (!(err instanceof TokenEndpointError) || err.status === 0 || err.status >= 500) {
|
||||
throw aiRefusal('provider_unavailable', 'ChatGPT is not responding');
|
||||
}
|
||||
throw aiRefusal('provider_unavailable', 'ChatGPT is not responding');
|
||||
// The endpoint's own words, so an admin can tell an expired code from a client or redirect it refused.
|
||||
logWarn(`[AI] ChatGPT sign-in: the token endpoint refused the code, ${err.message}`);
|
||||
// Only invalid_grant means the code ran out or was used already; anything else is not the user's delay.
|
||||
if (err.code === 'invalid_grant') throw aiRefusal('expired', 'The sign-in took too long; start it again');
|
||||
throw aiRefusal('generic', `ChatGPT refused the sign-in (${err.code ?? `HTTP ${err.status}`})`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,7 +419,7 @@ export class ChatgptAuthService {
|
||||
throw new TokenEndpointError(0, undefined);
|
||||
}
|
||||
const json = await readCappedJson<unknown>(res, MAX_TOKEN_BYTES);
|
||||
if (!res.ok) throw new TokenEndpointError(res.status, errorCodeOf(json));
|
||||
if (!res.ok) throw new TokenEndpointError(res.status, errorCodeOf(json), errorDescriptionOf(json));
|
||||
const parsed = tokenResponseSchema.safeParse(json);
|
||||
if (!parsed.success) throw new TokenEndpointError(res.status, 'unreadable_answer');
|
||||
return parsed.data;
|
||||
|
||||
@@ -36,6 +36,11 @@ vi.mock('../../../../src/utils/ssrfGuard', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/utils/ssrfGuard')>()),
|
||||
safeFetch,
|
||||
}));
|
||||
const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() }));
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/nest/audit/audit-log.logger')>()),
|
||||
logWarn,
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
@@ -361,6 +366,33 @@ describe('finishing a sign-in', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('a refused code (#3196)', () => {
|
||||
it('CGPT-016: only invalid_grant reads as expired; another refusal names its OAuth error and is logged', async () => {
|
||||
const user = await caller();
|
||||
let flow = await started(user.id);
|
||||
safeFetch.mockResolvedValueOnce(
|
||||
tokenAnswer(400, { error: 'invalid_client', error_description: 'Client authentication failed' }),
|
||||
);
|
||||
const refused = await refusal(
|
||||
service().finish(user, flow.flowId, callbackUrl({ code: 'c', state: flow.state, client_id: 'oaiapp_x' })),
|
||||
);
|
||||
expect(refused.status).toBe(400);
|
||||
expect(refused.body).toMatchObject({ code: 'generic' });
|
||||
expect(refused.body.error).toContain('invalid_client');
|
||||
expect(logWarn.mock.calls.flat().join(' ')).toMatch(/invalid_client.*Client authentication failed/);
|
||||
|
||||
flow = await started(user.id);
|
||||
safeFetch.mockResolvedValueOnce(tokenAnswer(400, { error: 'invalid_grant' }));
|
||||
expect(
|
||||
(
|
||||
await refusal(
|
||||
service().finish(user, flow.flowId, callbackUrl({ code: 'c', state: flow.state, client_id: 'oaiapp_x' })),
|
||||
)
|
||||
).body,
|
||||
).toMatchObject({ code: 'expired' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('tokens', () => {
|
||||
it('CGPT-020: a token that is still good is used as it is', async () => {
|
||||
const { user } = await makeUser(orm());
|
||||
|
||||
Reference in New Issue
Block a user