ADAPT-Chase commited on
Commit
ccd9038
·
verified ·
1 Parent(s): b3315f2

Add files using upload-large-folder tool

Browse files
projects/ui/qwen-code/packages/core/src/ide/ide-client.test.ts ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import * as path from 'path';
9
+ import { IdeClient } from './ide-client.js';
10
+
11
+ describe('IdeClient.validateWorkspacePath', () => {
12
+ it('should return valid if cwd is a subpath of the IDE workspace path', () => {
13
+ const result = IdeClient.validateWorkspacePath(
14
+ '/Users/person/gemini-cli',
15
+ 'VS Code',
16
+ '/Users/person/gemini-cli/sub-dir',
17
+ );
18
+ expect(result.isValid).toBe(true);
19
+ });
20
+
21
+ it('should return invalid if GEMINI_CLI_IDE_WORKSPACE_PATH is undefined', () => {
22
+ const result = IdeClient.validateWorkspacePath(
23
+ undefined,
24
+ 'VS Code',
25
+ '/Users/person/gemini-cli/sub-dir',
26
+ );
27
+ expect(result.isValid).toBe(false);
28
+ expect(result.error).toContain('Failed to connect');
29
+ });
30
+
31
+ it('should return invalid if GEMINI_CLI_IDE_WORKSPACE_PATH is empty', () => {
32
+ const result = IdeClient.validateWorkspacePath(
33
+ '',
34
+ 'VS Code',
35
+ '/Users/person/gemini-cli/sub-dir',
36
+ );
37
+ expect(result.isValid).toBe(false);
38
+ expect(result.error).toContain('please open a workspace folder');
39
+ });
40
+
41
+ it('should return invalid if cwd is not within the IDE workspace path', () => {
42
+ const result = IdeClient.validateWorkspacePath(
43
+ '/some/other/path',
44
+ 'VS Code',
45
+ '/Users/person/gemini-cli/sub-dir',
46
+ );
47
+ expect(result.isValid).toBe(false);
48
+ expect(result.error).toContain('Directory mismatch');
49
+ });
50
+
51
+ it('should handle multiple workspace paths and return valid', () => {
52
+ const result = IdeClient.validateWorkspacePath(
53
+ ['/some/other/path', '/Users/person/gemini-cli'].join(path.delimiter),
54
+ 'VS Code',
55
+ '/Users/person/gemini-cli/sub-dir',
56
+ );
57
+ expect(result.isValid).toBe(true);
58
+ });
59
+
60
+ it('should return invalid if cwd is not in any of the multiple workspace paths', () => {
61
+ const result = IdeClient.validateWorkspacePath(
62
+ ['/some/other/path', '/another/path'].join(path.delimiter),
63
+ 'VS Code',
64
+ '/Users/person/gemini-cli/sub-dir',
65
+ );
66
+ expect(result.isValid).toBe(false);
67
+ expect(result.error).toContain('Directory mismatch');
68
+ });
69
+
70
+ it.skipIf(process.platform !== 'win32')('should handle windows paths', () => {
71
+ const result = IdeClient.validateWorkspacePath(
72
+ 'c:/some/other/path;d:/Users/person/gemini-cli',
73
+ 'VS Code',
74
+ 'd:/Users/person/gemini-cli/sub-dir',
75
+ );
76
+ expect(result.isValid).toBe(true);
77
+ });
78
+ });
projects/ui/qwen-code/packages/core/src/ide/ide-client.ts ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'node:fs';
8
+ import { isSubpath } from '../utils/paths.js';
9
+ import { detectIde, DetectedIde, getIdeInfo } from '../ide/detect-ide.js';
10
+ import {
11
+ ideContext,
12
+ IdeContextNotificationSchema,
13
+ IdeDiffAcceptedNotificationSchema,
14
+ IdeDiffClosedNotificationSchema,
15
+ CloseDiffResponseSchema,
16
+ DiffUpdateResult,
17
+ } from '../ide/ideContext.js';
18
+ import { getIdeProcessId } from './process-utils.js';
19
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
20
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
21
+ import * as os from 'node:os';
22
+ import * as path from 'node:path';
23
+ import { EnvHttpProxyAgent } from 'undici';
24
+
25
+ const logger = {
26
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
+ debug: (...args: any[]) => console.debug('[DEBUG] [IDEClient]', ...args),
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+ error: (...args: any[]) => console.error('[ERROR] [IDEClient]', ...args),
30
+ };
31
+
32
+ export type IDEConnectionState = {
33
+ status: IDEConnectionStatus;
34
+ details?: string; // User-facing
35
+ };
36
+
37
+ export enum IDEConnectionStatus {
38
+ Connected = 'connected',
39
+ Disconnected = 'disconnected',
40
+ Connecting = 'connecting',
41
+ }
42
+
43
+ function getRealPath(path: string): string {
44
+ try {
45
+ return fs.realpathSync(path);
46
+ } catch (_e) {
47
+ // If realpathSync fails, it might be because the path doesn't exist.
48
+ // In that case, we can fall back to the original path.
49
+ return path;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Manages the connection to and interaction with the IDE server.
55
+ */
56
+ export class IdeClient {
57
+ private static instance: IdeClient;
58
+ private client: Client | undefined = undefined;
59
+ private state: IDEConnectionState = {
60
+ status: IDEConnectionStatus.Disconnected,
61
+ details:
62
+ 'IDE integration is currently disabled. To enable it, run /ide enable.',
63
+ };
64
+ private readonly currentIde: DetectedIde | undefined;
65
+ private readonly currentIdeDisplayName: string | undefined;
66
+ private diffResponses = new Map<string, (result: DiffUpdateResult) => void>();
67
+ private statusListeners = new Set<(state: IDEConnectionState) => void>();
68
+
69
+ private constructor() {
70
+ this.currentIde = detectIde();
71
+ if (this.currentIde) {
72
+ this.currentIdeDisplayName = getIdeInfo(this.currentIde).displayName;
73
+ }
74
+ }
75
+
76
+ static getInstance(): IdeClient {
77
+ if (!IdeClient.instance) {
78
+ IdeClient.instance = new IdeClient();
79
+ }
80
+ return IdeClient.instance;
81
+ }
82
+
83
+ addStatusChangeListener(listener: (state: IDEConnectionState) => void) {
84
+ this.statusListeners.add(listener);
85
+ }
86
+
87
+ removeStatusChangeListener(listener: (state: IDEConnectionState) => void) {
88
+ this.statusListeners.delete(listener);
89
+ }
90
+
91
+ async connect(): Promise<void> {
92
+ if (!this.currentIde || !this.currentIdeDisplayName) {
93
+ this.setState(
94
+ IDEConnectionStatus.Disconnected,
95
+ `IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: ${Object.values(
96
+ DetectedIde,
97
+ )
98
+ .map((ide) => getIdeInfo(ide).displayName)
99
+ .join(', ')}`,
100
+ false,
101
+ );
102
+ return;
103
+ }
104
+
105
+ this.setState(IDEConnectionStatus.Connecting);
106
+
107
+ const ideInfoFromFile = await this.getIdeInfoFromFile();
108
+ const workspacePath =
109
+ ideInfoFromFile.workspacePath ??
110
+ process.env['QWEN_CODE_IDE_WORKSPACE_PATH'];
111
+
112
+ const { isValid, error } = IdeClient.validateWorkspacePath(
113
+ workspacePath,
114
+ this.currentIdeDisplayName,
115
+ process.cwd(),
116
+ );
117
+
118
+ if (!isValid) {
119
+ this.setState(IDEConnectionStatus.Disconnected, error, true);
120
+ return;
121
+ }
122
+
123
+ const portFromFile = ideInfoFromFile.port;
124
+ if (portFromFile) {
125
+ const connected = await this.establishConnection(portFromFile);
126
+ if (connected) {
127
+ return;
128
+ }
129
+ }
130
+
131
+ const portFromEnv = this.getPortFromEnv();
132
+ if (portFromEnv) {
133
+ const connected = await this.establishConnection(portFromEnv);
134
+ if (connected) {
135
+ return;
136
+ }
137
+ }
138
+
139
+ this.setState(
140
+ IDEConnectionStatus.Disconnected,
141
+ `Failed to connect to IDE companion extension for ${this.currentIdeDisplayName}. Please ensure the extension is running. To install the extension, run /ide install.`,
142
+ true,
143
+ );
144
+ }
145
+
146
+ /**
147
+ * A diff is accepted with any modifications if the user performs one of the
148
+ * following actions:
149
+ * - Clicks the checkbox icon in the IDE to accept
150
+ * - Runs `command+shift+p` > "Gemini CLI: Accept Diff in IDE" to accept
151
+ * - Selects "accept" in the CLI UI
152
+ * - Saves the file via `ctrl/command+s`
153
+ *
154
+ * A diff is rejected if the user performs one of the following actions:
155
+ * - Clicks the "x" icon in the IDE
156
+ * - Runs "Gemini CLI: Close Diff in IDE"
157
+ * - Selects "no" in the CLI UI
158
+ * - Closes the file
159
+ */
160
+ async openDiff(
161
+ filePath: string,
162
+ newContent?: string,
163
+ ): Promise<DiffUpdateResult> {
164
+ return new Promise<DiffUpdateResult>((resolve, reject) => {
165
+ this.diffResponses.set(filePath, resolve);
166
+ this.client
167
+ ?.callTool({
168
+ name: `openDiff`,
169
+ arguments: {
170
+ filePath,
171
+ newContent,
172
+ },
173
+ })
174
+ .catch((err) => {
175
+ logger.debug(`callTool for ${filePath} failed:`, err);
176
+ reject(err);
177
+ });
178
+ });
179
+ }
180
+
181
+ async closeDiff(filePath: string): Promise<string | undefined> {
182
+ try {
183
+ const result = await this.client?.callTool({
184
+ name: `closeDiff`,
185
+ arguments: {
186
+ filePath,
187
+ },
188
+ });
189
+
190
+ if (result) {
191
+ const parsed = CloseDiffResponseSchema.parse(result);
192
+ return parsed.content;
193
+ }
194
+ } catch (err) {
195
+ logger.debug(`callTool for ${filePath} failed:`, err);
196
+ }
197
+ return;
198
+ }
199
+
200
+ // Closes the diff. Instead of waiting for a notification,
201
+ // manually resolves the diff resolver as the desired outcome.
202
+ async resolveDiffFromCli(filePath: string, outcome: 'accepted' | 'rejected') {
203
+ const content = await this.closeDiff(filePath);
204
+ const resolver = this.diffResponses.get(filePath);
205
+ if (resolver) {
206
+ if (outcome === 'accepted') {
207
+ resolver({ status: 'accepted', content });
208
+ } else {
209
+ resolver({ status: 'rejected', content: undefined });
210
+ }
211
+ this.diffResponses.delete(filePath);
212
+ }
213
+ }
214
+
215
+ async disconnect() {
216
+ if (this.state.status === IDEConnectionStatus.Disconnected) {
217
+ return;
218
+ }
219
+ for (const filePath of this.diffResponses.keys()) {
220
+ await this.closeDiff(filePath);
221
+ }
222
+ this.diffResponses.clear();
223
+ this.setState(
224
+ IDEConnectionStatus.Disconnected,
225
+ 'IDE integration disabled. To enable it again, run /ide enable.',
226
+ );
227
+ this.client?.close();
228
+ }
229
+
230
+ getCurrentIde(): DetectedIde | undefined {
231
+ return this.currentIde;
232
+ }
233
+
234
+ getConnectionStatus(): IDEConnectionState {
235
+ return this.state;
236
+ }
237
+
238
+ getDetectedIdeDisplayName(): string | undefined {
239
+ return this.currentIdeDisplayName;
240
+ }
241
+
242
+ private setState(
243
+ status: IDEConnectionStatus,
244
+ details?: string,
245
+ logToConsole = false,
246
+ ) {
247
+ const isAlreadyDisconnected =
248
+ this.state.status === IDEConnectionStatus.Disconnected &&
249
+ status === IDEConnectionStatus.Disconnected;
250
+
251
+ // Only update details & log to console if the state wasn't already
252
+ // disconnected, so that the first detail message is preserved.
253
+ if (!isAlreadyDisconnected) {
254
+ this.state = { status, details };
255
+ for (const listener of this.statusListeners) {
256
+ listener(this.state);
257
+ }
258
+ if (details) {
259
+ if (logToConsole) {
260
+ logger.error(details);
261
+ } else {
262
+ // We only want to log disconnect messages to debug
263
+ // if they are not already being logged to the console.
264
+ logger.debug(details);
265
+ }
266
+ }
267
+ }
268
+
269
+ if (status === IDEConnectionStatus.Disconnected) {
270
+ ideContext.clearIdeContext();
271
+ }
272
+ }
273
+
274
+ static validateWorkspacePath(
275
+ ideWorkspacePath: string | undefined,
276
+ currentIdeDisplayName: string | undefined,
277
+ cwd: string,
278
+ ): { isValid: boolean; error?: string } {
279
+ if (ideWorkspacePath === undefined) {
280
+ return {
281
+ isValid: false,
282
+ error: `Failed to connect to IDE companion extension for ${currentIdeDisplayName}. Please ensure the extension is running. To install the extension, run /ide install.`,
283
+ };
284
+ }
285
+
286
+ if (ideWorkspacePath === '') {
287
+ return {
288
+ isValid: false,
289
+ error: `To use this feature, please open a workspace folder in ${currentIdeDisplayName} and try again.`,
290
+ };
291
+ }
292
+
293
+ const ideWorkspacePaths = ideWorkspacePath.split(path.delimiter);
294
+ const realCwd = getRealPath(cwd);
295
+ const isWithinWorkspace = ideWorkspacePaths.some((workspacePath) => {
296
+ const idePath = getRealPath(workspacePath);
297
+ return isSubpath(idePath, realCwd);
298
+ });
299
+
300
+ if (!isWithinWorkspace) {
301
+ return {
302
+ isValid: false,
303
+ error: `Directory mismatch. Qwen Code is running in a different location than the open workspace in ${currentIdeDisplayName}. Please run the CLI from one of the following directories: ${ideWorkspacePaths.join(
304
+ ', ',
305
+ )}`,
306
+ };
307
+ }
308
+ return { isValid: true };
309
+ }
310
+
311
+ private getPortFromEnv(): string | undefined {
312
+ const port = process.env['QWEN_CODE_IDE_SERVER_PORT'];
313
+ if (!port) {
314
+ return undefined;
315
+ }
316
+ return port;
317
+ }
318
+
319
+ private async getIdeInfoFromFile(): Promise<{
320
+ port?: string;
321
+ workspacePath?: string;
322
+ }> {
323
+ try {
324
+ const ideProcessId = await getIdeProcessId();
325
+ const portFile = path.join(
326
+ os.tmpdir(),
327
+ `qwen-code-ide-server-${ideProcessId}.json`,
328
+ );
329
+ const portFileContents = await fs.promises.readFile(portFile, 'utf8');
330
+ const ideInfo = JSON.parse(portFileContents);
331
+ return {
332
+ port: ideInfo?.port?.toString(),
333
+ workspacePath: ideInfo?.workspacePath,
334
+ };
335
+ } catch (_) {
336
+ return {};
337
+ }
338
+ }
339
+
340
+ private createProxyAwareFetch() {
341
+ // ignore proxy for 'localhost' by deafult to allow connecting to the ide mcp server
342
+ const existingNoProxy = process.env['NO_PROXY'] || '';
343
+ const agent = new EnvHttpProxyAgent({
344
+ noProxy: [existingNoProxy, 'localhost'].filter(Boolean).join(','),
345
+ });
346
+ const undiciPromise = import('undici');
347
+ return async (url: string | URL, init?: RequestInit): Promise<Response> => {
348
+ const { fetch: fetchFn } = await undiciPromise;
349
+ const fetchOptions: RequestInit & { dispatcher?: unknown } = {
350
+ ...init,
351
+ dispatcher: agent,
352
+ };
353
+ const options = fetchOptions as unknown as import('undici').RequestInit;
354
+ const response = await fetchFn(url, options);
355
+ return new Response(response.body as ReadableStream<unknown> | null, {
356
+ status: response.status,
357
+ statusText: response.statusText,
358
+ headers: response.headers,
359
+ });
360
+ };
361
+ }
362
+
363
+ private registerClientHandlers() {
364
+ if (!this.client) {
365
+ return;
366
+ }
367
+
368
+ this.client.setNotificationHandler(
369
+ IdeContextNotificationSchema,
370
+ (notification) => {
371
+ ideContext.setIdeContext(notification.params);
372
+ },
373
+ );
374
+ this.client.onerror = (_error) => {
375
+ this.setState(
376
+ IDEConnectionStatus.Disconnected,
377
+ `IDE connection error. The connection was lost unexpectedly. Please try reconnecting by running /ide enable`,
378
+ true,
379
+ );
380
+ };
381
+ this.client.onclose = () => {
382
+ this.setState(
383
+ IDEConnectionStatus.Disconnected,
384
+ `IDE connection error. The connection was lost unexpectedly. Please try reconnecting by running /ide enable`,
385
+ true,
386
+ );
387
+ };
388
+ this.client.setNotificationHandler(
389
+ IdeDiffAcceptedNotificationSchema,
390
+ (notification) => {
391
+ const { filePath, content } = notification.params;
392
+ const resolver = this.diffResponses.get(filePath);
393
+ if (resolver) {
394
+ resolver({ status: 'accepted', content });
395
+ this.diffResponses.delete(filePath);
396
+ } else {
397
+ logger.debug(`No resolver found for ${filePath}`);
398
+ }
399
+ },
400
+ );
401
+
402
+ this.client.setNotificationHandler(
403
+ IdeDiffClosedNotificationSchema,
404
+ (notification) => {
405
+ const { filePath } = notification.params;
406
+ const resolver = this.diffResponses.get(filePath);
407
+ if (resolver) {
408
+ resolver({ status: 'rejected', content: undefined });
409
+ this.diffResponses.delete(filePath);
410
+ } else {
411
+ logger.debug(`No resolver found for ${filePath}`);
412
+ }
413
+ },
414
+ );
415
+ }
416
+
417
+ private async establishConnection(port: string): Promise<boolean> {
418
+ let transport: StreamableHTTPClientTransport | undefined;
419
+ try {
420
+ this.client = new Client({
421
+ name: 'streamable-http-client',
422
+ // TODO(#3487): use the CLI version here.
423
+ version: '1.0.0',
424
+ });
425
+
426
+ transport = new StreamableHTTPClientTransport(
427
+ new URL(`http://${getIdeServerHost()}:${port}/mcp`),
428
+ {
429
+ fetch: this.createProxyAwareFetch(),
430
+ },
431
+ );
432
+
433
+ this.registerClientHandlers();
434
+
435
+ await this.client.connect(transport);
436
+ this.registerClientHandlers();
437
+ this.setState(IDEConnectionStatus.Connected);
438
+ return true;
439
+ } catch (_error) {
440
+ if (transport) {
441
+ try {
442
+ await transport.close();
443
+ } catch (closeError) {
444
+ logger.debug('Failed to close transport:', closeError);
445
+ }
446
+ }
447
+ return false;
448
+ }
449
+ }
450
+ }
451
+
452
+ function getIdeServerHost() {
453
+ const isInContainer =
454
+ fs.existsSync('/.dockerenv') || fs.existsSync('/run/.containerenv');
455
+ return isInContainer ? 'host.docker.internal' : 'localhost';
456
+ }
projects/ui/qwen-code/packages/core/src/ide/ide-installer.test.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import { getIdeInstaller, IdeInstaller } from './ide-installer.js';
9
+ import * as child_process from 'child_process';
10
+ import * as fs from 'fs';
11
+ import * as os from 'os';
12
+ import { DetectedIde } from './detect-ide.js';
13
+
14
+ vi.mock('child_process');
15
+ vi.mock('fs');
16
+ vi.mock('os');
17
+
18
+ describe('ide-installer', () => {
19
+ beforeEach(() => {
20
+ vi.spyOn(os, 'homedir').mockReturnValue('/home/user');
21
+ });
22
+
23
+ afterEach(() => {
24
+ vi.restoreAllMocks();
25
+ });
26
+
27
+ describe('getIdeInstaller', () => {
28
+ it('should return a VsCodeInstaller for "vscode"', () => {
29
+ const installer = getIdeInstaller(DetectedIde.VSCode);
30
+ expect(installer).not.toBeNull();
31
+ // A more specific check might be needed if we export the class
32
+ expect(installer).toBeInstanceOf(Object);
33
+ });
34
+
35
+ it('should return null for an unknown IDE', () => {
36
+ const installer = getIdeInstaller('unknown' as DetectedIde);
37
+ expect(installer).toBeNull();
38
+ });
39
+ });
40
+
41
+ describe('VsCodeInstaller', () => {
42
+ let installer: IdeInstaller;
43
+
44
+ beforeEach(() => {
45
+ // We get a new installer for each test to reset the find command logic
46
+ installer = getIdeInstaller(DetectedIde.VSCode)!;
47
+ vi.spyOn(child_process, 'execSync').mockImplementation(() => '');
48
+ vi.spyOn(fs, 'existsSync').mockReturnValue(false);
49
+ });
50
+
51
+ describe('install', () => {
52
+ it('should return a failure message if VS Code is not installed', async () => {
53
+ vi.spyOn(child_process, 'execSync').mockImplementation(() => {
54
+ throw new Error('Command not found');
55
+ });
56
+ vi.spyOn(fs, 'existsSync').mockReturnValue(false);
57
+ // Re-create the installer so it re-runs findVsCodeCommand
58
+ installer = getIdeInstaller(DetectedIde.VSCode)!;
59
+ const result = await installer.install();
60
+ expect(result.success).toBe(false);
61
+ expect(result.message).toContain('VS Code CLI not found');
62
+ });
63
+ });
64
+ });
65
+ });
projects/ui/qwen-code/packages/core/src/ide/ide-installer.ts ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as child_process from 'child_process';
8
+ import * as process from 'process';
9
+ import * as path from 'path';
10
+ import * as fs from 'fs';
11
+ import * as os from 'os';
12
+ import { DetectedIde } from './detect-ide.js';
13
+ import { QWEN_CODE_COMPANION_EXTENSION_NAME } from './constants.js';
14
+
15
+ const VSCODE_COMMAND = process.platform === 'win32' ? 'code.cmd' : 'code';
16
+
17
+ export interface IdeInstaller {
18
+ install(): Promise<InstallResult>;
19
+ }
20
+
21
+ export interface InstallResult {
22
+ success: boolean;
23
+ message: string;
24
+ }
25
+
26
+ async function findVsCodeCommand(): Promise<string | null> {
27
+ // 1. Check PATH first.
28
+ try {
29
+ if (process.platform === 'win32') {
30
+ const result = child_process
31
+ .execSync(`where.exe ${VSCODE_COMMAND}`)
32
+ .toString()
33
+ .trim();
34
+ // `where.exe` can return multiple paths. Return the first one.
35
+ const firstPath = result.split(/\r?\n/)[0];
36
+ if (firstPath) {
37
+ return firstPath;
38
+ }
39
+ } else {
40
+ child_process.execSync(`command -v ${VSCODE_COMMAND}`, {
41
+ stdio: 'ignore',
42
+ });
43
+ return VSCODE_COMMAND;
44
+ }
45
+ } catch {
46
+ // Not in PATH, continue to check common locations.
47
+ }
48
+
49
+ // 2. Check common installation locations.
50
+ const locations: string[] = [];
51
+ const platform = process.platform;
52
+ const homeDir = os.homedir();
53
+
54
+ if (platform === 'darwin') {
55
+ // macOS
56
+ locations.push(
57
+ '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code',
58
+ path.join(homeDir, 'Library/Application Support/Code/bin/code'),
59
+ );
60
+ } else if (platform === 'linux') {
61
+ // Linux
62
+ locations.push(
63
+ '/usr/share/code/bin/code',
64
+ '/snap/bin/code',
65
+ path.join(homeDir, '.local/share/code/bin/code'),
66
+ );
67
+ } else if (platform === 'win32') {
68
+ // Windows
69
+ locations.push(
70
+ path.join(
71
+ process.env['ProgramFiles'] || 'C:\\Program Files',
72
+ 'Microsoft VS Code',
73
+ 'bin',
74
+ 'code.cmd',
75
+ ),
76
+ path.join(
77
+ homeDir,
78
+ 'AppData',
79
+ 'Local',
80
+ 'Programs',
81
+ 'Microsoft VS Code',
82
+ 'bin',
83
+ 'code.cmd',
84
+ ),
85
+ );
86
+ }
87
+
88
+ for (const location of locations) {
89
+ if (fs.existsSync(location)) {
90
+ return location;
91
+ }
92
+ }
93
+
94
+ return null;
95
+ }
96
+
97
+ class VsCodeInstaller implements IdeInstaller {
98
+ private vsCodeCommand: Promise<string | null>;
99
+
100
+ constructor() {
101
+ this.vsCodeCommand = findVsCodeCommand();
102
+ }
103
+
104
+ async install(): Promise<InstallResult> {
105
+ const commandPath = await this.vsCodeCommand;
106
+ if (!commandPath) {
107
+ return {
108
+ success: false,
109
+ message: `VS Code CLI not found. Please ensure 'code' is in your system's PATH. For help, see https://code.visualstudio.com/docs/configure/command-line#_code-is-not-recognized-as-an-internal-or-external-command. You can also install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the VS Code marketplace.`,
110
+ };
111
+ }
112
+
113
+ const command = `"${commandPath}" --install-extension qwenlm.qwen-code-vscode-ide-companion --force`;
114
+ try {
115
+ child_process.execSync(command, { stdio: 'pipe' });
116
+ return {
117
+ success: true,
118
+ message: 'VS Code companion extension was installed successfully.',
119
+ };
120
+ } catch (_error) {
121
+ return {
122
+ success: false,
123
+ message: `Failed to install VS Code companion extension. Please try installing '${QWEN_CODE_COMPANION_EXTENSION_NAME}' manually from the VS Code extension marketplace.`,
124
+ };
125
+ }
126
+ }
127
+ }
128
+
129
+ export function getIdeInstaller(ide: DetectedIde): IdeInstaller | null {
130
+ switch (ide) {
131
+ case DetectedIde.VSCode:
132
+ return new VsCodeInstaller();
133
+ default:
134
+ return null;
135
+ }
136
+ }
projects/ui/qwen-code/packages/core/src/ide/ideContext.test.ts ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
8
+ import {
9
+ createIdeContextStore,
10
+ FileSchema,
11
+ IdeContextSchema,
12
+ } from './ideContext.js';
13
+
14
+ describe('ideContext', () => {
15
+ describe('createIdeContextStore', () => {
16
+ let ideContext: ReturnType<typeof createIdeContextStore>;
17
+
18
+ beforeEach(() => {
19
+ // Create a fresh, isolated instance for each test
20
+ ideContext = createIdeContextStore();
21
+ });
22
+
23
+ it('should return undefined initially for ide context', () => {
24
+ expect(ideContext.getIdeContext()).toBeUndefined();
25
+ });
26
+
27
+ it('should set and retrieve the ide context', () => {
28
+ const testFile = {
29
+ workspaceState: {
30
+ openFiles: [
31
+ {
32
+ path: '/path/to/test/file.ts',
33
+ isActive: true,
34
+ selectedText: '1234',
35
+ timestamp: 0,
36
+ },
37
+ ],
38
+ },
39
+ };
40
+
41
+ ideContext.setIdeContext(testFile);
42
+
43
+ const activeFile = ideContext.getIdeContext();
44
+ expect(activeFile).toEqual(testFile);
45
+ });
46
+
47
+ it('should update the ide context when called multiple times', () => {
48
+ const firstFile = {
49
+ workspaceState: {
50
+ openFiles: [
51
+ {
52
+ path: '/path/to/first.js',
53
+ isActive: true,
54
+ selectedText: '1234',
55
+ timestamp: 0,
56
+ },
57
+ ],
58
+ },
59
+ };
60
+ ideContext.setIdeContext(firstFile);
61
+
62
+ const secondFile = {
63
+ workspaceState: {
64
+ openFiles: [
65
+ {
66
+ path: '/path/to/second.py',
67
+ isActive: true,
68
+ cursor: { line: 20, character: 30 },
69
+ timestamp: 0,
70
+ },
71
+ ],
72
+ },
73
+ };
74
+ ideContext.setIdeContext(secondFile);
75
+
76
+ const activeFile = ideContext.getIdeContext();
77
+ expect(activeFile).toEqual(secondFile);
78
+ });
79
+
80
+ it('should handle empty string for file path', () => {
81
+ const testFile = {
82
+ workspaceState: {
83
+ openFiles: [
84
+ {
85
+ path: '',
86
+ isActive: true,
87
+ selectedText: '1234',
88
+ timestamp: 0,
89
+ },
90
+ ],
91
+ },
92
+ };
93
+ ideContext.setIdeContext(testFile);
94
+ expect(ideContext.getIdeContext()).toEqual(testFile);
95
+ });
96
+
97
+ it('should notify subscribers when ide context changes', () => {
98
+ const subscriber1 = vi.fn();
99
+ const subscriber2 = vi.fn();
100
+
101
+ ideContext.subscribeToIdeContext(subscriber1);
102
+ ideContext.subscribeToIdeContext(subscriber2);
103
+
104
+ const testFile = {
105
+ workspaceState: {
106
+ openFiles: [
107
+ {
108
+ path: '/path/to/subscribed.ts',
109
+ isActive: true,
110
+ cursor: { line: 15, character: 25 },
111
+ timestamp: 0,
112
+ },
113
+ ],
114
+ },
115
+ };
116
+ ideContext.setIdeContext(testFile);
117
+
118
+ expect(subscriber1).toHaveBeenCalledTimes(1);
119
+ expect(subscriber1).toHaveBeenCalledWith(testFile);
120
+ expect(subscriber2).toHaveBeenCalledTimes(1);
121
+ expect(subscriber2).toHaveBeenCalledWith(testFile);
122
+
123
+ // Test with another update
124
+ const newFile = {
125
+ workspaceState: {
126
+ openFiles: [
127
+ {
128
+ path: '/path/to/new.js',
129
+ isActive: true,
130
+ selectedText: '1234',
131
+ timestamp: 0,
132
+ },
133
+ ],
134
+ },
135
+ };
136
+ ideContext.setIdeContext(newFile);
137
+
138
+ expect(subscriber1).toHaveBeenCalledTimes(2);
139
+ expect(subscriber1).toHaveBeenCalledWith(newFile);
140
+ expect(subscriber2).toHaveBeenCalledTimes(2);
141
+ expect(subscriber2).toHaveBeenCalledWith(newFile);
142
+ });
143
+
144
+ it('should stop notifying a subscriber after unsubscribe', () => {
145
+ const subscriber1 = vi.fn();
146
+ const subscriber2 = vi.fn();
147
+
148
+ const unsubscribe1 = ideContext.subscribeToIdeContext(subscriber1);
149
+ ideContext.subscribeToIdeContext(subscriber2);
150
+
151
+ ideContext.setIdeContext({
152
+ workspaceState: {
153
+ openFiles: [
154
+ {
155
+ path: '/path/to/file1.txt',
156
+ isActive: true,
157
+ selectedText: '1234',
158
+ timestamp: 0,
159
+ },
160
+ ],
161
+ },
162
+ });
163
+ expect(subscriber1).toHaveBeenCalledTimes(1);
164
+ expect(subscriber2).toHaveBeenCalledTimes(1);
165
+
166
+ unsubscribe1();
167
+
168
+ ideContext.setIdeContext({
169
+ workspaceState: {
170
+ openFiles: [
171
+ {
172
+ path: '/path/to/file2.txt',
173
+ isActive: true,
174
+ selectedText: '1234',
175
+ timestamp: 0,
176
+ },
177
+ ],
178
+ },
179
+ });
180
+ expect(subscriber1).toHaveBeenCalledTimes(1); // Should not be called again
181
+ expect(subscriber2).toHaveBeenCalledTimes(2);
182
+ });
183
+
184
+ it('should clear the ide context', () => {
185
+ const testFile = {
186
+ workspaceState: {
187
+ openFiles: [
188
+ {
189
+ path: '/path/to/test/file.ts',
190
+ isActive: true,
191
+ selectedText: '1234',
192
+ timestamp: 0,
193
+ },
194
+ ],
195
+ },
196
+ };
197
+
198
+ ideContext.setIdeContext(testFile);
199
+
200
+ expect(ideContext.getIdeContext()).toEqual(testFile);
201
+
202
+ ideContext.clearIdeContext();
203
+
204
+ expect(ideContext.getIdeContext()).toBeUndefined();
205
+ });
206
+ });
207
+
208
+ describe('FileSchema', () => {
209
+ it('should validate a file with only required fields', () => {
210
+ const file = {
211
+ path: '/path/to/file.ts',
212
+ timestamp: 12345,
213
+ };
214
+ const result = FileSchema.safeParse(file);
215
+ expect(result.success).toBe(true);
216
+ });
217
+
218
+ it('should validate a file with all fields', () => {
219
+ const file = {
220
+ path: '/path/to/file.ts',
221
+ timestamp: 12345,
222
+ isActive: true,
223
+ selectedText: 'const x = 1;',
224
+ cursor: {
225
+ line: 10,
226
+ character: 20,
227
+ },
228
+ };
229
+ const result = FileSchema.safeParse(file);
230
+ expect(result.success).toBe(true);
231
+ });
232
+
233
+ it('should fail validation if path is missing', () => {
234
+ const file = {
235
+ timestamp: 12345,
236
+ };
237
+ const result = FileSchema.safeParse(file);
238
+ expect(result.success).toBe(false);
239
+ });
240
+
241
+ it('should fail validation if timestamp is missing', () => {
242
+ const file = {
243
+ path: '/path/to/file.ts',
244
+ };
245
+ const result = FileSchema.safeParse(file);
246
+ expect(result.success).toBe(false);
247
+ });
248
+ });
249
+
250
+ describe('IdeContextSchema', () => {
251
+ it('should validate an empty context', () => {
252
+ const context = {};
253
+ const result = IdeContextSchema.safeParse(context);
254
+ expect(result.success).toBe(true);
255
+ });
256
+
257
+ it('should validate a context with an empty workspaceState', () => {
258
+ const context = {
259
+ workspaceState: {},
260
+ };
261
+ const result = IdeContextSchema.safeParse(context);
262
+ expect(result.success).toBe(true);
263
+ });
264
+
265
+ it('should validate a context with an empty openFiles array', () => {
266
+ const context = {
267
+ workspaceState: {
268
+ openFiles: [],
269
+ },
270
+ };
271
+ const result = IdeContextSchema.safeParse(context);
272
+ expect(result.success).toBe(true);
273
+ });
274
+
275
+ it('should validate a context with a valid file', () => {
276
+ const context = {
277
+ workspaceState: {
278
+ openFiles: [
279
+ {
280
+ path: '/path/to/file.ts',
281
+ timestamp: 12345,
282
+ },
283
+ ],
284
+ },
285
+ };
286
+ const result = IdeContextSchema.safeParse(context);
287
+ expect(result.success).toBe(true);
288
+ });
289
+
290
+ it('should fail validation with an invalid file', () => {
291
+ const context = {
292
+ workspaceState: {
293
+ openFiles: [
294
+ {
295
+ timestamp: 12345, // path is missing
296
+ },
297
+ ],
298
+ },
299
+ };
300
+ const result = IdeContextSchema.safeParse(context);
301
+ expect(result.success).toBe(false);
302
+ });
303
+ });
304
+ });
projects/ui/qwen-code/packages/core/src/ide/ideContext.ts ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { z } from 'zod';
8
+
9
+ /**
10
+ * Zod schema for validating a file context from the IDE.
11
+ */
12
+ export const FileSchema = z.object({
13
+ path: z.string(),
14
+ timestamp: z.number(),
15
+ isActive: z.boolean().optional(),
16
+ selectedText: z.string().optional(),
17
+ cursor: z
18
+ .object({
19
+ line: z.number(),
20
+ character: z.number(),
21
+ })
22
+ .optional(),
23
+ });
24
+ export type File = z.infer<typeof FileSchema>;
25
+
26
+ export const IdeContextSchema = z.object({
27
+ workspaceState: z
28
+ .object({
29
+ openFiles: z.array(FileSchema).optional(),
30
+ })
31
+ .optional(),
32
+ });
33
+ export type IdeContext = z.infer<typeof IdeContextSchema>;
34
+
35
+ /**
36
+ * Zod schema for validating the 'ide/contextUpdate' notification from the IDE.
37
+ */
38
+ export const IdeContextNotificationSchema = z.object({
39
+ jsonrpc: z.literal('2.0'),
40
+ method: z.literal('ide/contextUpdate'),
41
+ params: IdeContextSchema,
42
+ });
43
+
44
+ export const IdeDiffAcceptedNotificationSchema = z.object({
45
+ jsonrpc: z.literal('2.0'),
46
+ method: z.literal('ide/diffAccepted'),
47
+ params: z.object({
48
+ filePath: z.string(),
49
+ content: z.string(),
50
+ }),
51
+ });
52
+
53
+ export const IdeDiffClosedNotificationSchema = z.object({
54
+ jsonrpc: z.literal('2.0'),
55
+ method: z.literal('ide/diffClosed'),
56
+ params: z.object({
57
+ filePath: z.string(),
58
+ content: z.string().optional(),
59
+ }),
60
+ });
61
+
62
+ export const CloseDiffResponseSchema = z
63
+ .object({
64
+ content: z
65
+ .array(
66
+ z.object({
67
+ text: z.string(),
68
+ type: z.literal('text'),
69
+ }),
70
+ )
71
+ .min(1),
72
+ })
73
+ .transform((val, ctx) => {
74
+ try {
75
+ const parsed = JSON.parse(val.content[0].text);
76
+ const innerSchema = z.object({ content: z.string().optional() });
77
+ const validationResult = innerSchema.safeParse(parsed);
78
+ if (!validationResult.success) {
79
+ validationResult.error.issues.forEach((issue) => ctx.addIssue(issue));
80
+ return z.NEVER;
81
+ }
82
+ return validationResult.data;
83
+ } catch (_) {
84
+ ctx.addIssue({
85
+ code: z.ZodIssueCode.custom,
86
+ message: 'Invalid JSON in text content',
87
+ });
88
+ return z.NEVER;
89
+ }
90
+ });
91
+
92
+ export type DiffUpdateResult =
93
+ | {
94
+ status: 'accepted';
95
+ content?: string;
96
+ }
97
+ | {
98
+ status: 'rejected';
99
+ content: undefined;
100
+ };
101
+
102
+ type IdeContextSubscriber = (ideContext: IdeContext | undefined) => void;
103
+
104
+ /**
105
+ * Creates a new store for managing the IDE's context.
106
+ * This factory function encapsulates the state and logic, allowing for the creation
107
+ * of isolated instances, which is particularly useful for testing.
108
+ *
109
+ * @returns An object with methods to interact with the IDE context.
110
+ */
111
+ export function createIdeContextStore() {
112
+ let ideContextState: IdeContext | undefined = undefined;
113
+ const subscribers = new Set<IdeContextSubscriber>();
114
+
115
+ /**
116
+ * Notifies all registered subscribers about the current IDE context.
117
+ */
118
+ function notifySubscribers(): void {
119
+ for (const subscriber of subscribers) {
120
+ subscriber(ideContextState);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Sets the IDE context and notifies all registered subscribers of the change.
126
+ * @param newIdeContext The new IDE context from the IDE.
127
+ */
128
+ function setIdeContext(newIdeContext: IdeContext): void {
129
+ ideContextState = newIdeContext;
130
+ notifySubscribers();
131
+ }
132
+
133
+ /**
134
+ * Clears the IDE context and notifies all registered subscribers of the change.
135
+ */
136
+ function clearIdeContext(): void {
137
+ ideContextState = undefined;
138
+ notifySubscribers();
139
+ }
140
+
141
+ /**
142
+ * Retrieves the current IDE context.
143
+ * @returns The `IdeContext` object if a file is active; otherwise, `undefined`.
144
+ */
145
+ function getIdeContext(): IdeContext | undefined {
146
+ return ideContextState;
147
+ }
148
+
149
+ /**
150
+ * Subscribes to changes in the IDE context.
151
+ *
152
+ * When the IDE context changes, the provided `subscriber` function will be called.
153
+ * Note: The subscriber is not called with the current value upon subscription.
154
+ *
155
+ * @param subscriber The function to be called when the IDE context changes.
156
+ * @returns A function that, when called, will unsubscribe the provided subscriber.
157
+ */
158
+ function subscribeToIdeContext(subscriber: IdeContextSubscriber): () => void {
159
+ subscribers.add(subscriber);
160
+ return () => {
161
+ subscribers.delete(subscriber);
162
+ };
163
+ }
164
+
165
+ return {
166
+ setIdeContext,
167
+ getIdeContext,
168
+ subscribeToIdeContext,
169
+ clearIdeContext,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * The default, shared instance of the IDE context store for the application.
175
+ */
176
+ export const ideContext = createIdeContextStore();
projects/ui/qwen-code/packages/core/src/ide/process-utils.ts ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { exec } from 'child_process';
8
+ import { promisify } from 'util';
9
+ import os from 'os';
10
+ import path from 'path';
11
+
12
+ const execAsync = promisify(exec);
13
+
14
+ const MAX_TRAVERSAL_DEPTH = 32;
15
+
16
+ /**
17
+ * Fetches the parent process ID and name for a given process ID.
18
+ *
19
+ * @param pid The process ID to inspect.
20
+ * @returns A promise that resolves to the parent's PID and name.
21
+ */
22
+ async function getParentProcessInfo(pid: number): Promise<{
23
+ parentPid: number;
24
+ name: string;
25
+ }> {
26
+ const platform = os.platform();
27
+ if (platform === 'win32') {
28
+ const command = `wmic process where "ProcessId=${pid}" get Name,ParentProcessId /value`;
29
+ const { stdout } = await execAsync(command);
30
+ const nameMatch = stdout.match(/Name=([^\n]*)/);
31
+ const processName = nameMatch ? nameMatch[1].trim() : '';
32
+ const ppidMatch = stdout.match(/ParentProcessId=(\d+)/);
33
+ const parentPid = ppidMatch ? parseInt(ppidMatch[1], 10) : 0;
34
+ return { parentPid, name: processName };
35
+ } else {
36
+ const command = `ps -o ppid=,command= -p ${pid}`;
37
+ const { stdout } = await execAsync(command);
38
+ const trimmedStdout = stdout.trim();
39
+ const ppidString = trimmedStdout.split(/\s+/)[0];
40
+ const parentPid = parseInt(ppidString, 10);
41
+ const fullCommand = trimmedStdout.substring(ppidString.length).trim();
42
+ const processName = path.basename(fullCommand.split(' ')[0]);
43
+ return { parentPid: isNaN(parentPid) ? 1 : parentPid, name: processName };
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Traverses the process tree on Unix-like systems to find the IDE process ID.
49
+ *
50
+ * The strategy is to find the shell process that spawned the CLI, and then
51
+ * find that shell's parent process (the IDE). To get the true IDE process,
52
+ * we traverse one level higher to get the grandparent.
53
+ *
54
+ * @returns A promise that resolves to the numeric PID.
55
+ */
56
+ async function getIdeProcessIdForUnix(): Promise<number> {
57
+ const shells = ['zsh', 'bash', 'sh', 'tcsh', 'csh', 'ksh', 'fish', 'dash'];
58
+ let currentPid = process.pid;
59
+
60
+ for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
61
+ try {
62
+ const { parentPid, name } = await getParentProcessInfo(currentPid);
63
+
64
+ const isShell = shells.some((shell) => name === shell);
65
+ if (isShell) {
66
+ // The direct parent of the shell is often a utility process (e.g. VS
67
+ // Code's `ptyhost` process). To get the true IDE process, we need to
68
+ // traverse one level higher to get the grandparent.
69
+ try {
70
+ const { parentPid: grandParentPid } =
71
+ await getParentProcessInfo(parentPid);
72
+ if (grandParentPid > 1) {
73
+ return grandParentPid;
74
+ }
75
+ } catch {
76
+ // Ignore if getting grandparent fails, we'll just use the parent pid.
77
+ }
78
+ return parentPid;
79
+ }
80
+
81
+ if (parentPid <= 1) {
82
+ break; // Reached the root
83
+ }
84
+ currentPid = parentPid;
85
+ } catch {
86
+ // Process in chain died
87
+ break;
88
+ }
89
+ }
90
+
91
+ console.error(
92
+ 'Failed to find shell process in the process tree. Falling back to top-level process, which may be inaccurate. If you see this, please file a bug via /bug.',
93
+ );
94
+ return currentPid;
95
+ }
96
+
97
+ /**
98
+ * Traverses the process tree on Windows to find the IDE process ID.
99
+ *
100
+ * The strategy is to find the grandchild of the root process.
101
+ *
102
+ * @returns A promise that resolves to the numeric PID.
103
+ */
104
+ async function getIdeProcessIdForWindows(): Promise<number> {
105
+ let currentPid = process.pid;
106
+
107
+ for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
108
+ try {
109
+ const { parentPid } = await getParentProcessInfo(currentPid);
110
+
111
+ if (parentPid > 0) {
112
+ try {
113
+ const { parentPid: grandParentPid } =
114
+ await getParentProcessInfo(parentPid);
115
+ if (grandParentPid === 0) {
116
+ // Found grandchild of root
117
+ return currentPid;
118
+ }
119
+ } catch {
120
+ // getting grandparent failed, proceed
121
+ }
122
+ }
123
+
124
+ if (parentPid <= 0) {
125
+ break; // Reached the root
126
+ }
127
+ currentPid = parentPid;
128
+ } catch {
129
+ // Process in chain died
130
+ break;
131
+ }
132
+ }
133
+ return currentPid;
134
+ }
135
+
136
+ /**
137
+ * Traverses up the process tree to find the process ID of the IDE.
138
+ *
139
+ * This function uses different strategies depending on the operating system
140
+ * to identify the main application process (e.g., the main VS Code window
141
+ * process).
142
+ *
143
+ * If the IDE process cannot be reliably identified, it will return the
144
+ * top-level ancestor process ID as a fallback.
145
+ *
146
+ * @returns A promise that resolves to the numeric PID of the IDE process.
147
+ * @throws Will throw an error if the underlying shell commands fail.
148
+ */
149
+ export async function getIdeProcessId(): Promise<number> {
150
+ const platform = os.platform();
151
+
152
+ if (platform === 'win32') {
153
+ return getIdeProcessIdForWindows();
154
+ }
155
+
156
+ return getIdeProcessIdForUnix();
157
+ }
projects/ui/qwen-code/packages/core/src/mcp/google-auth-provider.test.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GoogleAuth } from 'google-auth-library';
8
+ import { GoogleCredentialProvider } from './google-auth-provider.js';
9
+ import { vi, describe, beforeEach, it, expect, Mock } from 'vitest';
10
+ import { MCPServerConfig } from '../config/config.js';
11
+
12
+ vi.mock('google-auth-library');
13
+
14
+ describe('GoogleCredentialProvider', () => {
15
+ const validConfig = {
16
+ url: 'https://test.googleapis.com',
17
+ oauth: {
18
+ scopes: ['scope1', 'scope2'],
19
+ },
20
+ } as MCPServerConfig;
21
+
22
+ it('should throw an error if no scopes are provided', () => {
23
+ const config = {
24
+ url: 'https://test.googleapis.com',
25
+ } as MCPServerConfig;
26
+ expect(() => new GoogleCredentialProvider(config)).toThrow(
27
+ 'Scopes must be provided in the oauth config for Google Credentials provider',
28
+ );
29
+ });
30
+
31
+ it('should use scopes from the config if provided', () => {
32
+ new GoogleCredentialProvider(validConfig);
33
+ expect(GoogleAuth).toHaveBeenCalledWith({
34
+ scopes: ['scope1', 'scope2'],
35
+ });
36
+ });
37
+
38
+ it('should throw an error for a non-allowlisted host', () => {
39
+ const config = {
40
+ url: 'https://example.com',
41
+ oauth: {
42
+ scopes: ['scope1', 'scope2'],
43
+ },
44
+ } as MCPServerConfig;
45
+ expect(() => new GoogleCredentialProvider(config)).toThrow(
46
+ 'Host "example.com" is not an allowed host for Google Credential provider.',
47
+ );
48
+ });
49
+
50
+ it('should allow luci.app', () => {
51
+ const config = {
52
+ url: 'https://luci.app',
53
+ oauth: {
54
+ scopes: ['scope1', 'scope2'],
55
+ },
56
+ } as MCPServerConfig;
57
+ new GoogleCredentialProvider(config);
58
+ });
59
+
60
+ it('should allow sub.luci.app', () => {
61
+ const config = {
62
+ url: 'https://sub.luci.app',
63
+ oauth: {
64
+ scopes: ['scope1', 'scope2'],
65
+ },
66
+ } as MCPServerConfig;
67
+ new GoogleCredentialProvider(config);
68
+ });
69
+
70
+ it('should not allow googleapis.com without a subdomain', () => {
71
+ const config = {
72
+ url: 'https://googleapis.com',
73
+ oauth: {
74
+ scopes: ['scope1', 'scope2'],
75
+ },
76
+ } as MCPServerConfig;
77
+ expect(() => new GoogleCredentialProvider(config)).toThrow(
78
+ 'Host "googleapis.com" is not an allowed host for Google Credential provider.',
79
+ );
80
+ });
81
+
82
+ describe('with provider instance', () => {
83
+ let provider: GoogleCredentialProvider;
84
+
85
+ beforeEach(() => {
86
+ provider = new GoogleCredentialProvider(validConfig);
87
+ vi.clearAllMocks();
88
+ });
89
+
90
+ it('should return credentials', async () => {
91
+ const mockClient = {
92
+ getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
93
+ };
94
+ (GoogleAuth.prototype.getClient as Mock).mockResolvedValue(mockClient);
95
+
96
+ const credentials = await provider.tokens();
97
+
98
+ expect(credentials?.access_token).toBe('test-token');
99
+ });
100
+
101
+ it('should return undefined if access token is not available', async () => {
102
+ const mockClient = {
103
+ getAccessToken: vi.fn().mockResolvedValue({ token: null }),
104
+ };
105
+ (GoogleAuth.prototype.getClient as Mock).mockResolvedValue(mockClient);
106
+
107
+ const credentials = await provider.tokens();
108
+ expect(credentials).toBeUndefined();
109
+ });
110
+ });
111
+ });
projects/ui/qwen-code/packages/core/src/mcp/google-auth-provider.ts ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
8
+ import {
9
+ OAuthClientInformation,
10
+ OAuthClientInformationFull,
11
+ OAuthClientMetadata,
12
+ OAuthTokens,
13
+ } from '@modelcontextprotocol/sdk/shared/auth.js';
14
+ import { GoogleAuth } from 'google-auth-library';
15
+ import { MCPServerConfig } from '../config/config.js';
16
+
17
+ const ALLOWED_HOSTS = [/^.+\.googleapis\.com$/, /^(.*\.)?luci\.app$/];
18
+
19
+ export class GoogleCredentialProvider implements OAuthClientProvider {
20
+ private readonly auth: GoogleAuth;
21
+
22
+ // Properties required by OAuthClientProvider, with no-op values
23
+ readonly redirectUrl = '';
24
+ readonly clientMetadata: OAuthClientMetadata = {
25
+ client_name: 'Gemini CLI (Google ADC)',
26
+ redirect_uris: [],
27
+ grant_types: [],
28
+ response_types: [],
29
+ token_endpoint_auth_method: 'none',
30
+ };
31
+ private _clientInformation?: OAuthClientInformationFull;
32
+
33
+ constructor(private readonly config?: MCPServerConfig) {
34
+ const url = this.config?.url || this.config?.httpUrl;
35
+ if (!url) {
36
+ throw new Error(
37
+ 'URL must be provided in the config for Google Credentials provider',
38
+ );
39
+ }
40
+
41
+ const hostname = new URL(url).hostname;
42
+ if (!ALLOWED_HOSTS.some((pattern) => pattern.test(hostname))) {
43
+ throw new Error(
44
+ `Host "${hostname}" is not an allowed host for Google Credential provider.`,
45
+ );
46
+ }
47
+
48
+ const scopes = this.config?.oauth?.scopes;
49
+ if (!scopes || scopes.length === 0) {
50
+ throw new Error(
51
+ 'Scopes must be provided in the oauth config for Google Credentials provider',
52
+ );
53
+ }
54
+ this.auth = new GoogleAuth({
55
+ scopes,
56
+ });
57
+ }
58
+
59
+ clientInformation(): OAuthClientInformation | undefined {
60
+ return this._clientInformation;
61
+ }
62
+
63
+ saveClientInformation(clientInformation: OAuthClientInformationFull): void {
64
+ this._clientInformation = clientInformation;
65
+ }
66
+
67
+ async tokens(): Promise<OAuthTokens | undefined> {
68
+ const client = await this.auth.getClient();
69
+ const accessTokenResponse = await client.getAccessToken();
70
+
71
+ if (!accessTokenResponse.token) {
72
+ console.error('Failed to get access token from Google ADC');
73
+ return undefined;
74
+ }
75
+
76
+ const tokens: OAuthTokens = {
77
+ access_token: accessTokenResponse.token,
78
+ token_type: 'Bearer',
79
+ };
80
+ return tokens;
81
+ }
82
+
83
+ saveTokens(_tokens: OAuthTokens): void {
84
+ // No-op, ADC manages tokens.
85
+ }
86
+
87
+ redirectToAuthorization(_authorizationUrl: URL): void {
88
+ // No-op
89
+ }
90
+
91
+ saveCodeVerifier(_codeVerifier: string): void {
92
+ // No-op
93
+ }
94
+
95
+ codeVerifier(): string {
96
+ // No-op
97
+ return '';
98
+ }
99
+ }
projects/ui/qwen-code/packages/core/src/mcp/oauth-provider.test.ts ADDED
@@ -0,0 +1,957 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi } from 'vitest';
8
+
9
+ // Mock dependencies AT THE TOP
10
+ const mockOpenBrowserSecurely = vi.hoisted(() => vi.fn());
11
+ vi.mock('../utils/secure-browser-launcher.js', () => ({
12
+ openBrowserSecurely: mockOpenBrowserSecurely,
13
+ }));
14
+ vi.mock('node:crypto');
15
+ vi.mock('./oauth-token-storage.js');
16
+
17
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
18
+ import * as http from 'node:http';
19
+ import * as crypto from 'node:crypto';
20
+ import {
21
+ MCPOAuthProvider,
22
+ MCPOAuthConfig,
23
+ OAuthTokenResponse,
24
+ OAuthClientRegistrationResponse,
25
+ } from './oauth-provider.js';
26
+ import { MCPOAuthTokenStorage, MCPOAuthToken } from './oauth-token-storage.js';
27
+
28
+ // Mock fetch globally
29
+ const mockFetch = vi.fn();
30
+ global.fetch = mockFetch;
31
+
32
+ // Helper function to create mock fetch responses with proper headers
33
+ const createMockResponse = (options: {
34
+ ok: boolean;
35
+ status?: number;
36
+ contentType?: string;
37
+ text?: string | (() => Promise<string>);
38
+ json?: unknown | (() => Promise<unknown>);
39
+ }) => {
40
+ const response: {
41
+ ok: boolean;
42
+ status?: number;
43
+ headers: {
44
+ get: (name: string) => string | null;
45
+ };
46
+ text?: () => Promise<string>;
47
+ json?: () => Promise<unknown>;
48
+ } = {
49
+ ok: options.ok,
50
+ headers: {
51
+ get: (name: string) => {
52
+ if (name.toLowerCase() === 'content-type') {
53
+ return options.contentType || null;
54
+ }
55
+ return null;
56
+ },
57
+ },
58
+ };
59
+
60
+ if (options.status !== undefined) {
61
+ response.status = options.status;
62
+ }
63
+
64
+ if (options.text !== undefined) {
65
+ response.text =
66
+ typeof options.text === 'string'
67
+ ? () => Promise.resolve(options.text as string)
68
+ : (options.text as () => Promise<string>);
69
+ }
70
+
71
+ if (options.json !== undefined) {
72
+ response.json =
73
+ typeof options.json === 'function'
74
+ ? (options.json as () => Promise<unknown>)
75
+ : () => Promise.resolve(options.json);
76
+ }
77
+
78
+ return response;
79
+ };
80
+
81
+ // Define a reusable mock server with .listen, .close, and .on methods
82
+ const mockHttpServer = {
83
+ listen: vi.fn(),
84
+ close: vi.fn(),
85
+ on: vi.fn(),
86
+ };
87
+ vi.mock('node:http', () => ({
88
+ createServer: vi.fn(() => mockHttpServer),
89
+ }));
90
+
91
+ describe('MCPOAuthProvider', () => {
92
+ const mockConfig: MCPOAuthConfig = {
93
+ enabled: true,
94
+ clientId: 'test-client-id',
95
+ clientSecret: 'test-client-secret',
96
+ authorizationUrl: 'https://auth.example.com/authorize',
97
+ tokenUrl: 'https://auth.example.com/token',
98
+ scopes: ['read', 'write'],
99
+ redirectUri: 'http://localhost:7777/oauth/callback',
100
+ audiences: ['https://api.example.com'],
101
+ };
102
+
103
+ const mockToken: MCPOAuthToken = {
104
+ accessToken: 'access_token_123',
105
+ refreshToken: 'refresh_token_456',
106
+ tokenType: 'Bearer',
107
+ scope: 'read write',
108
+ expiresAt: Date.now() + 3600000,
109
+ };
110
+
111
+ const mockTokenResponse: OAuthTokenResponse = {
112
+ access_token: 'access_token_123',
113
+ token_type: 'Bearer',
114
+ expires_in: 3600,
115
+ refresh_token: 'refresh_token_456',
116
+ scope: 'read write',
117
+ };
118
+
119
+ beforeEach(() => {
120
+ vi.clearAllMocks();
121
+ mockOpenBrowserSecurely.mockClear();
122
+ vi.spyOn(console, 'log').mockImplementation(() => {});
123
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
124
+ vi.spyOn(console, 'error').mockImplementation(() => {});
125
+
126
+ // Mock crypto functions
127
+ vi.mocked(crypto.randomBytes).mockImplementation((size: number) => {
128
+ if (size === 32) return Buffer.from('code_verifier_mock_32_bytes_long');
129
+ if (size === 16) return Buffer.from('state_mock_16_by');
130
+ return Buffer.alloc(size);
131
+ });
132
+
133
+ vi.mocked(crypto.createHash).mockReturnValue({
134
+ update: vi.fn().mockReturnThis(),
135
+ digest: vi.fn().mockReturnValue('code_challenge_mock'),
136
+ } as unknown as crypto.Hash);
137
+
138
+ // Mock randomBytes to return predictable values for state
139
+ vi.mocked(crypto.randomBytes).mockImplementation((size) => {
140
+ if (size === 32) {
141
+ return Buffer.from('mock_code_verifier_32_bytes_long_string');
142
+ } else if (size === 16) {
143
+ return Buffer.from('mock_state_16_bytes');
144
+ }
145
+ return Buffer.alloc(size);
146
+ });
147
+
148
+ // Mock token storage
149
+ vi.mocked(MCPOAuthTokenStorage.saveToken).mockResolvedValue(undefined);
150
+ vi.mocked(MCPOAuthTokenStorage.getToken).mockResolvedValue(null);
151
+ });
152
+
153
+ afterEach(() => {
154
+ vi.restoreAllMocks();
155
+ });
156
+
157
+ describe('authenticate', () => {
158
+ it('should perform complete OAuth flow with PKCE', async () => {
159
+ // Mock HTTP server callback
160
+ let callbackHandler: unknown;
161
+ vi.mocked(http.createServer).mockImplementation((handler) => {
162
+ callbackHandler = handler;
163
+ return mockHttpServer as unknown as http.Server;
164
+ });
165
+
166
+ mockHttpServer.listen.mockImplementation((port, callback) => {
167
+ callback?.();
168
+ // Simulate OAuth callback
169
+ setTimeout(() => {
170
+ const mockReq = {
171
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
172
+ };
173
+ const mockRes = {
174
+ writeHead: vi.fn(),
175
+ end: vi.fn(),
176
+ };
177
+ (callbackHandler as (req: unknown, res: unknown) => void)(
178
+ mockReq,
179
+ mockRes,
180
+ );
181
+ }, 10);
182
+ });
183
+
184
+ // Mock token exchange
185
+ mockFetch.mockResolvedValueOnce(
186
+ createMockResponse({
187
+ ok: true,
188
+ contentType: 'application/json',
189
+ text: JSON.stringify(mockTokenResponse),
190
+ json: mockTokenResponse,
191
+ }),
192
+ );
193
+
194
+ const result = await MCPOAuthProvider.authenticate(
195
+ 'test-server',
196
+ mockConfig,
197
+ );
198
+
199
+ expect(result).toEqual({
200
+ accessToken: 'access_token_123',
201
+ refreshToken: 'refresh_token_456',
202
+ tokenType: 'Bearer',
203
+ scope: 'read write',
204
+ expiresAt: expect.any(Number),
205
+ });
206
+
207
+ expect(mockOpenBrowserSecurely).toHaveBeenCalledWith(
208
+ expect.stringContaining('authorize'),
209
+ );
210
+ expect(MCPOAuthTokenStorage.saveToken).toHaveBeenCalledWith(
211
+ 'test-server',
212
+ expect.objectContaining({ accessToken: 'access_token_123' }),
213
+ 'test-client-id',
214
+ 'https://auth.example.com/token',
215
+ undefined,
216
+ );
217
+ });
218
+
219
+ it('should handle OAuth discovery when no authorization URL provided', async () => {
220
+ // Use a mutable config object
221
+ const configWithoutAuth: MCPOAuthConfig = {
222
+ ...mockConfig,
223
+ clientId: 'test-client-id',
224
+ clientSecret: 'test-client-secret',
225
+ };
226
+ delete configWithoutAuth.authorizationUrl;
227
+ delete configWithoutAuth.tokenUrl;
228
+
229
+ const mockResourceMetadata = {
230
+ authorization_servers: ['https://discovered.auth.com'],
231
+ };
232
+
233
+ const mockAuthServerMetadata = {
234
+ authorization_endpoint: 'https://discovered.auth.com/authorize',
235
+ token_endpoint: 'https://discovered.auth.com/token',
236
+ scopes_supported: ['read', 'write'],
237
+ };
238
+
239
+ // Mock HEAD request for WWW-Authenticate check
240
+ mockFetch
241
+ .mockResolvedValueOnce(
242
+ createMockResponse({
243
+ ok: true,
244
+ status: 200,
245
+ }),
246
+ )
247
+ .mockResolvedValueOnce(
248
+ createMockResponse({
249
+ ok: true,
250
+ contentType: 'application/json',
251
+ text: JSON.stringify(mockResourceMetadata),
252
+ json: mockResourceMetadata,
253
+ }),
254
+ )
255
+ .mockResolvedValueOnce(
256
+ createMockResponse({
257
+ ok: true,
258
+ contentType: 'application/json',
259
+ text: JSON.stringify(mockAuthServerMetadata),
260
+ json: mockAuthServerMetadata,
261
+ }),
262
+ );
263
+
264
+ // Setup callback handler
265
+ let callbackHandler: unknown;
266
+ vi.mocked(http.createServer).mockImplementation((handler) => {
267
+ callbackHandler = handler;
268
+ return mockHttpServer as unknown as http.Server;
269
+ });
270
+
271
+ mockHttpServer.listen.mockImplementation((port, callback) => {
272
+ callback?.();
273
+ setTimeout(() => {
274
+ const mockReq = {
275
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
276
+ };
277
+ const mockRes = {
278
+ writeHead: vi.fn(),
279
+ end: vi.fn(),
280
+ };
281
+ (callbackHandler as (req: unknown, res: unknown) => void)(
282
+ mockReq,
283
+ mockRes,
284
+ );
285
+ }, 10);
286
+ });
287
+
288
+ // Mock token exchange with discovered endpoint
289
+ mockFetch.mockResolvedValueOnce(
290
+ createMockResponse({
291
+ ok: true,
292
+ contentType: 'application/json',
293
+ text: JSON.stringify(mockTokenResponse),
294
+ json: mockTokenResponse,
295
+ }),
296
+ );
297
+
298
+ const result = await MCPOAuthProvider.authenticate(
299
+ 'test-server',
300
+ configWithoutAuth,
301
+ 'https://api.example.com',
302
+ );
303
+
304
+ expect(result).toBeDefined();
305
+ expect(mockFetch).toHaveBeenCalledWith(
306
+ 'https://discovered.auth.com/token',
307
+ expect.objectContaining({
308
+ method: 'POST',
309
+ headers: expect.objectContaining({
310
+ 'Content-Type': 'application/x-www-form-urlencoded',
311
+ }),
312
+ }),
313
+ );
314
+ });
315
+
316
+ it('should perform dynamic client registration when no client ID provided', async () => {
317
+ const configWithoutClient = { ...mockConfig };
318
+ delete configWithoutClient.clientId;
319
+
320
+ const mockRegistrationResponse: OAuthClientRegistrationResponse = {
321
+ client_id: 'dynamic_client_id',
322
+ client_secret: 'dynamic_client_secret',
323
+ redirect_uris: ['http://localhost:7777/oauth/callback'],
324
+ grant_types: ['authorization_code', 'refresh_token'],
325
+ response_types: ['code'],
326
+ token_endpoint_auth_method: 'none',
327
+ };
328
+
329
+ const mockAuthServerMetadata = {
330
+ authorization_endpoint: 'https://auth.example.com/authorize',
331
+ token_endpoint: 'https://auth.example.com/token',
332
+ registration_endpoint: 'https://auth.example.com/register',
333
+ };
334
+
335
+ mockFetch
336
+ .mockResolvedValueOnce(
337
+ createMockResponse({
338
+ ok: true,
339
+ contentType: 'application/json',
340
+ text: JSON.stringify(mockAuthServerMetadata),
341
+ json: mockAuthServerMetadata,
342
+ }),
343
+ )
344
+ .mockResolvedValueOnce(
345
+ createMockResponse({
346
+ ok: true,
347
+ contentType: 'application/json',
348
+ text: JSON.stringify(mockRegistrationResponse),
349
+ json: mockRegistrationResponse,
350
+ }),
351
+ );
352
+
353
+ // Setup callback handler
354
+ let callbackHandler: unknown;
355
+ vi.mocked(http.createServer).mockImplementation((handler) => {
356
+ callbackHandler = handler;
357
+ return mockHttpServer as unknown as http.Server;
358
+ });
359
+
360
+ mockHttpServer.listen.mockImplementation((port, callback) => {
361
+ callback?.();
362
+ setTimeout(() => {
363
+ const mockReq = {
364
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
365
+ };
366
+ const mockRes = {
367
+ writeHead: vi.fn(),
368
+ end: vi.fn(),
369
+ };
370
+ (callbackHandler as (req: unknown, res: unknown) => void)(
371
+ mockReq,
372
+ mockRes,
373
+ );
374
+ }, 10);
375
+ });
376
+
377
+ // Mock token exchange
378
+ mockFetch.mockResolvedValueOnce(
379
+ createMockResponse({
380
+ ok: true,
381
+ contentType: 'application/json',
382
+ text: JSON.stringify(mockTokenResponse),
383
+ json: mockTokenResponse,
384
+ }),
385
+ );
386
+
387
+ const result = await MCPOAuthProvider.authenticate(
388
+ 'test-server',
389
+ configWithoutClient,
390
+ );
391
+
392
+ expect(result).toBeDefined();
393
+ expect(mockFetch).toHaveBeenCalledWith(
394
+ 'https://auth.example.com/register',
395
+ expect.objectContaining({
396
+ method: 'POST',
397
+ headers: { 'Content-Type': 'application/json' },
398
+ }),
399
+ );
400
+ });
401
+
402
+ it('should handle OAuth callback errors', async () => {
403
+ let callbackHandler: unknown;
404
+ vi.mocked(http.createServer).mockImplementation((handler) => {
405
+ callbackHandler = handler;
406
+ return mockHttpServer as unknown as http.Server;
407
+ });
408
+
409
+ mockHttpServer.listen.mockImplementation((port, callback) => {
410
+ callback?.();
411
+ setTimeout(() => {
412
+ const mockReq = {
413
+ url: '/oauth/callback?error=access_denied&error_description=User%20denied%20access',
414
+ };
415
+ const mockRes = {
416
+ writeHead: vi.fn(),
417
+ end: vi.fn(),
418
+ };
419
+ (callbackHandler as (req: unknown, res: unknown) => void)(
420
+ mockReq,
421
+ mockRes,
422
+ );
423
+ }, 10);
424
+ });
425
+
426
+ await expect(
427
+ MCPOAuthProvider.authenticate('test-server', mockConfig),
428
+ ).rejects.toThrow('OAuth error: access_denied');
429
+ });
430
+
431
+ it('should handle state mismatch in callback', async () => {
432
+ let callbackHandler: unknown;
433
+ vi.mocked(http.createServer).mockImplementation((handler) => {
434
+ callbackHandler = handler;
435
+ return mockHttpServer as unknown as http.Server;
436
+ });
437
+
438
+ mockHttpServer.listen.mockImplementation((port, callback) => {
439
+ callback?.();
440
+ setTimeout(() => {
441
+ const mockReq = {
442
+ url: '/oauth/callback?code=auth_code_123&state=wrong_state',
443
+ };
444
+ const mockRes = {
445
+ writeHead: vi.fn(),
446
+ end: vi.fn(),
447
+ };
448
+ (callbackHandler as (req: unknown, res: unknown) => void)(
449
+ mockReq,
450
+ mockRes,
451
+ );
452
+ }, 10);
453
+ });
454
+
455
+ await expect(
456
+ MCPOAuthProvider.authenticate('test-server', mockConfig),
457
+ ).rejects.toThrow('State mismatch - possible CSRF attack');
458
+ });
459
+
460
+ it('should handle token exchange failure', async () => {
461
+ let callbackHandler: unknown;
462
+ vi.mocked(http.createServer).mockImplementation((handler) => {
463
+ callbackHandler = handler;
464
+ return mockHttpServer as unknown as http.Server;
465
+ });
466
+
467
+ mockHttpServer.listen.mockImplementation((port, callback) => {
468
+ callback?.();
469
+ setTimeout(() => {
470
+ const mockReq = {
471
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
472
+ };
473
+ const mockRes = {
474
+ writeHead: vi.fn(),
475
+ end: vi.fn(),
476
+ };
477
+ (callbackHandler as (req: unknown, res: unknown) => void)(
478
+ mockReq,
479
+ mockRes,
480
+ );
481
+ }, 10);
482
+ });
483
+
484
+ mockFetch.mockResolvedValueOnce(
485
+ createMockResponse({
486
+ ok: false,
487
+ status: 400,
488
+ contentType: 'application/x-www-form-urlencoded',
489
+ text: 'error=invalid_grant&error_description=Invalid grant',
490
+ }),
491
+ );
492
+
493
+ await expect(
494
+ MCPOAuthProvider.authenticate('test-server', mockConfig),
495
+ ).rejects.toThrow('Token exchange failed: invalid_grant - Invalid grant');
496
+ });
497
+
498
+ it('should handle callback timeout', async () => {
499
+ vi.mocked(http.createServer).mockImplementation(
500
+ () => mockHttpServer as unknown as http.Server,
501
+ );
502
+
503
+ mockHttpServer.listen.mockImplementation((port, callback) => {
504
+ callback?.();
505
+ // Don't trigger callback - simulate timeout
506
+ });
507
+
508
+ // Mock setTimeout to trigger timeout immediately
509
+ const originalSetTimeout = global.setTimeout;
510
+ global.setTimeout = vi.fn((callback, delay) => {
511
+ if (delay === 5 * 60 * 1000) {
512
+ // 5 minute timeout
513
+ callback();
514
+ }
515
+ return originalSetTimeout(callback, 0);
516
+ }) as unknown as typeof setTimeout;
517
+
518
+ await expect(
519
+ MCPOAuthProvider.authenticate('test-server', mockConfig),
520
+ ).rejects.toThrow('OAuth callback timeout');
521
+
522
+ global.setTimeout = originalSetTimeout;
523
+ });
524
+ });
525
+
526
+ describe('refreshAccessToken', () => {
527
+ it('should refresh token successfully', async () => {
528
+ const refreshResponse = {
529
+ access_token: 'new_access_token',
530
+ token_type: 'Bearer',
531
+ expires_in: 3600,
532
+ refresh_token: 'new_refresh_token',
533
+ };
534
+
535
+ mockFetch.mockResolvedValueOnce(
536
+ createMockResponse({
537
+ ok: true,
538
+ contentType: 'application/json',
539
+ text: JSON.stringify(refreshResponse),
540
+ json: refreshResponse,
541
+ }),
542
+ );
543
+
544
+ const result = await MCPOAuthProvider.refreshAccessToken(
545
+ mockConfig,
546
+ 'old_refresh_token',
547
+ 'https://auth.example.com/token',
548
+ );
549
+
550
+ expect(result).toEqual(refreshResponse);
551
+ expect(mockFetch).toHaveBeenCalledWith(
552
+ 'https://auth.example.com/token',
553
+ expect.objectContaining({
554
+ method: 'POST',
555
+ headers: {
556
+ 'Content-Type': 'application/x-www-form-urlencoded',
557
+ Accept: 'application/json, application/x-www-form-urlencoded',
558
+ },
559
+ body: expect.stringContaining('grant_type=refresh_token'),
560
+ }),
561
+ );
562
+ });
563
+
564
+ it('should include client secret in refresh request when available', async () => {
565
+ mockFetch.mockResolvedValueOnce(
566
+ createMockResponse({
567
+ ok: true,
568
+ contentType: 'application/json',
569
+ text: JSON.stringify(mockTokenResponse),
570
+ json: mockTokenResponse,
571
+ }),
572
+ );
573
+
574
+ await MCPOAuthProvider.refreshAccessToken(
575
+ mockConfig,
576
+ 'refresh_token',
577
+ 'https://auth.example.com/token',
578
+ );
579
+
580
+ const fetchCall = mockFetch.mock.calls[0];
581
+ expect(fetchCall[1].body).toContain('client_secret=test-client-secret');
582
+ });
583
+
584
+ it('should handle refresh token failure', async () => {
585
+ mockFetch.mockResolvedValueOnce(
586
+ createMockResponse({
587
+ ok: false,
588
+ status: 400,
589
+ contentType: 'application/x-www-form-urlencoded',
590
+ text: 'error=invalid_request&error_description=Invalid refresh token',
591
+ }),
592
+ );
593
+
594
+ await expect(
595
+ MCPOAuthProvider.refreshAccessToken(
596
+ mockConfig,
597
+ 'invalid_refresh_token',
598
+ 'https://auth.example.com/token',
599
+ ),
600
+ ).rejects.toThrow(
601
+ 'Token refresh failed: invalid_request - Invalid refresh token',
602
+ );
603
+ });
604
+ });
605
+
606
+ describe('getValidToken', () => {
607
+ it('should return valid token when not expired', async () => {
608
+ const validCredentials = {
609
+ serverName: 'test-server',
610
+ token: mockToken,
611
+ clientId: 'test-client-id',
612
+ tokenUrl: 'https://auth.example.com/token',
613
+ updatedAt: Date.now(),
614
+ };
615
+
616
+ vi.mocked(MCPOAuthTokenStorage.getToken).mockResolvedValue(
617
+ validCredentials,
618
+ );
619
+ vi.mocked(MCPOAuthTokenStorage.isTokenExpired).mockReturnValue(false);
620
+
621
+ const result = await MCPOAuthProvider.getValidToken(
622
+ 'test-server',
623
+ mockConfig,
624
+ );
625
+
626
+ expect(result).toBe('access_token_123');
627
+ });
628
+
629
+ it('should refresh expired token and return new token', async () => {
630
+ const expiredCredentials = {
631
+ serverName: 'test-server',
632
+ token: { ...mockToken, expiresAt: Date.now() - 3600000 },
633
+ clientId: 'test-client-id',
634
+ tokenUrl: 'https://auth.example.com/token',
635
+ updatedAt: Date.now(),
636
+ };
637
+
638
+ vi.mocked(MCPOAuthTokenStorage.getToken).mockResolvedValue(
639
+ expiredCredentials,
640
+ );
641
+ vi.mocked(MCPOAuthTokenStorage.isTokenExpired).mockReturnValue(true);
642
+
643
+ const refreshResponse = {
644
+ access_token: 'new_access_token',
645
+ token_type: 'Bearer',
646
+ expires_in: 3600,
647
+ refresh_token: 'new_refresh_token',
648
+ };
649
+
650
+ mockFetch.mockResolvedValueOnce(
651
+ createMockResponse({
652
+ ok: true,
653
+ contentType: 'application/json',
654
+ text: JSON.stringify(refreshResponse),
655
+ json: refreshResponse,
656
+ }),
657
+ );
658
+
659
+ const result = await MCPOAuthProvider.getValidToken(
660
+ 'test-server',
661
+ mockConfig,
662
+ );
663
+
664
+ expect(result).toBe('new_access_token');
665
+ expect(MCPOAuthTokenStorage.saveToken).toHaveBeenCalledWith(
666
+ 'test-server',
667
+ expect.objectContaining({ accessToken: 'new_access_token' }),
668
+ 'test-client-id',
669
+ 'https://auth.example.com/token',
670
+ undefined,
671
+ );
672
+ });
673
+
674
+ it('should return null when no credentials exist', async () => {
675
+ vi.mocked(MCPOAuthTokenStorage.getToken).mockResolvedValue(null);
676
+
677
+ const result = await MCPOAuthProvider.getValidToken(
678
+ 'test-server',
679
+ mockConfig,
680
+ );
681
+
682
+ expect(result).toBeNull();
683
+ });
684
+
685
+ it('should handle refresh failure and remove invalid token', async () => {
686
+ const expiredCredentials = {
687
+ serverName: 'test-server',
688
+ token: { ...mockToken, expiresAt: Date.now() - 3600000 },
689
+ clientId: 'test-client-id',
690
+ tokenUrl: 'https://auth.example.com/token',
691
+ updatedAt: Date.now(),
692
+ };
693
+
694
+ vi.mocked(MCPOAuthTokenStorage.getToken).mockResolvedValue(
695
+ expiredCredentials,
696
+ );
697
+ vi.mocked(MCPOAuthTokenStorage.isTokenExpired).mockReturnValue(true);
698
+ vi.mocked(MCPOAuthTokenStorage.removeToken).mockResolvedValue(undefined);
699
+
700
+ mockFetch.mockResolvedValueOnce(
701
+ createMockResponse({
702
+ ok: false,
703
+ status: 400,
704
+ contentType: 'application/x-www-form-urlencoded',
705
+ text: 'error=invalid_request&error_description=Invalid refresh token',
706
+ }),
707
+ );
708
+
709
+ const result = await MCPOAuthProvider.getValidToken(
710
+ 'test-server',
711
+ mockConfig,
712
+ );
713
+
714
+ expect(result).toBeNull();
715
+ expect(MCPOAuthTokenStorage.removeToken).toHaveBeenCalledWith(
716
+ 'test-server',
717
+ );
718
+ expect(console.error).toHaveBeenCalledWith(
719
+ expect.stringContaining('Failed to refresh token'),
720
+ );
721
+ });
722
+
723
+ it('should return null for token without refresh capability', async () => {
724
+ const tokenWithoutRefresh = {
725
+ serverName: 'test-server',
726
+ token: {
727
+ ...mockToken,
728
+ refreshToken: undefined,
729
+ expiresAt: Date.now() - 3600000,
730
+ },
731
+ clientId: 'test-client-id',
732
+ tokenUrl: 'https://auth.example.com/token',
733
+ updatedAt: Date.now(),
734
+ };
735
+
736
+ vi.mocked(MCPOAuthTokenStorage.getToken).mockResolvedValue(
737
+ tokenWithoutRefresh,
738
+ );
739
+ vi.mocked(MCPOAuthTokenStorage.isTokenExpired).mockReturnValue(true);
740
+
741
+ const result = await MCPOAuthProvider.getValidToken(
742
+ 'test-server',
743
+ mockConfig,
744
+ );
745
+
746
+ expect(result).toBeNull();
747
+ });
748
+ });
749
+
750
+ describe('PKCE parameter generation', () => {
751
+ it('should generate valid PKCE parameters', async () => {
752
+ // Test is implicit in the authenticate flow tests, but we can verify
753
+ // the crypto mocks are called correctly
754
+ let callbackHandler: unknown;
755
+ vi.mocked(http.createServer).mockImplementation((handler) => {
756
+ callbackHandler = handler;
757
+ return mockHttpServer as unknown as http.Server;
758
+ });
759
+
760
+ mockHttpServer.listen.mockImplementation((port, callback) => {
761
+ callback?.();
762
+ setTimeout(() => {
763
+ const mockReq = {
764
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
765
+ };
766
+ const mockRes = {
767
+ writeHead: vi.fn(),
768
+ end: vi.fn(),
769
+ };
770
+ (callbackHandler as (req: unknown, res: unknown) => void)(
771
+ mockReq,
772
+ mockRes,
773
+ );
774
+ }, 10);
775
+ });
776
+
777
+ mockFetch.mockResolvedValueOnce(
778
+ createMockResponse({
779
+ ok: true,
780
+ contentType: 'application/json',
781
+ text: JSON.stringify(mockTokenResponse),
782
+ json: mockTokenResponse,
783
+ }),
784
+ );
785
+
786
+ await MCPOAuthProvider.authenticate('test-server', mockConfig);
787
+
788
+ expect(crypto.randomBytes).toHaveBeenCalledWith(32); // code verifier
789
+ expect(crypto.randomBytes).toHaveBeenCalledWith(16); // state
790
+ expect(crypto.createHash).toHaveBeenCalledWith('sha256');
791
+ });
792
+ });
793
+
794
+ describe('Authorization URL building', () => {
795
+ it('should build correct authorization URL with all parameters', async () => {
796
+ // Mock to capture the URL that would be opened
797
+ let capturedUrl: string | undefined;
798
+ mockOpenBrowserSecurely.mockImplementation((url: string) => {
799
+ capturedUrl = url;
800
+ return Promise.resolve();
801
+ });
802
+
803
+ let callbackHandler: unknown;
804
+ vi.mocked(http.createServer).mockImplementation((handler) => {
805
+ callbackHandler = handler;
806
+ return mockHttpServer as unknown as http.Server;
807
+ });
808
+
809
+ mockHttpServer.listen.mockImplementation((port, callback) => {
810
+ callback?.();
811
+ setTimeout(() => {
812
+ const mockReq = {
813
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
814
+ };
815
+ const mockRes = {
816
+ writeHead: vi.fn(),
817
+ end: vi.fn(),
818
+ };
819
+ (callbackHandler as (req: unknown, res: unknown) => void)(
820
+ mockReq,
821
+ mockRes,
822
+ );
823
+ }, 10);
824
+ });
825
+
826
+ mockFetch.mockResolvedValueOnce(
827
+ createMockResponse({
828
+ ok: true,
829
+ contentType: 'application/json',
830
+ text: JSON.stringify(mockTokenResponse),
831
+ json: mockTokenResponse,
832
+ }),
833
+ );
834
+
835
+ await MCPOAuthProvider.authenticate(
836
+ 'test-server',
837
+ mockConfig,
838
+ 'https://auth.example.com',
839
+ );
840
+
841
+ expect(capturedUrl).toBeDefined();
842
+ expect(capturedUrl!).toContain('response_type=code');
843
+ expect(capturedUrl!).toContain('client_id=test-client-id');
844
+ expect(capturedUrl!).toContain('code_challenge=code_challenge_mock');
845
+ expect(capturedUrl!).toContain('code_challenge_method=S256');
846
+ expect(capturedUrl!).toContain('scope=read+write');
847
+ expect(capturedUrl!).toContain('resource=https%3A%2F%2Fauth.example.com');
848
+ expect(capturedUrl!).toContain('audience=https%3A%2F%2Fapi.example.com');
849
+ });
850
+
851
+ it('should correctly append parameters to an authorization URL that already has query params', async () => {
852
+ // Mock to capture the URL that would be opened
853
+ let capturedUrl: string;
854
+ mockOpenBrowserSecurely.mockImplementation((url: string) => {
855
+ capturedUrl = url;
856
+ return Promise.resolve();
857
+ });
858
+
859
+ let callbackHandler: unknown;
860
+ vi.mocked(http.createServer).mockImplementation((handler) => {
861
+ callbackHandler = handler;
862
+ return mockHttpServer as unknown as http.Server;
863
+ });
864
+
865
+ mockHttpServer.listen.mockImplementation((port, callback) => {
866
+ callback?.();
867
+ setTimeout(() => {
868
+ const mockReq = {
869
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
870
+ };
871
+ const mockRes = {
872
+ writeHead: vi.fn(),
873
+ end: vi.fn(),
874
+ };
875
+ (callbackHandler as (req: unknown, res: unknown) => void)(
876
+ mockReq,
877
+ mockRes,
878
+ );
879
+ }, 10);
880
+ });
881
+
882
+ mockFetch.mockResolvedValueOnce(
883
+ createMockResponse({
884
+ ok: true,
885
+ contentType: 'application/json',
886
+ text: JSON.stringify(mockTokenResponse),
887
+ json: mockTokenResponse,
888
+ }),
889
+ );
890
+
891
+ const configWithParamsInUrl = {
892
+ ...mockConfig,
893
+ authorizationUrl: 'https://auth.example.com/authorize?audience=1234',
894
+ };
895
+
896
+ await MCPOAuthProvider.authenticate('test-server', configWithParamsInUrl);
897
+
898
+ const url = new URL(capturedUrl!);
899
+ expect(url.searchParams.get('audience')).toBe('1234');
900
+ expect(url.searchParams.get('client_id')).toBe('test-client-id');
901
+ expect(url.search.startsWith('?audience=1234&')).toBe(true);
902
+ });
903
+
904
+ it('should correctly append parameters to a URL with a fragment', async () => {
905
+ // Mock to capture the URL that would be opened
906
+ let capturedUrl: string;
907
+ mockOpenBrowserSecurely.mockImplementation((url: string) => {
908
+ capturedUrl = url;
909
+ return Promise.resolve();
910
+ });
911
+
912
+ let callbackHandler: unknown;
913
+ vi.mocked(http.createServer).mockImplementation((handler) => {
914
+ callbackHandler = handler;
915
+ return mockHttpServer as unknown as http.Server;
916
+ });
917
+
918
+ mockHttpServer.listen.mockImplementation((port, callback) => {
919
+ callback?.();
920
+ setTimeout(() => {
921
+ const mockReq = {
922
+ url: '/oauth/callback?code=auth_code_123&state=bW9ja19zdGF0ZV8xNl9ieXRlcw',
923
+ };
924
+ const mockRes = {
925
+ writeHead: vi.fn(),
926
+ end: vi.fn(),
927
+ };
928
+ (callbackHandler as (req: unknown, res: unknown) => void)(
929
+ mockReq,
930
+ mockRes,
931
+ );
932
+ }, 10);
933
+ });
934
+
935
+ mockFetch.mockResolvedValueOnce(
936
+ createMockResponse({
937
+ ok: true,
938
+ contentType: 'application/json',
939
+ text: JSON.stringify(mockTokenResponse),
940
+ json: mockTokenResponse,
941
+ }),
942
+ );
943
+
944
+ const configWithFragment = {
945
+ ...mockConfig,
946
+ authorizationUrl: 'https://auth.example.com/authorize#login',
947
+ };
948
+
949
+ await MCPOAuthProvider.authenticate('test-server', configWithFragment);
950
+
951
+ const url = new URL(capturedUrl!);
952
+ expect(url.searchParams.get('client_id')).toBe('test-client-id');
953
+ expect(url.hash).toBe('#login');
954
+ expect(url.pathname).toBe('/authorize');
955
+ });
956
+ });
957
+ });
projects/ui/qwen-code/packages/core/src/mcp/oauth-provider.ts ADDED
@@ -0,0 +1,894 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as http from 'node:http';
8
+ import * as crypto from 'node:crypto';
9
+ import { URL } from 'node:url';
10
+ import { openBrowserSecurely } from '../utils/secure-browser-launcher.js';
11
+ import { MCPOAuthToken, MCPOAuthTokenStorage } from './oauth-token-storage.js';
12
+ import { getErrorMessage } from '../utils/errors.js';
13
+ import { OAuthUtils } from './oauth-utils.js';
14
+
15
+ /**
16
+ * OAuth configuration for an MCP server.
17
+ */
18
+ export interface MCPOAuthConfig {
19
+ enabled?: boolean; // Whether OAuth is enabled for this server
20
+ clientId?: string;
21
+ clientSecret?: string;
22
+ authorizationUrl?: string;
23
+ tokenUrl?: string;
24
+ scopes?: string[];
25
+ audiences?: string[];
26
+ redirectUri?: string;
27
+ tokenParamName?: string; // For SSE connections, specifies the query parameter name for the token
28
+ }
29
+
30
+ /**
31
+ * OAuth authorization response.
32
+ */
33
+ export interface OAuthAuthorizationResponse {
34
+ code: string;
35
+ state: string;
36
+ }
37
+
38
+ /**
39
+ * OAuth token response from the authorization server.
40
+ */
41
+ export interface OAuthTokenResponse {
42
+ access_token: string;
43
+ token_type: string;
44
+ expires_in?: number;
45
+ refresh_token?: string;
46
+ scope?: string;
47
+ }
48
+
49
+ /**
50
+ * Dynamic client registration request.
51
+ */
52
+ export interface OAuthClientRegistrationRequest {
53
+ client_name: string;
54
+ redirect_uris: string[];
55
+ grant_types: string[];
56
+ response_types: string[];
57
+ token_endpoint_auth_method: string;
58
+ code_challenge_method?: string[];
59
+ scope?: string;
60
+ }
61
+
62
+ /**
63
+ * Dynamic client registration response.
64
+ */
65
+ export interface OAuthClientRegistrationResponse {
66
+ client_id: string;
67
+ client_secret?: string;
68
+ client_id_issued_at?: number;
69
+ client_secret_expires_at?: number;
70
+ redirect_uris: string[];
71
+ grant_types: string[];
72
+ response_types: string[];
73
+ token_endpoint_auth_method: string;
74
+ code_challenge_method?: string[];
75
+ scope?: string;
76
+ }
77
+
78
+ /**
79
+ * PKCE (Proof Key for Code Exchange) parameters.
80
+ */
81
+ interface PKCEParams {
82
+ codeVerifier: string;
83
+ codeChallenge: string;
84
+ state: string;
85
+ }
86
+
87
+ /**
88
+ * Provider for handling OAuth authentication for MCP servers.
89
+ */
90
+ export class MCPOAuthProvider {
91
+ private static readonly REDIRECT_PORT = 7777;
92
+ private static readonly REDIRECT_PATH = '/oauth/callback';
93
+ private static readonly HTTP_OK = 200;
94
+
95
+ /**
96
+ * Register a client dynamically with the OAuth server.
97
+ *
98
+ * @param registrationUrl The client registration endpoint URL
99
+ * @param config OAuth configuration
100
+ * @returns The registered client information
101
+ */
102
+ private static async registerClient(
103
+ registrationUrl: string,
104
+ config: MCPOAuthConfig,
105
+ ): Promise<OAuthClientRegistrationResponse> {
106
+ const redirectUri =
107
+ config.redirectUri ||
108
+ `http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`;
109
+
110
+ const registrationRequest: OAuthClientRegistrationRequest = {
111
+ client_name: 'Gemini CLI (Google ADC)',
112
+ redirect_uris: [redirectUri],
113
+ grant_types: ['authorization_code', 'refresh_token'],
114
+ response_types: ['code'],
115
+ token_endpoint_auth_method: 'none', // Public client
116
+ code_challenge_method: ['S256'],
117
+ scope: config.scopes?.join(' ') || '',
118
+ };
119
+
120
+ const response = await fetch(registrationUrl, {
121
+ method: 'POST',
122
+ headers: {
123
+ 'Content-Type': 'application/json',
124
+ },
125
+ body: JSON.stringify(registrationRequest),
126
+ });
127
+
128
+ if (!response.ok) {
129
+ const errorText = await response.text();
130
+ throw new Error(
131
+ `Client registration failed: ${response.status} ${response.statusText} - ${errorText}`,
132
+ );
133
+ }
134
+
135
+ return (await response.json()) as OAuthClientRegistrationResponse;
136
+ }
137
+
138
+ /**
139
+ * Discover OAuth configuration from an MCP server URL.
140
+ *
141
+ * @param mcpServerUrl The MCP server URL
142
+ * @returns OAuth configuration if discovered, null otherwise
143
+ */
144
+ private static async discoverOAuthFromMCPServer(
145
+ mcpServerUrl: string,
146
+ ): Promise<MCPOAuthConfig | null> {
147
+ // Use the full URL with path preserved for OAuth discovery
148
+ return OAuthUtils.discoverOAuthConfig(mcpServerUrl);
149
+ }
150
+
151
+ /**
152
+ * Generate PKCE parameters for OAuth flow.
153
+ *
154
+ * @returns PKCE parameters including code verifier, challenge, and state
155
+ */
156
+ private static generatePKCEParams(): PKCEParams {
157
+ // Generate code verifier (43-128 characters)
158
+ const codeVerifier = crypto.randomBytes(32).toString('base64url');
159
+
160
+ // Generate code challenge using SHA256
161
+ const codeChallenge = crypto
162
+ .createHash('sha256')
163
+ .update(codeVerifier)
164
+ .digest('base64url');
165
+
166
+ // Generate state for CSRF protection
167
+ const state = crypto.randomBytes(16).toString('base64url');
168
+
169
+ return { codeVerifier, codeChallenge, state };
170
+ }
171
+
172
+ /**
173
+ * Start a local HTTP server to handle OAuth callback.
174
+ *
175
+ * @param expectedState The state parameter to validate
176
+ * @returns Promise that resolves with the authorization code
177
+ */
178
+ private static async startCallbackServer(
179
+ expectedState: string,
180
+ ): Promise<OAuthAuthorizationResponse> {
181
+ return new Promise((resolve, reject) => {
182
+ const server = http.createServer(
183
+ async (req: http.IncomingMessage, res: http.ServerResponse) => {
184
+ try {
185
+ const url = new URL(
186
+ req.url!,
187
+ `http://localhost:${this.REDIRECT_PORT}`,
188
+ );
189
+
190
+ if (url.pathname !== this.REDIRECT_PATH) {
191
+ res.writeHead(404);
192
+ res.end('Not found');
193
+ return;
194
+ }
195
+
196
+ const code = url.searchParams.get('code');
197
+ const state = url.searchParams.get('state');
198
+ const error = url.searchParams.get('error');
199
+
200
+ if (error) {
201
+ res.writeHead(this.HTTP_OK, { 'Content-Type': 'text/html' });
202
+ res.end(`
203
+ <html>
204
+ <body>
205
+ <h1>Authentication Failed</h1>
206
+ <p>Error: ${(error as string).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</p>
207
+ <p>${((url.searchParams.get('error_description') || '') as string).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</p>
208
+ <p>You can close this window.</p>
209
+ </body>
210
+ </html>
211
+ `);
212
+ server.close();
213
+ reject(new Error(`OAuth error: ${error}`));
214
+ return;
215
+ }
216
+
217
+ if (!code || !state) {
218
+ res.writeHead(400);
219
+ res.end('Missing code or state parameter');
220
+ return;
221
+ }
222
+
223
+ if (state !== expectedState) {
224
+ res.writeHead(400);
225
+ res.end('Invalid state parameter');
226
+ server.close();
227
+ reject(new Error('State mismatch - possible CSRF attack'));
228
+ return;
229
+ }
230
+
231
+ // Send success response to browser
232
+ res.writeHead(this.HTTP_OK, { 'Content-Type': 'text/html' });
233
+ res.end(`
234
+ <html>
235
+ <body>
236
+ <h1>Authentication Successful!</h1>
237
+ <p>You can close this window and return to Gemini CLI.</p>
238
+ <script>window.close();</script>
239
+ </body>
240
+ </html>
241
+ `);
242
+
243
+ server.close();
244
+ resolve({ code, state });
245
+ } catch (error) {
246
+ server.close();
247
+ reject(error);
248
+ }
249
+ },
250
+ );
251
+
252
+ server.on('error', reject);
253
+ server.listen(this.REDIRECT_PORT, () => {
254
+ console.log(
255
+ `OAuth callback server listening on port ${this.REDIRECT_PORT}`,
256
+ );
257
+ });
258
+
259
+ // Timeout after 5 minutes
260
+ setTimeout(
261
+ () => {
262
+ server.close();
263
+ reject(new Error('OAuth callback timeout'));
264
+ },
265
+ 5 * 60 * 1000,
266
+ );
267
+ });
268
+ }
269
+
270
+ /**
271
+ * Build the authorization URL with PKCE parameters.
272
+ *
273
+ * @param config OAuth configuration
274
+ * @param pkceParams PKCE parameters
275
+ * @param mcpServerUrl The MCP server URL to use as the resource parameter
276
+ * @returns The authorization URL
277
+ */
278
+ private static buildAuthorizationUrl(
279
+ config: MCPOAuthConfig,
280
+ pkceParams: PKCEParams,
281
+ mcpServerUrl?: string,
282
+ ): string {
283
+ const redirectUri =
284
+ config.redirectUri ||
285
+ `http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`;
286
+
287
+ const params = new URLSearchParams({
288
+ client_id: config.clientId!,
289
+ response_type: 'code',
290
+ redirect_uri: redirectUri,
291
+ state: pkceParams.state,
292
+ code_challenge: pkceParams.codeChallenge,
293
+ code_challenge_method: 'S256',
294
+ });
295
+
296
+ if (config.scopes && config.scopes.length > 0) {
297
+ params.append('scope', config.scopes.join(' '));
298
+ }
299
+
300
+ if (config.audiences && config.audiences.length > 0) {
301
+ params.append('audience', config.audiences.join(' '));
302
+ }
303
+
304
+ // Add resource parameter for MCP OAuth spec compliance
305
+ // Only add if we have an MCP server URL (indicates MCP OAuth flow, not standard OAuth)
306
+ if (mcpServerUrl) {
307
+ try {
308
+ params.append(
309
+ 'resource',
310
+ OAuthUtils.buildResourceParameter(mcpServerUrl),
311
+ );
312
+ } catch (error) {
313
+ console.warn(
314
+ `Could not add resource parameter: ${getErrorMessage(error)}`,
315
+ );
316
+ }
317
+ }
318
+
319
+ const url = new URL(config.authorizationUrl!);
320
+ params.forEach((value, key) => {
321
+ url.searchParams.append(key, value);
322
+ });
323
+ return url.toString();
324
+ }
325
+
326
+ /**
327
+ * Exchange authorization code for tokens.
328
+ *
329
+ * @param config OAuth configuration
330
+ * @param code Authorization code
331
+ * @param codeVerifier PKCE code verifier
332
+ * @param mcpServerUrl The MCP server URL to use as the resource parameter
333
+ * @returns The token response
334
+ */
335
+ private static async exchangeCodeForToken(
336
+ config: MCPOAuthConfig,
337
+ code: string,
338
+ codeVerifier: string,
339
+ mcpServerUrl?: string,
340
+ ): Promise<OAuthTokenResponse> {
341
+ const redirectUri =
342
+ config.redirectUri ||
343
+ `http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`;
344
+
345
+ const params = new URLSearchParams({
346
+ grant_type: 'authorization_code',
347
+ code,
348
+ redirect_uri: redirectUri,
349
+ code_verifier: codeVerifier,
350
+ client_id: config.clientId!,
351
+ });
352
+
353
+ if (config.clientSecret) {
354
+ params.append('client_secret', config.clientSecret);
355
+ }
356
+
357
+ if (config.audiences && config.audiences.length > 0) {
358
+ params.append('audience', config.audiences.join(' '));
359
+ }
360
+
361
+ // Add resource parameter for MCP OAuth spec compliance
362
+ // Only add if we have an MCP server URL (indicates MCP OAuth flow, not standard OAuth)
363
+ if (mcpServerUrl) {
364
+ const resourceUrl = mcpServerUrl;
365
+ try {
366
+ params.append(
367
+ 'resource',
368
+ OAuthUtils.buildResourceParameter(resourceUrl),
369
+ );
370
+ } catch (error) {
371
+ console.warn(
372
+ `Could not add resource parameter: ${getErrorMessage(error)}`,
373
+ );
374
+ }
375
+ }
376
+
377
+ const response = await fetch(config.tokenUrl!, {
378
+ method: 'POST',
379
+ headers: {
380
+ 'Content-Type': 'application/x-www-form-urlencoded',
381
+ Accept: 'application/json, application/x-www-form-urlencoded',
382
+ },
383
+ body: params.toString(),
384
+ });
385
+
386
+ const responseText = await response.text();
387
+ const contentType = response.headers.get('content-type') || '';
388
+
389
+ if (!response.ok) {
390
+ // Try to parse error from form-urlencoded response
391
+ let errorMessage: string | null = null;
392
+ try {
393
+ const errorParams = new URLSearchParams(responseText);
394
+ const error = errorParams.get('error');
395
+ const errorDescription = errorParams.get('error_description');
396
+ if (error) {
397
+ errorMessage = `Token exchange failed: ${error} - ${errorDescription || 'No description'}`;
398
+ }
399
+ } catch {
400
+ // Fall back to raw error
401
+ }
402
+ throw new Error(
403
+ errorMessage ||
404
+ `Token exchange failed: ${response.status} - ${responseText}`,
405
+ );
406
+ }
407
+
408
+ // Log unexpected content types for debugging
409
+ if (
410
+ !contentType.includes('application/json') &&
411
+ !contentType.includes('application/x-www-form-urlencoded')
412
+ ) {
413
+ console.warn(
414
+ `Token endpoint returned unexpected content-type: ${contentType}. ` +
415
+ `Expected application/json or application/x-www-form-urlencoded. ` +
416
+ `Will attempt to parse response.`,
417
+ );
418
+ }
419
+
420
+ // Try to parse as JSON first, fall back to form-urlencoded
421
+ try {
422
+ return JSON.parse(responseText) as OAuthTokenResponse;
423
+ } catch {
424
+ // Parse form-urlencoded response
425
+ const tokenParams = new URLSearchParams(responseText);
426
+ const accessToken = tokenParams.get('access_token');
427
+ const tokenType = tokenParams.get('token_type') || 'Bearer';
428
+ const expiresIn = tokenParams.get('expires_in');
429
+ const refreshToken = tokenParams.get('refresh_token');
430
+ const scope = tokenParams.get('scope');
431
+
432
+ if (!accessToken) {
433
+ // Check for error in response
434
+ const error = tokenParams.get('error');
435
+ const errorDescription = tokenParams.get('error_description');
436
+ throw new Error(
437
+ `Token exchange failed: ${error || 'no_access_token'} - ${errorDescription || responseText}`,
438
+ );
439
+ }
440
+
441
+ return {
442
+ access_token: accessToken,
443
+ token_type: tokenType,
444
+ expires_in: expiresIn ? parseInt(expiresIn, 10) : undefined,
445
+ refresh_token: refreshToken || undefined,
446
+ scope: scope || undefined,
447
+ } as OAuthTokenResponse;
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Refresh an access token using a refresh token.
453
+ *
454
+ * @param config OAuth configuration
455
+ * @param refreshToken The refresh token
456
+ * @param tokenUrl The token endpoint URL
457
+ * @param mcpServerUrl The MCP server URL to use as the resource parameter
458
+ * @returns The new token response
459
+ */
460
+ static async refreshAccessToken(
461
+ config: MCPOAuthConfig,
462
+ refreshToken: string,
463
+ tokenUrl: string,
464
+ mcpServerUrl?: string,
465
+ ): Promise<OAuthTokenResponse> {
466
+ const params = new URLSearchParams({
467
+ grant_type: 'refresh_token',
468
+ refresh_token: refreshToken,
469
+ client_id: config.clientId!,
470
+ });
471
+
472
+ if (config.clientSecret) {
473
+ params.append('client_secret', config.clientSecret);
474
+ }
475
+
476
+ if (config.scopes && config.scopes.length > 0) {
477
+ params.append('scope', config.scopes.join(' '));
478
+ }
479
+
480
+ if (config.audiences && config.audiences.length > 0) {
481
+ params.append('audience', config.audiences.join(' '));
482
+ }
483
+
484
+ // Add resource parameter for MCP OAuth spec compliance
485
+ // Only add if we have an MCP server URL (indicates MCP OAuth flow, not standard OAuth)
486
+ if (mcpServerUrl) {
487
+ try {
488
+ params.append(
489
+ 'resource',
490
+ OAuthUtils.buildResourceParameter(mcpServerUrl),
491
+ );
492
+ } catch (error) {
493
+ console.warn(
494
+ `Could not add resource parameter: ${getErrorMessage(error)}`,
495
+ );
496
+ }
497
+ }
498
+
499
+ const response = await fetch(tokenUrl, {
500
+ method: 'POST',
501
+ headers: {
502
+ 'Content-Type': 'application/x-www-form-urlencoded',
503
+ Accept: 'application/json, application/x-www-form-urlencoded',
504
+ },
505
+ body: params.toString(),
506
+ });
507
+
508
+ const responseText = await response.text();
509
+ const contentType = response.headers.get('content-type') || '';
510
+
511
+ if (!response.ok) {
512
+ // Try to parse error from form-urlencoded response
513
+ let errorMessage: string | null = null;
514
+ try {
515
+ const errorParams = new URLSearchParams(responseText);
516
+ const error = errorParams.get('error');
517
+ const errorDescription = errorParams.get('error_description');
518
+ if (error) {
519
+ errorMessage = `Token refresh failed: ${error} - ${errorDescription || 'No description'}`;
520
+ }
521
+ } catch {
522
+ // Fall back to raw error
523
+ }
524
+ throw new Error(
525
+ errorMessage ||
526
+ `Token refresh failed: ${response.status} - ${responseText}`,
527
+ );
528
+ }
529
+
530
+ // Log unexpected content types for debugging
531
+ if (
532
+ !contentType.includes('application/json') &&
533
+ !contentType.includes('application/x-www-form-urlencoded')
534
+ ) {
535
+ console.warn(
536
+ `Token refresh endpoint returned unexpected content-type: ${contentType}. ` +
537
+ `Expected application/json or application/x-www-form-urlencoded. ` +
538
+ `Will attempt to parse response.`,
539
+ );
540
+ }
541
+
542
+ // Try to parse as JSON first, fall back to form-urlencoded
543
+ try {
544
+ return JSON.parse(responseText) as OAuthTokenResponse;
545
+ } catch {
546
+ // Parse form-urlencoded response
547
+ const tokenParams = new URLSearchParams(responseText);
548
+ const accessToken = tokenParams.get('access_token');
549
+ const tokenType = tokenParams.get('token_type') || 'Bearer';
550
+ const expiresIn = tokenParams.get('expires_in');
551
+ const refreshToken = tokenParams.get('refresh_token');
552
+ const scope = tokenParams.get('scope');
553
+
554
+ if (!accessToken) {
555
+ // Check for error in response
556
+ const error = tokenParams.get('error');
557
+ const errorDescription = tokenParams.get('error_description');
558
+ throw new Error(
559
+ `Token refresh failed: ${error || 'unknown_error'} - ${errorDescription || responseText}`,
560
+ );
561
+ }
562
+
563
+ return {
564
+ access_token: accessToken,
565
+ token_type: tokenType,
566
+ expires_in: expiresIn ? parseInt(expiresIn, 10) : undefined,
567
+ refresh_token: refreshToken || undefined,
568
+ scope: scope || undefined,
569
+ } as OAuthTokenResponse;
570
+ }
571
+ }
572
+
573
+ /**
574
+ * Perform the full OAuth authorization code flow with PKCE.
575
+ *
576
+ * @param serverName The name of the MCP server
577
+ * @param config OAuth configuration
578
+ * @param mcpServerUrl Optional MCP server URL for OAuth discovery
579
+ * @returns The obtained OAuth token
580
+ */
581
+ static async authenticate(
582
+ serverName: string,
583
+ config: MCPOAuthConfig,
584
+ mcpServerUrl?: string,
585
+ ): Promise<MCPOAuthToken> {
586
+ // If no authorization URL is provided, try to discover OAuth configuration
587
+ if (!config.authorizationUrl && mcpServerUrl) {
588
+ console.log(
589
+ 'No authorization URL provided, attempting OAuth discovery...',
590
+ );
591
+
592
+ // First check if the server requires authentication via WWW-Authenticate header
593
+ try {
594
+ const headers: HeadersInit = OAuthUtils.isSSEEndpoint(mcpServerUrl)
595
+ ? { Accept: 'text/event-stream' }
596
+ : { Accept: 'application/json' };
597
+
598
+ const response = await fetch(mcpServerUrl, {
599
+ method: 'HEAD',
600
+ headers,
601
+ });
602
+
603
+ if (response.status === 401 || response.status === 307) {
604
+ const wwwAuthenticate = response.headers.get('www-authenticate');
605
+
606
+ if (wwwAuthenticate) {
607
+ const discoveredConfig =
608
+ await OAuthUtils.discoverOAuthFromWWWAuthenticate(
609
+ wwwAuthenticate,
610
+ );
611
+ if (discoveredConfig) {
612
+ // Merge discovered config with existing config, preserving clientId and clientSecret
613
+ config = {
614
+ ...config,
615
+ authorizationUrl: discoveredConfig.authorizationUrl,
616
+ tokenUrl: discoveredConfig.tokenUrl,
617
+ scopes: discoveredConfig.scopes || config.scopes || [],
618
+ // Preserve existing client credentials
619
+ clientId: config.clientId,
620
+ clientSecret: config.clientSecret,
621
+ };
622
+ }
623
+ }
624
+ }
625
+ } catch (error) {
626
+ console.debug(
627
+ `Failed to check endpoint for authentication requirements: ${getErrorMessage(error)}`,
628
+ );
629
+ }
630
+
631
+ // If we still don't have OAuth config, try the standard discovery
632
+ if (!config.authorizationUrl) {
633
+ const discoveredConfig =
634
+ await this.discoverOAuthFromMCPServer(mcpServerUrl);
635
+ if (discoveredConfig) {
636
+ // Merge discovered config with existing config, preserving clientId and clientSecret
637
+ config = {
638
+ ...config,
639
+ authorizationUrl: discoveredConfig.authorizationUrl,
640
+ tokenUrl: discoveredConfig.tokenUrl,
641
+ scopes: discoveredConfig.scopes || config.scopes || [],
642
+ // Preserve existing client credentials
643
+ clientId: config.clientId,
644
+ clientSecret: config.clientSecret,
645
+ };
646
+ } else {
647
+ throw new Error(
648
+ 'Failed to discover OAuth configuration from MCP server',
649
+ );
650
+ }
651
+ }
652
+ }
653
+
654
+ // If no client ID is provided, try dynamic client registration
655
+ if (!config.clientId) {
656
+ // Extract server URL from authorization URL
657
+ if (!config.authorizationUrl) {
658
+ throw new Error(
659
+ 'Cannot perform dynamic registration without authorization URL',
660
+ );
661
+ }
662
+
663
+ const authUrl = new URL(config.authorizationUrl);
664
+ const serverUrl = `${authUrl.protocol}//${authUrl.host}`;
665
+
666
+ console.log(
667
+ 'No client ID provided, attempting dynamic client registration...',
668
+ );
669
+
670
+ // Get the authorization server metadata for registration
671
+ const authServerMetadataUrl = new URL(
672
+ '/.well-known/oauth-authorization-server',
673
+ serverUrl,
674
+ ).toString();
675
+
676
+ const authServerMetadata =
677
+ await OAuthUtils.fetchAuthorizationServerMetadata(
678
+ authServerMetadataUrl,
679
+ );
680
+ if (!authServerMetadata) {
681
+ throw new Error(
682
+ 'Failed to fetch authorization server metadata for client registration',
683
+ );
684
+ }
685
+
686
+ // Register client if registration endpoint is available
687
+ if (authServerMetadata.registration_endpoint) {
688
+ const clientRegistration = await this.registerClient(
689
+ authServerMetadata.registration_endpoint,
690
+ config,
691
+ );
692
+
693
+ config.clientId = clientRegistration.client_id;
694
+ if (clientRegistration.client_secret) {
695
+ config.clientSecret = clientRegistration.client_secret;
696
+ }
697
+
698
+ console.log('Dynamic client registration successful');
699
+ } else {
700
+ throw new Error(
701
+ 'No client ID provided and dynamic registration not supported',
702
+ );
703
+ }
704
+ }
705
+
706
+ // Validate configuration
707
+ if (!config.clientId || !config.authorizationUrl || !config.tokenUrl) {
708
+ throw new Error(
709
+ 'Missing required OAuth configuration after discovery and registration',
710
+ );
711
+ }
712
+
713
+ // Generate PKCE parameters
714
+ const pkceParams = this.generatePKCEParams();
715
+
716
+ // Build authorization URL
717
+ const authUrl = this.buildAuthorizationUrl(
718
+ config,
719
+ pkceParams,
720
+ mcpServerUrl,
721
+ );
722
+
723
+ console.log('\nOpening browser for OAuth authentication...');
724
+ console.log('If the browser does not open, please visit:');
725
+ console.log('');
726
+
727
+ // Get terminal width or default to 80
728
+ const terminalWidth = process.stdout.columns || 80;
729
+ const separatorLength = Math.min(terminalWidth - 2, 80);
730
+ const separator = '━'.repeat(separatorLength);
731
+
732
+ console.log(separator);
733
+ console.log(
734
+ 'COPY THE ENTIRE URL BELOW (select all text between the lines):',
735
+ );
736
+ console.log(separator);
737
+ console.log(authUrl);
738
+ console.log(separator);
739
+ console.log('');
740
+ console.log(
741
+ '💡 TIP: Triple-click to select the entire URL, then copy and paste it into your browser.',
742
+ );
743
+ console.log(
744
+ '⚠️ Make sure to copy the COMPLETE URL - it may wrap across multiple lines.',
745
+ );
746
+ console.log('');
747
+
748
+ // Start callback server
749
+ const callbackPromise = this.startCallbackServer(pkceParams.state);
750
+
751
+ // Open browser securely
752
+ try {
753
+ await openBrowserSecurely(authUrl);
754
+ } catch (error) {
755
+ console.warn(
756
+ 'Failed to open browser automatically:',
757
+ getErrorMessage(error),
758
+ );
759
+ }
760
+
761
+ // Wait for callback
762
+ const { code } = await callbackPromise;
763
+
764
+ console.log('\nAuthorization code received, exchanging for tokens...');
765
+
766
+ // Exchange code for tokens
767
+ const tokenResponse = await this.exchangeCodeForToken(
768
+ config,
769
+ code,
770
+ pkceParams.codeVerifier,
771
+ mcpServerUrl,
772
+ );
773
+
774
+ // Convert to our token format
775
+ if (!tokenResponse.access_token) {
776
+ throw new Error('No access token received from token endpoint');
777
+ }
778
+
779
+ const token: MCPOAuthToken = {
780
+ accessToken: tokenResponse.access_token,
781
+ tokenType: tokenResponse.token_type || 'Bearer',
782
+ refreshToken: tokenResponse.refresh_token,
783
+ scope: tokenResponse.scope,
784
+ };
785
+
786
+ if (tokenResponse.expires_in) {
787
+ token.expiresAt = Date.now() + tokenResponse.expires_in * 1000;
788
+ }
789
+
790
+ // Save token
791
+ try {
792
+ await MCPOAuthTokenStorage.saveToken(
793
+ serverName,
794
+ token,
795
+ config.clientId,
796
+ config.tokenUrl,
797
+ mcpServerUrl,
798
+ );
799
+ console.log('Authentication successful! Token saved.');
800
+
801
+ // Verify token was saved
802
+ const savedToken = await MCPOAuthTokenStorage.getToken(serverName);
803
+ if (savedToken && savedToken.token && savedToken.token.accessToken) {
804
+ const tokenPreview =
805
+ savedToken.token.accessToken.length > 20
806
+ ? `${savedToken.token.accessToken.substring(0, 20)}...`
807
+ : '[token]';
808
+ console.log(`Token verification successful: ${tokenPreview}`);
809
+ } else {
810
+ console.error(
811
+ 'Token verification failed: token not found or invalid after save',
812
+ );
813
+ }
814
+ } catch (saveError) {
815
+ console.error(`Failed to save token: ${getErrorMessage(saveError)}`);
816
+ throw saveError;
817
+ }
818
+
819
+ return token;
820
+ }
821
+
822
+ /**
823
+ * Get a valid access token for an MCP server, refreshing if necessary.
824
+ *
825
+ * @param serverName The name of the MCP server
826
+ * @param config OAuth configuration
827
+ * @returns A valid access token or null if not authenticated
828
+ */
829
+ static async getValidToken(
830
+ serverName: string,
831
+ config: MCPOAuthConfig,
832
+ ): Promise<string | null> {
833
+ console.debug(`Getting valid token for server: ${serverName}`);
834
+ const credentials = await MCPOAuthTokenStorage.getToken(serverName);
835
+
836
+ if (!credentials) {
837
+ console.debug(`No credentials found for server: ${serverName}`);
838
+ return null;
839
+ }
840
+
841
+ const { token } = credentials;
842
+ console.debug(
843
+ `Found token for server: ${serverName}, expired: ${MCPOAuthTokenStorage.isTokenExpired(token)}`,
844
+ );
845
+
846
+ // Check if token is expired
847
+ if (!MCPOAuthTokenStorage.isTokenExpired(token)) {
848
+ console.debug(`Returning valid token for server: ${serverName}`);
849
+ return token.accessToken;
850
+ }
851
+
852
+ // Try to refresh if we have a refresh token
853
+ if (token.refreshToken && config.clientId && credentials.tokenUrl) {
854
+ try {
855
+ console.log(`Refreshing expired token for MCP server: ${serverName}`);
856
+
857
+ const newTokenResponse = await this.refreshAccessToken(
858
+ config,
859
+ token.refreshToken,
860
+ credentials.tokenUrl,
861
+ credentials.mcpServerUrl,
862
+ );
863
+
864
+ // Update stored token
865
+ const newToken: MCPOAuthToken = {
866
+ accessToken: newTokenResponse.access_token,
867
+ tokenType: newTokenResponse.token_type,
868
+ refreshToken: newTokenResponse.refresh_token || token.refreshToken,
869
+ scope: newTokenResponse.scope || token.scope,
870
+ };
871
+
872
+ if (newTokenResponse.expires_in) {
873
+ newToken.expiresAt = Date.now() + newTokenResponse.expires_in * 1000;
874
+ }
875
+
876
+ await MCPOAuthTokenStorage.saveToken(
877
+ serverName,
878
+ newToken,
879
+ config.clientId,
880
+ credentials.tokenUrl,
881
+ credentials.mcpServerUrl,
882
+ );
883
+
884
+ return newToken.accessToken;
885
+ } catch (error) {
886
+ console.error(`Failed to refresh token: ${getErrorMessage(error)}`);
887
+ // Remove invalid token
888
+ await MCPOAuthTokenStorage.removeToken(serverName);
889
+ }
890
+ }
891
+
892
+ return null;
893
+ }
894
+ }
projects/ui/qwen-code/packages/core/src/mcp/oauth-token-storage.test.ts ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { promises as fs } from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import {
11
+ MCPOAuthTokenStorage,
12
+ MCPOAuthToken,
13
+ MCPOAuthCredentials,
14
+ } from './oauth-token-storage.js';
15
+
16
+ // Mock file system operations
17
+ vi.mock('node:fs', () => ({
18
+ promises: {
19
+ readFile: vi.fn(),
20
+ writeFile: vi.fn(),
21
+ mkdir: vi.fn(),
22
+ unlink: vi.fn(),
23
+ },
24
+ }));
25
+
26
+ vi.mock('node:os', () => ({
27
+ homedir: vi.fn(() => '/mock/home'),
28
+ }));
29
+
30
+ describe('MCPOAuthTokenStorage', () => {
31
+ const mockToken: MCPOAuthToken = {
32
+ accessToken: 'access_token_123',
33
+ refreshToken: 'refresh_token_456',
34
+ tokenType: 'Bearer',
35
+ scope: 'read write',
36
+ expiresAt: Date.now() + 3600000, // 1 hour from now
37
+ };
38
+
39
+ const mockCredentials: MCPOAuthCredentials = {
40
+ serverName: 'test-server',
41
+ token: mockToken,
42
+ clientId: 'test-client-id',
43
+ tokenUrl: 'https://auth.example.com/token',
44
+ updatedAt: Date.now(),
45
+ };
46
+
47
+ beforeEach(() => {
48
+ vi.clearAllMocks();
49
+ vi.spyOn(console, 'error').mockImplementation(() => {});
50
+ });
51
+
52
+ afterEach(() => {
53
+ vi.restoreAllMocks();
54
+ });
55
+
56
+ describe('loadTokens', () => {
57
+ it('should return empty map when token file does not exist', async () => {
58
+ vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
59
+
60
+ const tokens = await MCPOAuthTokenStorage.loadTokens();
61
+
62
+ expect(tokens.size).toBe(0);
63
+ expect(console.error).not.toHaveBeenCalled();
64
+ });
65
+
66
+ it('should load tokens from file successfully', async () => {
67
+ const tokensArray = [mockCredentials];
68
+ vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(tokensArray));
69
+
70
+ const tokens = await MCPOAuthTokenStorage.loadTokens();
71
+
72
+ expect(tokens.size).toBe(1);
73
+ expect(tokens.get('test-server')).toEqual(mockCredentials);
74
+ expect(fs.readFile).toHaveBeenCalledWith(
75
+ path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
76
+ 'utf-8',
77
+ );
78
+ });
79
+
80
+ it('should handle corrupted token file gracefully', async () => {
81
+ vi.mocked(fs.readFile).mockResolvedValue('invalid json');
82
+
83
+ const tokens = await MCPOAuthTokenStorage.loadTokens();
84
+
85
+ expect(tokens.size).toBe(0);
86
+ expect(console.error).toHaveBeenCalledWith(
87
+ expect.stringContaining('Failed to load MCP OAuth tokens'),
88
+ );
89
+ });
90
+
91
+ it('should handle file read errors other than ENOENT', async () => {
92
+ const error = new Error('Permission denied');
93
+ vi.mocked(fs.readFile).mockRejectedValue(error);
94
+
95
+ const tokens = await MCPOAuthTokenStorage.loadTokens();
96
+
97
+ expect(tokens.size).toBe(0);
98
+ expect(console.error).toHaveBeenCalledWith(
99
+ expect.stringContaining('Failed to load MCP OAuth tokens'),
100
+ );
101
+ });
102
+ });
103
+
104
+ describe('saveToken', () => {
105
+ it('should save token with restricted permissions', async () => {
106
+ vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
107
+ vi.mocked(fs.mkdir).mockResolvedValue(undefined);
108
+ vi.mocked(fs.writeFile).mockResolvedValue(undefined);
109
+
110
+ await MCPOAuthTokenStorage.saveToken(
111
+ 'test-server',
112
+ mockToken,
113
+ 'client-id',
114
+ 'https://token.url',
115
+ );
116
+
117
+ expect(fs.mkdir).toHaveBeenCalledWith(
118
+ path.join('/mock/home', '.gemini'),
119
+ { recursive: true },
120
+ );
121
+ expect(fs.writeFile).toHaveBeenCalledWith(
122
+ path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
123
+ expect.stringContaining('test-server'),
124
+ { mode: 0o600 },
125
+ );
126
+ });
127
+
128
+ it('should update existing token for same server', async () => {
129
+ const existingCredentials = {
130
+ ...mockCredentials,
131
+ serverName: 'existing-server',
132
+ };
133
+ vi.mocked(fs.readFile).mockResolvedValue(
134
+ JSON.stringify([existingCredentials]),
135
+ );
136
+ vi.mocked(fs.writeFile).mockResolvedValue(undefined);
137
+
138
+ const newToken = { ...mockToken, accessToken: 'new_access_token' };
139
+ await MCPOAuthTokenStorage.saveToken('existing-server', newToken);
140
+
141
+ const writeCall = vi.mocked(fs.writeFile).mock.calls[0];
142
+ const savedData = JSON.parse(writeCall[1] as string);
143
+
144
+ expect(savedData).toHaveLength(1);
145
+ expect(savedData[0].token.accessToken).toBe('new_access_token');
146
+ expect(savedData[0].serverName).toBe('existing-server');
147
+ });
148
+
149
+ it('should handle write errors gracefully', async () => {
150
+ vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
151
+ vi.mocked(fs.mkdir).mockResolvedValue(undefined);
152
+ const writeError = new Error('Disk full');
153
+ vi.mocked(fs.writeFile).mockRejectedValue(writeError);
154
+
155
+ await expect(
156
+ MCPOAuthTokenStorage.saveToken('test-server', mockToken),
157
+ ).rejects.toThrow('Disk full');
158
+
159
+ expect(console.error).toHaveBeenCalledWith(
160
+ expect.stringContaining('Failed to save MCP OAuth token'),
161
+ );
162
+ });
163
+ });
164
+
165
+ describe('getToken', () => {
166
+ it('should return token for existing server', async () => {
167
+ vi.mocked(fs.readFile).mockResolvedValue(
168
+ JSON.stringify([mockCredentials]),
169
+ );
170
+
171
+ const result = await MCPOAuthTokenStorage.getToken('test-server');
172
+
173
+ expect(result).toEqual(mockCredentials);
174
+ });
175
+
176
+ it('should return null for non-existent server', async () => {
177
+ vi.mocked(fs.readFile).mockResolvedValue(
178
+ JSON.stringify([mockCredentials]),
179
+ );
180
+
181
+ const result = await MCPOAuthTokenStorage.getToken('non-existent');
182
+
183
+ expect(result).toBeNull();
184
+ });
185
+
186
+ it('should return null when no tokens file exists', async () => {
187
+ vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
188
+
189
+ const result = await MCPOAuthTokenStorage.getToken('test-server');
190
+
191
+ expect(result).toBeNull();
192
+ });
193
+ });
194
+
195
+ describe('removeToken', () => {
196
+ it('should remove token for specific server', async () => {
197
+ const credentials1 = { ...mockCredentials, serverName: 'server1' };
198
+ const credentials2 = { ...mockCredentials, serverName: 'server2' };
199
+ vi.mocked(fs.readFile).mockResolvedValue(
200
+ JSON.stringify([credentials1, credentials2]),
201
+ );
202
+ vi.mocked(fs.writeFile).mockResolvedValue(undefined);
203
+
204
+ await MCPOAuthTokenStorage.removeToken('server1');
205
+
206
+ const writeCall = vi.mocked(fs.writeFile).mock.calls[0];
207
+ const savedData = JSON.parse(writeCall[1] as string);
208
+
209
+ expect(savedData).toHaveLength(1);
210
+ expect(savedData[0].serverName).toBe('server2');
211
+ });
212
+
213
+ it('should remove token file when no tokens remain', async () => {
214
+ vi.mocked(fs.readFile).mockResolvedValue(
215
+ JSON.stringify([mockCredentials]),
216
+ );
217
+ vi.mocked(fs.unlink).mockResolvedValue(undefined);
218
+
219
+ await MCPOAuthTokenStorage.removeToken('test-server');
220
+
221
+ expect(fs.unlink).toHaveBeenCalledWith(
222
+ path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
223
+ );
224
+ expect(fs.writeFile).not.toHaveBeenCalled();
225
+ });
226
+
227
+ it('should handle removal of non-existent token gracefully', async () => {
228
+ vi.mocked(fs.readFile).mockResolvedValue(
229
+ JSON.stringify([mockCredentials]),
230
+ );
231
+
232
+ await MCPOAuthTokenStorage.removeToken('non-existent');
233
+
234
+ expect(fs.writeFile).not.toHaveBeenCalled();
235
+ expect(fs.unlink).not.toHaveBeenCalled();
236
+ });
237
+
238
+ it('should handle file operation errors gracefully', async () => {
239
+ vi.mocked(fs.readFile).mockResolvedValue(
240
+ JSON.stringify([mockCredentials]),
241
+ );
242
+ vi.mocked(fs.unlink).mockRejectedValue(new Error('Permission denied'));
243
+
244
+ await MCPOAuthTokenStorage.removeToken('test-server');
245
+
246
+ expect(console.error).toHaveBeenCalledWith(
247
+ expect.stringContaining('Failed to remove MCP OAuth token'),
248
+ );
249
+ });
250
+ });
251
+
252
+ describe('isTokenExpired', () => {
253
+ it('should return false for token without expiry', () => {
254
+ const tokenWithoutExpiry = { ...mockToken };
255
+ delete tokenWithoutExpiry.expiresAt;
256
+
257
+ const result = MCPOAuthTokenStorage.isTokenExpired(tokenWithoutExpiry);
258
+
259
+ expect(result).toBe(false);
260
+ });
261
+
262
+ it('should return false for valid token', () => {
263
+ const futureToken = {
264
+ ...mockToken,
265
+ expiresAt: Date.now() + 3600000, // 1 hour from now
266
+ };
267
+
268
+ const result = MCPOAuthTokenStorage.isTokenExpired(futureToken);
269
+
270
+ expect(result).toBe(false);
271
+ });
272
+
273
+ it('should return true for expired token', () => {
274
+ const expiredToken = {
275
+ ...mockToken,
276
+ expiresAt: Date.now() - 3600000, // 1 hour ago
277
+ };
278
+
279
+ const result = MCPOAuthTokenStorage.isTokenExpired(expiredToken);
280
+
281
+ expect(result).toBe(true);
282
+ });
283
+
284
+ it('should return true for token expiring within buffer time', () => {
285
+ const soonToExpireToken = {
286
+ ...mockToken,
287
+ expiresAt: Date.now() + 60000, // 1 minute from now (within 5-minute buffer)
288
+ };
289
+
290
+ const result = MCPOAuthTokenStorage.isTokenExpired(soonToExpireToken);
291
+
292
+ expect(result).toBe(true);
293
+ });
294
+ });
295
+
296
+ describe('clearAllTokens', () => {
297
+ it('should remove token file successfully', async () => {
298
+ vi.mocked(fs.unlink).mockResolvedValue(undefined);
299
+
300
+ await MCPOAuthTokenStorage.clearAllTokens();
301
+
302
+ expect(fs.unlink).toHaveBeenCalledWith(
303
+ path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
304
+ );
305
+ });
306
+
307
+ it('should handle non-existent file gracefully', async () => {
308
+ vi.mocked(fs.unlink).mockRejectedValue({ code: 'ENOENT' });
309
+
310
+ await MCPOAuthTokenStorage.clearAllTokens();
311
+
312
+ expect(console.error).not.toHaveBeenCalled();
313
+ });
314
+
315
+ it('should handle other file errors gracefully', async () => {
316
+ vi.mocked(fs.unlink).mockRejectedValue(new Error('Permission denied'));
317
+
318
+ await MCPOAuthTokenStorage.clearAllTokens();
319
+
320
+ expect(console.error).toHaveBeenCalledWith(
321
+ expect.stringContaining('Failed to clear MCP OAuth tokens'),
322
+ );
323
+ });
324
+ });
325
+ });
projects/ui/qwen-code/packages/core/src/mcp/oauth-token-storage.ts ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { promises as fs } from 'node:fs';
8
+ import * as path from 'node:path';
9
+ import * as os from 'node:os';
10
+ import { getErrorMessage } from '../utils/errors.js';
11
+
12
+ /**
13
+ * Interface for MCP OAuth tokens.
14
+ */
15
+ export interface MCPOAuthToken {
16
+ accessToken: string;
17
+ refreshToken?: string;
18
+ expiresAt?: number;
19
+ tokenType: string;
20
+ scope?: string;
21
+ }
22
+
23
+ /**
24
+ * Interface for stored MCP OAuth credentials.
25
+ */
26
+ export interface MCPOAuthCredentials {
27
+ serverName: string;
28
+ token: MCPOAuthToken;
29
+ clientId?: string;
30
+ tokenUrl?: string;
31
+ mcpServerUrl?: string;
32
+ updatedAt: number;
33
+ }
34
+
35
+ /**
36
+ * Class for managing MCP OAuth token storage and retrieval.
37
+ */
38
+ export class MCPOAuthTokenStorage {
39
+ private static readonly TOKEN_FILE = 'mcp-oauth-tokens.json';
40
+ private static readonly CONFIG_DIR = '.gemini';
41
+
42
+ /**
43
+ * Get the path to the token storage file.
44
+ *
45
+ * @returns The full path to the token storage file
46
+ */
47
+ private static getTokenFilePath(): string {
48
+ const homeDir = os.homedir();
49
+ return path.join(homeDir, this.CONFIG_DIR, this.TOKEN_FILE);
50
+ }
51
+
52
+ /**
53
+ * Ensure the config directory exists.
54
+ */
55
+ private static async ensureConfigDir(): Promise<void> {
56
+ const configDir = path.dirname(this.getTokenFilePath());
57
+ await fs.mkdir(configDir, { recursive: true });
58
+ }
59
+
60
+ /**
61
+ * Load all stored MCP OAuth tokens.
62
+ *
63
+ * @returns A map of server names to credentials
64
+ */
65
+ static async loadTokens(): Promise<Map<string, MCPOAuthCredentials>> {
66
+ const tokenMap = new Map<string, MCPOAuthCredentials>();
67
+
68
+ try {
69
+ const tokenFile = this.getTokenFilePath();
70
+ const data = await fs.readFile(tokenFile, 'utf-8');
71
+ const tokens = JSON.parse(data) as MCPOAuthCredentials[];
72
+
73
+ for (const credential of tokens) {
74
+ tokenMap.set(credential.serverName, credential);
75
+ }
76
+ } catch (error) {
77
+ // File doesn't exist or is invalid, return empty map
78
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
79
+ console.error(
80
+ `Failed to load MCP OAuth tokens: ${getErrorMessage(error)}`,
81
+ );
82
+ }
83
+ }
84
+
85
+ return tokenMap;
86
+ }
87
+
88
+ /**
89
+ * Save a token for a specific MCP server.
90
+ *
91
+ * @param serverName The name of the MCP server
92
+ * @param token The OAuth token to save
93
+ * @param clientId Optional client ID used for this token
94
+ * @param tokenUrl Optional token URL used for this token
95
+ * @param mcpServerUrl Optional MCP server URL
96
+ */
97
+ static async saveToken(
98
+ serverName: string,
99
+ token: MCPOAuthToken,
100
+ clientId?: string,
101
+ tokenUrl?: string,
102
+ mcpServerUrl?: string,
103
+ ): Promise<void> {
104
+ await this.ensureConfigDir();
105
+
106
+ const tokens = await this.loadTokens();
107
+
108
+ const credential: MCPOAuthCredentials = {
109
+ serverName,
110
+ token,
111
+ clientId,
112
+ tokenUrl,
113
+ mcpServerUrl,
114
+ updatedAt: Date.now(),
115
+ };
116
+
117
+ tokens.set(serverName, credential);
118
+
119
+ const tokenArray = Array.from(tokens.values());
120
+ const tokenFile = this.getTokenFilePath();
121
+
122
+ try {
123
+ await fs.writeFile(
124
+ tokenFile,
125
+ JSON.stringify(tokenArray, null, 2),
126
+ { mode: 0o600 }, // Restrict file permissions
127
+ );
128
+ } catch (error) {
129
+ console.error(
130
+ `Failed to save MCP OAuth token: ${getErrorMessage(error)}`,
131
+ );
132
+ throw error;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Get a token for a specific MCP server.
138
+ *
139
+ * @param serverName The name of the MCP server
140
+ * @returns The stored credentials or null if not found
141
+ */
142
+ static async getToken(
143
+ serverName: string,
144
+ ): Promise<MCPOAuthCredentials | null> {
145
+ const tokens = await this.loadTokens();
146
+ return tokens.get(serverName) || null;
147
+ }
148
+
149
+ /**
150
+ * Remove a token for a specific MCP server.
151
+ *
152
+ * @param serverName The name of the MCP server
153
+ */
154
+ static async removeToken(serverName: string): Promise<void> {
155
+ const tokens = await this.loadTokens();
156
+
157
+ if (tokens.delete(serverName)) {
158
+ const tokenArray = Array.from(tokens.values());
159
+ const tokenFile = this.getTokenFilePath();
160
+
161
+ try {
162
+ if (tokenArray.length === 0) {
163
+ // Remove file if no tokens left
164
+ await fs.unlink(tokenFile);
165
+ } else {
166
+ await fs.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), {
167
+ mode: 0o600,
168
+ });
169
+ }
170
+ } catch (error) {
171
+ console.error(
172
+ `Failed to remove MCP OAuth token: ${getErrorMessage(error)}`,
173
+ );
174
+ }
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Check if a token is expired.
180
+ *
181
+ * @param token The token to check
182
+ * @returns True if the token is expired
183
+ */
184
+ static isTokenExpired(token: MCPOAuthToken): boolean {
185
+ if (!token.expiresAt) {
186
+ return false; // No expiry, assume valid
187
+ }
188
+
189
+ // Add a 5-minute buffer to account for clock skew
190
+ const bufferMs = 5 * 60 * 1000;
191
+ return Date.now() + bufferMs >= token.expiresAt;
192
+ }
193
+
194
+ /**
195
+ * Clear all stored MCP OAuth tokens.
196
+ */
197
+ static async clearAllTokens(): Promise<void> {
198
+ try {
199
+ const tokenFile = this.getTokenFilePath();
200
+ await fs.unlink(tokenFile);
201
+ } catch (error) {
202
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
203
+ console.error(
204
+ `Failed to clear MCP OAuth tokens: ${getErrorMessage(error)}`,
205
+ );
206
+ }
207
+ }
208
+ }
209
+ }
projects/ui/qwen-code/packages/core/src/mcp/oauth-utils.test.ts ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import {
9
+ OAuthUtils,
10
+ OAuthAuthorizationServerMetadata,
11
+ OAuthProtectedResourceMetadata,
12
+ } from './oauth-utils.js';
13
+
14
+ // Mock fetch globally
15
+ const mockFetch = vi.fn();
16
+ global.fetch = mockFetch;
17
+
18
+ describe('OAuthUtils', () => {
19
+ beforeEach(() => {
20
+ vi.clearAllMocks();
21
+ vi.spyOn(console, 'debug').mockImplementation(() => {});
22
+ vi.spyOn(console, 'error').mockImplementation(() => {});
23
+ vi.spyOn(console, 'log').mockImplementation(() => {});
24
+ });
25
+
26
+ afterEach(() => {
27
+ vi.restoreAllMocks();
28
+ });
29
+
30
+ describe('buildWellKnownUrls', () => {
31
+ it('should build standard root-based URLs by default', () => {
32
+ const urls = OAuthUtils.buildWellKnownUrls('https://example.com/mcp');
33
+ expect(urls.protectedResource).toBe(
34
+ 'https://example.com/.well-known/oauth-protected-resource',
35
+ );
36
+ expect(urls.authorizationServer).toBe(
37
+ 'https://example.com/.well-known/oauth-authorization-server',
38
+ );
39
+ });
40
+
41
+ it('should build path-based URLs when includePathSuffix is true', () => {
42
+ const urls = OAuthUtils.buildWellKnownUrls(
43
+ 'https://example.com/mcp',
44
+ true,
45
+ );
46
+ expect(urls.protectedResource).toBe(
47
+ 'https://example.com/.well-known/oauth-protected-resource/mcp',
48
+ );
49
+ expect(urls.authorizationServer).toBe(
50
+ 'https://example.com/.well-known/oauth-authorization-server/mcp',
51
+ );
52
+ });
53
+
54
+ it('should handle root path correctly', () => {
55
+ const urls = OAuthUtils.buildWellKnownUrls('https://example.com', true);
56
+ expect(urls.protectedResource).toBe(
57
+ 'https://example.com/.well-known/oauth-protected-resource',
58
+ );
59
+ expect(urls.authorizationServer).toBe(
60
+ 'https://example.com/.well-known/oauth-authorization-server',
61
+ );
62
+ });
63
+
64
+ it('should handle trailing slash in path', () => {
65
+ const urls = OAuthUtils.buildWellKnownUrls(
66
+ 'https://example.com/mcp/',
67
+ true,
68
+ );
69
+ expect(urls.protectedResource).toBe(
70
+ 'https://example.com/.well-known/oauth-protected-resource/mcp',
71
+ );
72
+ expect(urls.authorizationServer).toBe(
73
+ 'https://example.com/.well-known/oauth-authorization-server/mcp',
74
+ );
75
+ });
76
+ });
77
+
78
+ describe('fetchProtectedResourceMetadata', () => {
79
+ const mockResourceMetadata: OAuthProtectedResourceMetadata = {
80
+ resource: 'https://api.example.com',
81
+ authorization_servers: ['https://auth.example.com'],
82
+ bearer_methods_supported: ['header'],
83
+ };
84
+
85
+ it('should fetch protected resource metadata successfully', async () => {
86
+ mockFetch.mockResolvedValueOnce({
87
+ ok: true,
88
+ json: () => Promise.resolve(mockResourceMetadata),
89
+ });
90
+
91
+ const result = await OAuthUtils.fetchProtectedResourceMetadata(
92
+ 'https://example.com/.well-known/oauth-protected-resource',
93
+ );
94
+
95
+ expect(result).toEqual(mockResourceMetadata);
96
+ });
97
+
98
+ it('should return null when fetch fails', async () => {
99
+ mockFetch.mockResolvedValueOnce({
100
+ ok: false,
101
+ });
102
+
103
+ const result = await OAuthUtils.fetchProtectedResourceMetadata(
104
+ 'https://example.com/.well-known/oauth-protected-resource',
105
+ );
106
+
107
+ expect(result).toBeNull();
108
+ });
109
+ });
110
+
111
+ describe('fetchAuthorizationServerMetadata', () => {
112
+ const mockAuthServerMetadata: OAuthAuthorizationServerMetadata = {
113
+ issuer: 'https://auth.example.com',
114
+ authorization_endpoint: 'https://auth.example.com/authorize',
115
+ token_endpoint: 'https://auth.example.com/token',
116
+ scopes_supported: ['read', 'write'],
117
+ };
118
+
119
+ it('should fetch authorization server metadata successfully', async () => {
120
+ mockFetch.mockResolvedValueOnce({
121
+ ok: true,
122
+ json: () => Promise.resolve(mockAuthServerMetadata),
123
+ });
124
+
125
+ const result = await OAuthUtils.fetchAuthorizationServerMetadata(
126
+ 'https://auth.example.com/.well-known/oauth-authorization-server',
127
+ );
128
+
129
+ expect(result).toEqual(mockAuthServerMetadata);
130
+ });
131
+
132
+ it('should return null when fetch fails', async () => {
133
+ mockFetch.mockResolvedValueOnce({
134
+ ok: false,
135
+ });
136
+
137
+ const result = await OAuthUtils.fetchAuthorizationServerMetadata(
138
+ 'https://auth.example.com/.well-known/oauth-authorization-server',
139
+ );
140
+
141
+ expect(result).toBeNull();
142
+ });
143
+ });
144
+
145
+ describe('metadataToOAuthConfig', () => {
146
+ it('should convert metadata to OAuth config', () => {
147
+ const metadata: OAuthAuthorizationServerMetadata = {
148
+ issuer: 'https://auth.example.com',
149
+ authorization_endpoint: 'https://auth.example.com/authorize',
150
+ token_endpoint: 'https://auth.example.com/token',
151
+ scopes_supported: ['read', 'write'],
152
+ };
153
+
154
+ const config = OAuthUtils.metadataToOAuthConfig(metadata);
155
+
156
+ expect(config).toEqual({
157
+ authorizationUrl: 'https://auth.example.com/authorize',
158
+ tokenUrl: 'https://auth.example.com/token',
159
+ scopes: ['read', 'write'],
160
+ });
161
+ });
162
+
163
+ it('should handle empty scopes', () => {
164
+ const metadata: OAuthAuthorizationServerMetadata = {
165
+ issuer: 'https://auth.example.com',
166
+ authorization_endpoint: 'https://auth.example.com/authorize',
167
+ token_endpoint: 'https://auth.example.com/token',
168
+ };
169
+
170
+ const config = OAuthUtils.metadataToOAuthConfig(metadata);
171
+
172
+ expect(config.scopes).toEqual([]);
173
+ });
174
+ });
175
+
176
+ describe('parseWWWAuthenticateHeader', () => {
177
+ it('should parse resource metadata URI from WWW-Authenticate header', () => {
178
+ const header =
179
+ 'Bearer realm="example", resource_metadata="https://example.com/.well-known/oauth-protected-resource"';
180
+ const result = OAuthUtils.parseWWWAuthenticateHeader(header);
181
+ expect(result).toBe(
182
+ 'https://example.com/.well-known/oauth-protected-resource',
183
+ );
184
+ });
185
+
186
+ it('should return null when no resource metadata URI is found', () => {
187
+ const header = 'Bearer realm="example"';
188
+ const result = OAuthUtils.parseWWWAuthenticateHeader(header);
189
+ expect(result).toBeNull();
190
+ });
191
+ });
192
+
193
+ describe('extractBaseUrl', () => {
194
+ it('should extract base URL from MCP server URL', () => {
195
+ const result = OAuthUtils.extractBaseUrl('https://example.com/mcp/v1');
196
+ expect(result).toBe('https://example.com');
197
+ });
198
+
199
+ it('should handle URLs with ports', () => {
200
+ const result = OAuthUtils.extractBaseUrl(
201
+ 'https://example.com:8080/mcp/v1',
202
+ );
203
+ expect(result).toBe('https://example.com:8080');
204
+ });
205
+ });
206
+
207
+ describe('isSSEEndpoint', () => {
208
+ it('should return true for SSE endpoints', () => {
209
+ expect(OAuthUtils.isSSEEndpoint('https://example.com/sse')).toBe(true);
210
+ expect(OAuthUtils.isSSEEndpoint('https://example.com/api/v1/sse')).toBe(
211
+ true,
212
+ );
213
+ });
214
+
215
+ it('should return true for non-MCP endpoints', () => {
216
+ expect(OAuthUtils.isSSEEndpoint('https://example.com/api')).toBe(true);
217
+ });
218
+
219
+ it('should return false for MCP endpoints', () => {
220
+ expect(OAuthUtils.isSSEEndpoint('https://example.com/mcp')).toBe(false);
221
+ expect(OAuthUtils.isSSEEndpoint('https://example.com/api/mcp/v1')).toBe(
222
+ false,
223
+ );
224
+ });
225
+ });
226
+
227
+ describe('buildResourceParameter', () => {
228
+ it('should build resource parameter from endpoint URL', () => {
229
+ const result = OAuthUtils.buildResourceParameter(
230
+ 'https://example.com/oauth/token',
231
+ );
232
+ expect(result).toBe('https://example.com');
233
+ });
234
+
235
+ it('should handle URLs with ports', () => {
236
+ const result = OAuthUtils.buildResourceParameter(
237
+ 'https://example.com:8080/oauth/token',
238
+ );
239
+ expect(result).toBe('https://example.com:8080');
240
+ });
241
+ });
242
+ });
projects/ui/qwen-code/packages/core/src/mcp/oauth-utils.ts ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { MCPOAuthConfig } from './oauth-provider.js';
8
+ import { getErrorMessage } from '../utils/errors.js';
9
+
10
+ /**
11
+ * OAuth authorization server metadata as per RFC 8414.
12
+ */
13
+ export interface OAuthAuthorizationServerMetadata {
14
+ issuer: string;
15
+ authorization_endpoint: string;
16
+ token_endpoint: string;
17
+ token_endpoint_auth_methods_supported?: string[];
18
+ revocation_endpoint?: string;
19
+ revocation_endpoint_auth_methods_supported?: string[];
20
+ registration_endpoint?: string;
21
+ response_types_supported?: string[];
22
+ grant_types_supported?: string[];
23
+ code_challenge_methods_supported?: string[];
24
+ scopes_supported?: string[];
25
+ }
26
+
27
+ /**
28
+ * OAuth protected resource metadata as per RFC 9728.
29
+ */
30
+ export interface OAuthProtectedResourceMetadata {
31
+ resource: string;
32
+ authorization_servers?: string[];
33
+ bearer_methods_supported?: string[];
34
+ resource_documentation?: string;
35
+ resource_signing_alg_values_supported?: string[];
36
+ resource_encryption_alg_values_supported?: string[];
37
+ resource_encryption_enc_values_supported?: string[];
38
+ }
39
+
40
+ /**
41
+ * Utility class for common OAuth operations.
42
+ */
43
+ export class OAuthUtils {
44
+ /**
45
+ * Construct well-known OAuth endpoint URLs.
46
+ * By default, uses standard root-based well-known URLs.
47
+ * If includePathSuffix is true, appends any path from the base URL to the well-known endpoints.
48
+ */
49
+ static buildWellKnownUrls(baseUrl: string, includePathSuffix = false) {
50
+ const serverUrl = new URL(baseUrl);
51
+ const base = `${serverUrl.protocol}//${serverUrl.host}`;
52
+
53
+ if (!includePathSuffix) {
54
+ // Standard discovery: use root-based well-known URLs
55
+ return {
56
+ protectedResource: new URL(
57
+ '/.well-known/oauth-protected-resource',
58
+ base,
59
+ ).toString(),
60
+ authorizationServer: new URL(
61
+ '/.well-known/oauth-authorization-server',
62
+ base,
63
+ ).toString(),
64
+ };
65
+ }
66
+
67
+ // Path-based discovery: append path suffix to well-known URLs
68
+ const pathSuffix = serverUrl.pathname.replace(/\/$/, ''); // Remove trailing slash
69
+ return {
70
+ protectedResource: new URL(
71
+ `/.well-known/oauth-protected-resource${pathSuffix}`,
72
+ base,
73
+ ).toString(),
74
+ authorizationServer: new URL(
75
+ `/.well-known/oauth-authorization-server${pathSuffix}`,
76
+ base,
77
+ ).toString(),
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Fetch OAuth protected resource metadata.
83
+ *
84
+ * @param resourceMetadataUrl The protected resource metadata URL
85
+ * @returns The protected resource metadata or null if not available
86
+ */
87
+ static async fetchProtectedResourceMetadata(
88
+ resourceMetadataUrl: string,
89
+ ): Promise<OAuthProtectedResourceMetadata | null> {
90
+ try {
91
+ const response = await fetch(resourceMetadataUrl);
92
+ if (!response.ok) {
93
+ return null;
94
+ }
95
+ return (await response.json()) as OAuthProtectedResourceMetadata;
96
+ } catch (error) {
97
+ console.debug(
98
+ `Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error)}`,
99
+ );
100
+ return null;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Fetch OAuth authorization server metadata.
106
+ *
107
+ * @param authServerMetadataUrl The authorization server metadata URL
108
+ * @returns The authorization server metadata or null if not available
109
+ */
110
+ static async fetchAuthorizationServerMetadata(
111
+ authServerMetadataUrl: string,
112
+ ): Promise<OAuthAuthorizationServerMetadata | null> {
113
+ try {
114
+ const response = await fetch(authServerMetadataUrl);
115
+ if (!response.ok) {
116
+ return null;
117
+ }
118
+ return (await response.json()) as OAuthAuthorizationServerMetadata;
119
+ } catch (error) {
120
+ console.debug(
121
+ `Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error)}`,
122
+ );
123
+ return null;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Convert authorization server metadata to OAuth configuration.
129
+ *
130
+ * @param metadata The authorization server metadata
131
+ * @returns The OAuth configuration
132
+ */
133
+ static metadataToOAuthConfig(
134
+ metadata: OAuthAuthorizationServerMetadata,
135
+ ): MCPOAuthConfig {
136
+ return {
137
+ authorizationUrl: metadata.authorization_endpoint,
138
+ tokenUrl: metadata.token_endpoint,
139
+ scopes: metadata.scopes_supported || [],
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Discover OAuth configuration using the standard well-known endpoints.
145
+ *
146
+ * @param serverUrl The base URL of the server
147
+ * @returns The discovered OAuth configuration or null if not available
148
+ */
149
+ static async discoverOAuthConfig(
150
+ serverUrl: string,
151
+ ): Promise<MCPOAuthConfig | null> {
152
+ try {
153
+ // First try standard root-based discovery
154
+ const wellKnownUrls = this.buildWellKnownUrls(serverUrl, false);
155
+
156
+ // Try to get the protected resource metadata at root
157
+ let resourceMetadata = await this.fetchProtectedResourceMetadata(
158
+ wellKnownUrls.protectedResource,
159
+ );
160
+
161
+ // If root discovery fails and we have a path, try path-based discovery
162
+ if (!resourceMetadata) {
163
+ const url = new URL(serverUrl);
164
+ if (url.pathname && url.pathname !== '/') {
165
+ const pathBasedUrls = this.buildWellKnownUrls(serverUrl, true);
166
+ resourceMetadata = await this.fetchProtectedResourceMetadata(
167
+ pathBasedUrls.protectedResource,
168
+ );
169
+ }
170
+ }
171
+
172
+ if (resourceMetadata?.authorization_servers?.length) {
173
+ // Use the first authorization server
174
+ const authServerUrl = resourceMetadata.authorization_servers[0];
175
+
176
+ // The authorization server URL may include a path (e.g., https://github.com/login/oauth)
177
+ // We need to preserve this path when constructing the metadata URL
178
+ const authServerUrlObj = new URL(authServerUrl);
179
+ const authServerPath =
180
+ authServerUrlObj.pathname === '/' ? '' : authServerUrlObj.pathname;
181
+
182
+ // Try with the authorization server's path first
183
+ let authServerMetadataUrl = new URL(
184
+ `/.well-known/oauth-authorization-server${authServerPath}`,
185
+ `${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
186
+ ).toString();
187
+
188
+ let authServerMetadata = await this.fetchAuthorizationServerMetadata(
189
+ authServerMetadataUrl,
190
+ );
191
+
192
+ // If that fails, try root as fallback
193
+ if (!authServerMetadata && authServerPath) {
194
+ authServerMetadataUrl = new URL(
195
+ '/.well-known/oauth-authorization-server',
196
+ `${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
197
+ ).toString();
198
+ authServerMetadata = await this.fetchAuthorizationServerMetadata(
199
+ authServerMetadataUrl,
200
+ );
201
+ }
202
+
203
+ if (authServerMetadata) {
204
+ const config = this.metadataToOAuthConfig(authServerMetadata);
205
+ if (authServerMetadata.registration_endpoint) {
206
+ console.log(
207
+ 'Dynamic client registration is supported at:',
208
+ authServerMetadata.registration_endpoint,
209
+ );
210
+ }
211
+ return config;
212
+ }
213
+ }
214
+
215
+ // Fallback: try /.well-known/oauth-authorization-server at the base URL
216
+ console.debug(
217
+ `Trying OAuth discovery fallback at ${wellKnownUrls.authorizationServer}`,
218
+ );
219
+ const authServerMetadata = await this.fetchAuthorizationServerMetadata(
220
+ wellKnownUrls.authorizationServer,
221
+ );
222
+
223
+ if (authServerMetadata) {
224
+ const config = this.metadataToOAuthConfig(authServerMetadata);
225
+ if (authServerMetadata.registration_endpoint) {
226
+ console.log(
227
+ 'Dynamic client registration is supported at:',
228
+ authServerMetadata.registration_endpoint,
229
+ );
230
+ }
231
+ return config;
232
+ }
233
+
234
+ return null;
235
+ } catch (error) {
236
+ console.debug(
237
+ `Failed to discover OAuth configuration: ${getErrorMessage(error)}`,
238
+ );
239
+ return null;
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Parse WWW-Authenticate header to extract OAuth information.
245
+ *
246
+ * @param header The WWW-Authenticate header value
247
+ * @returns The resource metadata URI if found
248
+ */
249
+ static parseWWWAuthenticateHeader(header: string): string | null {
250
+ // Parse Bearer realm and resource_metadata
251
+ const match = header.match(/resource_metadata="([^"]+)"/);
252
+ if (match) {
253
+ return match[1];
254
+ }
255
+ return null;
256
+ }
257
+
258
+ /**
259
+ * Discover OAuth configuration from WWW-Authenticate header.
260
+ *
261
+ * @param wwwAuthenticate The WWW-Authenticate header value
262
+ * @returns The discovered OAuth configuration or null if not available
263
+ */
264
+ static async discoverOAuthFromWWWAuthenticate(
265
+ wwwAuthenticate: string,
266
+ ): Promise<MCPOAuthConfig | null> {
267
+ const resourceMetadataUri =
268
+ this.parseWWWAuthenticateHeader(wwwAuthenticate);
269
+ if (!resourceMetadataUri) {
270
+ return null;
271
+ }
272
+
273
+ const resourceMetadata =
274
+ await this.fetchProtectedResourceMetadata(resourceMetadataUri);
275
+ if (!resourceMetadata?.authorization_servers?.length) {
276
+ return null;
277
+ }
278
+
279
+ const authServerUrl = resourceMetadata.authorization_servers[0];
280
+
281
+ // The authorization server URL may include a path (e.g., https://github.com/login/oauth)
282
+ // We need to preserve this path when constructing the metadata URL
283
+ const authServerUrlObj = new URL(authServerUrl);
284
+ const authServerPath =
285
+ authServerUrlObj.pathname === '/' ? '' : authServerUrlObj.pathname;
286
+
287
+ // Build auth server metadata URL with the authorization server's path
288
+ const authServerMetadataUrl = new URL(
289
+ `/.well-known/oauth-authorization-server${authServerPath}`,
290
+ `${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
291
+ ).toString();
292
+
293
+ let authServerMetadata = await this.fetchAuthorizationServerMetadata(
294
+ authServerMetadataUrl,
295
+ );
296
+
297
+ // If that fails and we have a path, also try the root path as a fallback
298
+ if (!authServerMetadata && authServerPath) {
299
+ const rootAuthServerMetadataUrl = new URL(
300
+ '/.well-known/oauth-authorization-server',
301
+ `${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
302
+ ).toString();
303
+
304
+ authServerMetadata = await this.fetchAuthorizationServerMetadata(
305
+ rootAuthServerMetadataUrl,
306
+ );
307
+ }
308
+
309
+ if (authServerMetadata) {
310
+ return this.metadataToOAuthConfig(authServerMetadata);
311
+ }
312
+
313
+ return null;
314
+ }
315
+
316
+ /**
317
+ * Extract base URL from an MCP server URL.
318
+ *
319
+ * @param mcpServerUrl The MCP server URL
320
+ * @returns The base URL
321
+ */
322
+ static extractBaseUrl(mcpServerUrl: string): string {
323
+ const serverUrl = new URL(mcpServerUrl);
324
+ return `${serverUrl.protocol}//${serverUrl.host}`;
325
+ }
326
+
327
+ /**
328
+ * Check if a URL is an SSE endpoint.
329
+ *
330
+ * @param url The URL to check
331
+ * @returns True if the URL appears to be an SSE endpoint
332
+ */
333
+ static isSSEEndpoint(url: string): boolean {
334
+ return url.includes('/sse') || !url.includes('/mcp');
335
+ }
336
+
337
+ /**
338
+ * Build a resource parameter for OAuth requests.
339
+ *
340
+ * @param endpointUrl The endpoint URL
341
+ * @returns The resource parameter value
342
+ */
343
+ static buildResourceParameter(endpointUrl: string): string {
344
+ const url = new URL(endpointUrl);
345
+ return `${url.protocol}//${url.host}`;
346
+ }
347
+ }
projects/ui/qwen-code/packages/core/src/mocks/msw.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { setupServer } from 'msw/node';
8
+
9
+ export const server = setupServer();
projects/ui/qwen-code/packages/core/src/prompts/mcp-prompts.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Config } from '../config/config.js';
8
+ import { DiscoveredMCPPrompt } from '../tools/mcp-client.js';
9
+
10
+ export function getMCPServerPrompts(
11
+ config: Config,
12
+ serverName: string,
13
+ ): DiscoveredMCPPrompt[] {
14
+ const promptRegistry = config.getPromptRegistry();
15
+ if (!promptRegistry) {
16
+ return [];
17
+ }
18
+ return promptRegistry.getPromptsByServer(serverName);
19
+ }
projects/ui/qwen-code/packages/core/src/prompts/prompt-registry.ts ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { DiscoveredMCPPrompt } from '../tools/mcp-client.js';
8
+
9
+ export class PromptRegistry {
10
+ private prompts: Map<string, DiscoveredMCPPrompt> = new Map();
11
+
12
+ /**
13
+ * Registers a prompt definition.
14
+ * @param prompt - The prompt object containing schema and execution logic.
15
+ */
16
+ registerPrompt(prompt: DiscoveredMCPPrompt): void {
17
+ if (this.prompts.has(prompt.name)) {
18
+ const newName = `${prompt.serverName}_${prompt.name}`;
19
+ console.warn(
20
+ `Prompt with name "${prompt.name}" is already registered. Renaming to "${newName}".`,
21
+ );
22
+ this.prompts.set(newName, { ...prompt, name: newName });
23
+ } else {
24
+ this.prompts.set(prompt.name, prompt);
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Returns an array of all registered and discovered prompt instances.
30
+ */
31
+ getAllPrompts(): DiscoveredMCPPrompt[] {
32
+ return Array.from(this.prompts.values()).sort((a, b) =>
33
+ a.name.localeCompare(b.name),
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Get the definition of a specific prompt.
39
+ */
40
+ getPrompt(name: string): DiscoveredMCPPrompt | undefined {
41
+ return this.prompts.get(name);
42
+ }
43
+
44
+ /**
45
+ * Returns an array of prompts registered from a specific MCP server.
46
+ */
47
+ getPromptsByServer(serverName: string): DiscoveredMCPPrompt[] {
48
+ const serverPrompts: DiscoveredMCPPrompt[] = [];
49
+ for (const prompt of this.prompts.values()) {
50
+ if (prompt.serverName === serverName) {
51
+ serverPrompts.push(prompt);
52
+ }
53
+ }
54
+ return serverPrompts.sort((a, b) => a.name.localeCompare(b.name));
55
+ }
56
+
57
+ /**
58
+ * Clears all the prompts from the registry.
59
+ */
60
+ clear(): void {
61
+ this.prompts.clear();
62
+ }
63
+
64
+ /**
65
+ * Removes all prompts from a specific server.
66
+ */
67
+ removePromptsByServer(serverName: string): void {
68
+ for (const [name, prompt] of this.prompts.entries()) {
69
+ if (prompt.serverName === serverName) {
70
+ this.prompts.delete(name);
71
+ }
72
+ }
73
+ }
74
+ }
projects/ui/qwen-code/packages/core/src/qwen/qwenContentGenerator.test.ts ADDED
@@ -0,0 +1,1601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import {
9
+ IQwenOAuth2Client,
10
+ type QwenCredentials,
11
+ type ErrorData,
12
+ } from './qwenOAuth2.js';
13
+ import {
14
+ GenerateContentParameters,
15
+ GenerateContentResponse,
16
+ CountTokensParameters,
17
+ CountTokensResponse,
18
+ EmbedContentParameters,
19
+ EmbedContentResponse,
20
+ FinishReason,
21
+ } from '@google/genai';
22
+ import { QwenContentGenerator } from './qwenContentGenerator.js';
23
+ import { SharedTokenManager } from './sharedTokenManager.js';
24
+ import { Config } from '../config/config.js';
25
+ import { AuthType, ContentGeneratorConfig } from '../core/contentGenerator.js';
26
+
27
+ // Mock SharedTokenManager
28
+ vi.mock('./sharedTokenManager.js', () => ({
29
+ SharedTokenManager: class {
30
+ private static instance: unknown = null;
31
+ private mockCredentials: QwenCredentials | null = null;
32
+ private shouldThrowError: boolean = false;
33
+ private errorToThrow: Error | null = null;
34
+
35
+ static getInstance() {
36
+ if (!this.instance) {
37
+ this.instance = new this();
38
+ }
39
+ return this.instance;
40
+ }
41
+
42
+ async getValidCredentials(
43
+ qwenClient: IQwenOAuth2Client,
44
+ ): Promise<QwenCredentials> {
45
+ // If we're configured to throw an error, do so
46
+ if (this.shouldThrowError && this.errorToThrow) {
47
+ throw this.errorToThrow;
48
+ }
49
+
50
+ // Try to get credentials from the mock client first to trigger auth errors
51
+ try {
52
+ const { token } = await qwenClient.getAccessToken();
53
+ if (token) {
54
+ const credentials = qwenClient.getCredentials();
55
+ return credentials;
56
+ }
57
+ } catch (error) {
58
+ // If it's an auth error and we need to simulate refresh behavior
59
+ const errorMessage =
60
+ error instanceof Error
61
+ ? error.message.toLowerCase()
62
+ : String(error).toLowerCase();
63
+ const errorCode =
64
+ (error as { status?: number; code?: number })?.status ||
65
+ (error as { status?: number; code?: number })?.code;
66
+
67
+ const isAuthError =
68
+ errorCode === 401 ||
69
+ errorCode === 403 ||
70
+ errorMessage.includes('unauthorized') ||
71
+ errorMessage.includes('forbidden') ||
72
+ errorMessage.includes('token expired');
73
+
74
+ if (isAuthError) {
75
+ // Try to refresh the token through the client
76
+ try {
77
+ const refreshResult = await qwenClient.refreshAccessToken();
78
+ if (refreshResult && !('error' in refreshResult)) {
79
+ // Refresh succeeded, update client credentials and return them
80
+ const updatedCredentials = qwenClient.getCredentials();
81
+ return updatedCredentials;
82
+ } else {
83
+ // Refresh failed, throw appropriate error
84
+ throw new Error(
85
+ 'Failed to obtain valid Qwen access token. Please re-authenticate.',
86
+ );
87
+ }
88
+ } catch {
89
+ throw new Error(
90
+ 'Failed to obtain valid Qwen access token. Please re-authenticate.',
91
+ );
92
+ }
93
+ } else {
94
+ // Re-throw non-auth errors
95
+ throw error;
96
+ }
97
+ }
98
+
99
+ // Return mock credentials only if they're set
100
+ if (this.mockCredentials && this.mockCredentials.access_token) {
101
+ return this.mockCredentials;
102
+ }
103
+
104
+ // Default fallback for tests that need credentials
105
+ return {
106
+ access_token: 'valid-token',
107
+ refresh_token: 'valid-refresh-token',
108
+ resource_url: 'https://test-endpoint.com/v1',
109
+ expiry_date: Date.now() + 3600000,
110
+ };
111
+ }
112
+
113
+ getCurrentCredentials(): QwenCredentials | null {
114
+ return this.mockCredentials;
115
+ }
116
+
117
+ clearCache(): void {
118
+ this.mockCredentials = null;
119
+ }
120
+
121
+ // Helper method for tests to set credentials
122
+ setMockCredentials(credentials: QwenCredentials | null): void {
123
+ this.mockCredentials = credentials;
124
+ }
125
+
126
+ // Helper method for tests to simulate errors
127
+ setMockError(error: Error | null): void {
128
+ this.shouldThrowError = !!error;
129
+ this.errorToThrow = error;
130
+ }
131
+ },
132
+ }));
133
+
134
+ // Mock the OpenAIContentGenerator parent class
135
+ vi.mock('../core/openaiContentGenerator.js', () => ({
136
+ OpenAIContentGenerator: class {
137
+ client: {
138
+ apiKey: string;
139
+ baseURL: string;
140
+ };
141
+
142
+ constructor(
143
+ contentGeneratorConfig: ContentGeneratorConfig,
144
+ _config: Config,
145
+ ) {
146
+ this.client = {
147
+ apiKey: contentGeneratorConfig.apiKey || 'test-key',
148
+ baseURL: contentGeneratorConfig.baseUrl || 'https://api.openai.com/v1',
149
+ };
150
+ }
151
+
152
+ async generateContent(
153
+ _request: GenerateContentParameters,
154
+ ): Promise<GenerateContentResponse> {
155
+ return createMockResponse('Generated content');
156
+ }
157
+
158
+ async generateContentStream(
159
+ _request: GenerateContentParameters,
160
+ ): Promise<AsyncGenerator<GenerateContentResponse>> {
161
+ return (async function* () {
162
+ yield createMockResponse('Stream chunk 1');
163
+ yield createMockResponse('Stream chunk 2');
164
+ })();
165
+ }
166
+
167
+ async countTokens(
168
+ _request: CountTokensParameters,
169
+ ): Promise<CountTokensResponse> {
170
+ return { totalTokens: 10 };
171
+ }
172
+
173
+ async embedContent(
174
+ _request: EmbedContentParameters,
175
+ ): Promise<EmbedContentResponse> {
176
+ return { embeddings: [{ values: [0.1, 0.2, 0.3] }] };
177
+ }
178
+
179
+ protected shouldSuppressErrorLogging(
180
+ _error: unknown,
181
+ _request: GenerateContentParameters,
182
+ ): boolean {
183
+ return false;
184
+ }
185
+ },
186
+ }));
187
+
188
+ const createMockResponse = (text: string): GenerateContentResponse =>
189
+ ({
190
+ candidates: [
191
+ {
192
+ content: { role: 'model', parts: [{ text }] },
193
+ finishReason: FinishReason.STOP,
194
+ index: 0,
195
+ safetyRatings: [],
196
+ },
197
+ ],
198
+ promptFeedback: { safetyRatings: [] },
199
+ text,
200
+ data: undefined,
201
+ functionCalls: [],
202
+ executableCode: '',
203
+ codeExecutionResult: '',
204
+ }) as GenerateContentResponse;
205
+
206
+ describe('QwenContentGenerator', () => {
207
+ let mockQwenClient: IQwenOAuth2Client;
208
+ let qwenContentGenerator: QwenContentGenerator;
209
+ let mockConfig: Config;
210
+
211
+ const mockCredentials: QwenCredentials = {
212
+ access_token: 'test-access-token',
213
+ refresh_token: 'test-refresh-token',
214
+ resource_url: 'https://test-endpoint.com/v1',
215
+ };
216
+
217
+ beforeEach(() => {
218
+ vi.clearAllMocks();
219
+
220
+ // Mock Config
221
+ mockConfig = {
222
+ getContentGeneratorConfig: vi.fn().mockReturnValue({
223
+ authType: 'qwen',
224
+ enableOpenAILogging: false,
225
+ timeout: 120000,
226
+ maxRetries: 3,
227
+ samplingParams: {
228
+ temperature: 0.7,
229
+ max_tokens: 1000,
230
+ top_p: 0.9,
231
+ },
232
+ }),
233
+ } as unknown as Config;
234
+
235
+ // Mock QwenOAuth2Client
236
+ mockQwenClient = {
237
+ getAccessToken: vi.fn(),
238
+ getCredentials: vi.fn(),
239
+ setCredentials: vi.fn(),
240
+ refreshAccessToken: vi.fn(),
241
+ requestDeviceAuthorization: vi.fn(),
242
+ pollDeviceToken: vi.fn(),
243
+ };
244
+
245
+ // Create QwenContentGenerator instance
246
+ const contentGeneratorConfig = {
247
+ model: 'qwen-turbo',
248
+ authType: AuthType.QWEN_OAUTH,
249
+ };
250
+ qwenContentGenerator = new QwenContentGenerator(
251
+ mockQwenClient,
252
+ contentGeneratorConfig,
253
+ mockConfig,
254
+ );
255
+ });
256
+
257
+ afterEach(() => {
258
+ vi.restoreAllMocks();
259
+ });
260
+
261
+ describe('Core Content Generation Methods', () => {
262
+ it('should generate content with valid token', async () => {
263
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
264
+ token: 'valid-token',
265
+ });
266
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
267
+
268
+ const request: GenerateContentParameters = {
269
+ model: 'qwen-turbo',
270
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
271
+ };
272
+
273
+ const result = await qwenContentGenerator.generateContent(
274
+ request,
275
+ 'test-prompt-id',
276
+ );
277
+
278
+ expect(result.text).toBe('Generated content');
279
+ expect(mockQwenClient.getAccessToken).toHaveBeenCalled();
280
+ });
281
+
282
+ it('should generate content stream with valid token', async () => {
283
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
284
+ token: 'valid-token',
285
+ });
286
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
287
+
288
+ const request: GenerateContentParameters = {
289
+ model: 'qwen-turbo',
290
+ contents: [{ role: 'user', parts: [{ text: 'Hello stream' }] }],
291
+ };
292
+
293
+ const stream = await qwenContentGenerator.generateContentStream(
294
+ request,
295
+ 'test-prompt-id',
296
+ );
297
+ const chunks: string[] = [];
298
+
299
+ for await (const chunk of stream) {
300
+ chunks.push(chunk.text || '');
301
+ }
302
+
303
+ expect(chunks).toEqual(['Stream chunk 1', 'Stream chunk 2']);
304
+ expect(mockQwenClient.getAccessToken).toHaveBeenCalled();
305
+ });
306
+
307
+ it('should count tokens with valid token', async () => {
308
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
309
+ token: 'valid-token',
310
+ });
311
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
312
+
313
+ const request: CountTokensParameters = {
314
+ model: 'qwen-turbo',
315
+ contents: [{ role: 'user', parts: [{ text: 'Count me' }] }],
316
+ };
317
+
318
+ const result = await qwenContentGenerator.countTokens(request);
319
+
320
+ expect(result.totalTokens).toBe(10);
321
+ expect(mockQwenClient.getAccessToken).toHaveBeenCalled();
322
+ });
323
+
324
+ it('should embed content with valid token', async () => {
325
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
326
+ token: 'valid-token',
327
+ });
328
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
329
+
330
+ const request: EmbedContentParameters = {
331
+ model: 'qwen-turbo',
332
+ contents: [{ parts: [{ text: 'Embed me' }] }],
333
+ };
334
+
335
+ const result = await qwenContentGenerator.embedContent(request);
336
+
337
+ expect(result.embeddings).toHaveLength(1);
338
+ expect(result.embeddings?.[0]?.values).toEqual([0.1, 0.2, 0.3]);
339
+ expect(mockQwenClient.getAccessToken).toHaveBeenCalled();
340
+ });
341
+ });
342
+
343
+ describe('Token Management and Refresh Logic', () => {
344
+ it('should refresh token on auth error and retry', async () => {
345
+ const authError = { status: 401, message: 'Unauthorized' };
346
+
347
+ // First call fails with auth error, second call succeeds
348
+ vi.mocked(mockQwenClient.getAccessToken)
349
+ .mockRejectedValueOnce(authError)
350
+ .mockResolvedValueOnce({ token: 'refreshed-token' });
351
+
352
+ // Refresh succeeds
353
+ vi.mocked(mockQwenClient.refreshAccessToken).mockResolvedValue({
354
+ access_token: 'refreshed-token',
355
+ token_type: 'Bearer',
356
+ expires_in: 3600,
357
+ resource_url: 'https://refreshed-endpoint.com',
358
+ });
359
+
360
+ // Set credentials for second call
361
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
362
+ access_token: 'refreshed-token',
363
+ token_type: 'Bearer',
364
+ refresh_token: 'refresh-token',
365
+ resource_url: 'https://refreshed-endpoint.com',
366
+ expiry_date: Date.now() + 3600000,
367
+ });
368
+
369
+ const request: GenerateContentParameters = {
370
+ model: 'qwen-turbo',
371
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
372
+ };
373
+
374
+ const result = await qwenContentGenerator.generateContent(
375
+ request,
376
+ 'test-prompt-id',
377
+ );
378
+
379
+ expect(result.text).toBe('Generated content');
380
+ expect(mockQwenClient.refreshAccessToken).toHaveBeenCalled();
381
+ });
382
+
383
+ it('should refresh token on auth error and retry for content stream', async () => {
384
+ const authError = { status: 401, message: 'Unauthorized' };
385
+
386
+ // Reset mocks for this test
387
+ vi.clearAllMocks();
388
+
389
+ // First call fails with auth error, second call succeeds
390
+ vi.mocked(mockQwenClient.getAccessToken)
391
+ .mockRejectedValueOnce(authError)
392
+ .mockResolvedValueOnce({ token: 'refreshed-stream-token' });
393
+
394
+ // Refresh succeeds
395
+ vi.mocked(mockQwenClient.refreshAccessToken).mockResolvedValue({
396
+ access_token: 'refreshed-stream-token',
397
+ token_type: 'Bearer',
398
+ expires_in: 3600,
399
+ resource_url: 'https://refreshed-stream-endpoint.com',
400
+ });
401
+
402
+ // Set credentials for second call
403
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
404
+ access_token: 'refreshed-stream-token',
405
+ token_type: 'Bearer',
406
+ refresh_token: 'refresh-token',
407
+ resource_url: 'https://refreshed-stream-endpoint.com',
408
+ expiry_date: Date.now() + 3600000,
409
+ });
410
+
411
+ const request: GenerateContentParameters = {
412
+ model: 'qwen-turbo',
413
+ contents: [{ role: 'user', parts: [{ text: 'Hello stream' }] }],
414
+ };
415
+
416
+ const stream = await qwenContentGenerator.generateContentStream(
417
+ request,
418
+ 'test-prompt-id',
419
+ );
420
+ const chunks: string[] = [];
421
+
422
+ for await (const chunk of stream) {
423
+ chunks.push(chunk.text || '');
424
+ }
425
+
426
+ expect(chunks).toEqual(['Stream chunk 1', 'Stream chunk 2']);
427
+ expect(mockQwenClient.refreshAccessToken).toHaveBeenCalled();
428
+ });
429
+
430
+ it('should handle token refresh failure', async () => {
431
+ // Mock the SharedTokenManager to throw an error
432
+ const mockTokenManager = SharedTokenManager.getInstance() as unknown as {
433
+ setMockError: (error: Error | null) => void;
434
+ };
435
+ mockTokenManager.setMockError(
436
+ new Error(
437
+ 'Failed to obtain valid Qwen access token. Please re-authenticate.',
438
+ ),
439
+ );
440
+
441
+ const request: GenerateContentParameters = {
442
+ model: 'qwen-turbo',
443
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
444
+ };
445
+
446
+ await expect(
447
+ qwenContentGenerator.generateContent(request, 'test-prompt-id'),
448
+ ).rejects.toThrow(
449
+ 'Failed to obtain valid Qwen access token. Please re-authenticate.',
450
+ );
451
+
452
+ // Clean up
453
+ mockTokenManager.setMockError(null);
454
+ });
455
+
456
+ it('should update endpoint when token is refreshed', async () => {
457
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
458
+ token: 'valid-token',
459
+ });
460
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
461
+ ...mockCredentials,
462
+ resource_url: 'https://new-endpoint.com',
463
+ });
464
+
465
+ const request: GenerateContentParameters = {
466
+ model: 'qwen-turbo',
467
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
468
+ };
469
+
470
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
471
+
472
+ expect(mockQwenClient.getCredentials).toHaveBeenCalled();
473
+ });
474
+ });
475
+
476
+ describe('Endpoint URL Normalization', () => {
477
+ it('should use default endpoint when no custom endpoint provided', async () => {
478
+ let capturedBaseURL = '';
479
+
480
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
481
+ token: 'valid-token',
482
+ });
483
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
484
+ access_token: 'test-token',
485
+ refresh_token: 'test-refresh',
486
+ // No resource_url provided
487
+ });
488
+
489
+ // Mock the parent's generateContent to capture the baseURL during the call
490
+ const parentPrototype = Object.getPrototypeOf(
491
+ Object.getPrototypeOf(qwenContentGenerator),
492
+ );
493
+ const originalGenerateContent = parentPrototype.generateContent;
494
+ parentPrototype.generateContent = vi.fn().mockImplementation(function (
495
+ this: QwenContentGenerator,
496
+ ) {
497
+ capturedBaseURL = (this as unknown as { client: { baseURL: string } })
498
+ .client.baseURL;
499
+ return createMockResponse('Generated content');
500
+ });
501
+
502
+ const request: GenerateContentParameters = {
503
+ model: 'qwen-turbo',
504
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
505
+ };
506
+
507
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
508
+
509
+ // Should use default endpoint with /v1 suffix
510
+ expect(capturedBaseURL).toBe(
511
+ 'https://dashscope.aliyuncs.com/compatible-mode/v1',
512
+ );
513
+
514
+ // Restore original method
515
+ parentPrototype.generateContent = originalGenerateContent;
516
+ });
517
+
518
+ it('should normalize hostname-only endpoints by adding https protocol', async () => {
519
+ let capturedBaseURL = '';
520
+
521
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
522
+ token: 'valid-token',
523
+ });
524
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
525
+ ...mockCredentials,
526
+ resource_url: 'custom-endpoint.com',
527
+ });
528
+
529
+ // Mock the parent's generateContent to capture the baseURL during the call
530
+ const parentPrototype = Object.getPrototypeOf(
531
+ Object.getPrototypeOf(qwenContentGenerator),
532
+ );
533
+ const originalGenerateContent = parentPrototype.generateContent;
534
+ parentPrototype.generateContent = vi.fn().mockImplementation(function (
535
+ this: QwenContentGenerator,
536
+ ) {
537
+ capturedBaseURL = (this as unknown as { client: { baseURL: string } })
538
+ .client.baseURL;
539
+ return createMockResponse('Generated content');
540
+ });
541
+
542
+ const request: GenerateContentParameters = {
543
+ model: 'qwen-turbo',
544
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
545
+ };
546
+
547
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
548
+
549
+ // Should add https:// and /v1
550
+ expect(capturedBaseURL).toBe('https://custom-endpoint.com/v1');
551
+
552
+ // Restore original method
553
+ parentPrototype.generateContent = originalGenerateContent;
554
+ });
555
+
556
+ it('should preserve existing protocol in endpoint URLs', async () => {
557
+ let capturedBaseURL = '';
558
+
559
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
560
+ token: 'valid-token',
561
+ });
562
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
563
+ ...mockCredentials,
564
+ resource_url: 'https://custom-endpoint.com',
565
+ });
566
+
567
+ // Mock the parent's generateContent to capture the baseURL during the call
568
+ const parentPrototype = Object.getPrototypeOf(
569
+ Object.getPrototypeOf(qwenContentGenerator),
570
+ );
571
+ const originalGenerateContent = parentPrototype.generateContent;
572
+ parentPrototype.generateContent = vi.fn().mockImplementation(function (
573
+ this: QwenContentGenerator,
574
+ ) {
575
+ capturedBaseURL = (this as unknown as { client: { baseURL: string } })
576
+ .client.baseURL;
577
+ return createMockResponse('Generated content');
578
+ });
579
+
580
+ const request: GenerateContentParameters = {
581
+ model: 'qwen-turbo',
582
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
583
+ };
584
+
585
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
586
+
587
+ // Should preserve https:// and add /v1
588
+ expect(capturedBaseURL).toBe('https://custom-endpoint.com/v1');
589
+
590
+ // Restore original method
591
+ parentPrototype.generateContent = originalGenerateContent;
592
+ });
593
+
594
+ it('should not duplicate /v1 suffix if already present', async () => {
595
+ let capturedBaseURL = '';
596
+
597
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
598
+ token: 'valid-token',
599
+ });
600
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
601
+ ...mockCredentials,
602
+ resource_url: 'https://custom-endpoint.com/v1',
603
+ });
604
+
605
+ // Mock the parent's generateContent to capture the baseURL during the call
606
+ const parentPrototype = Object.getPrototypeOf(
607
+ Object.getPrototypeOf(qwenContentGenerator),
608
+ );
609
+ const originalGenerateContent = parentPrototype.generateContent;
610
+ parentPrototype.generateContent = vi.fn().mockImplementation(function (
611
+ this: QwenContentGenerator,
612
+ ) {
613
+ capturedBaseURL = (this as unknown as { client: { baseURL: string } })
614
+ .client.baseURL;
615
+ return createMockResponse('Generated content');
616
+ });
617
+
618
+ const request: GenerateContentParameters = {
619
+ model: 'qwen-turbo',
620
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
621
+ };
622
+
623
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
624
+
625
+ // Should not duplicate /v1
626
+ expect(capturedBaseURL).toBe('https://custom-endpoint.com/v1');
627
+
628
+ // Restore original method
629
+ parentPrototype.generateContent = originalGenerateContent;
630
+ });
631
+ });
632
+
633
+ describe('Client State Management', () => {
634
+ it('should restore original client credentials after operations', async () => {
635
+ const client = (
636
+ qwenContentGenerator as unknown as {
637
+ client: { apiKey: string; baseURL: string };
638
+ }
639
+ ).client;
640
+ const originalApiKey = client.apiKey;
641
+ const originalBaseURL = client.baseURL;
642
+
643
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
644
+ token: 'temp-token',
645
+ });
646
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
647
+ ...mockCredentials,
648
+ resource_url: 'https://temp-endpoint.com',
649
+ });
650
+
651
+ const request: GenerateContentParameters = {
652
+ model: 'qwen-turbo',
653
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
654
+ };
655
+
656
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
657
+
658
+ // Should restore original values after operation
659
+ expect(client.apiKey).toBe(originalApiKey);
660
+ expect(client.baseURL).toBe(originalBaseURL);
661
+ });
662
+
663
+ it('should restore credentials even when operation throws', async () => {
664
+ const client = (
665
+ qwenContentGenerator as unknown as {
666
+ client: { apiKey: string; baseURL: string };
667
+ }
668
+ ).client;
669
+ const originalApiKey = client.apiKey;
670
+ const originalBaseURL = client.baseURL;
671
+
672
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
673
+ token: 'temp-token',
674
+ });
675
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
676
+
677
+ // Mock the parent method to throw an error
678
+ const mockError = new Error('Network error');
679
+ const parentPrototype = Object.getPrototypeOf(
680
+ Object.getPrototypeOf(qwenContentGenerator),
681
+ );
682
+ const originalGenerateContent = parentPrototype.generateContent;
683
+ parentPrototype.generateContent = vi.fn().mockRejectedValue(mockError);
684
+
685
+ const request: GenerateContentParameters = {
686
+ model: 'qwen-turbo',
687
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
688
+ };
689
+
690
+ try {
691
+ await qwenContentGenerator.generateContent(request, 'test-prompt-id');
692
+ } catch (error) {
693
+ expect(error).toBe(mockError);
694
+ }
695
+
696
+ // Credentials should still be restored
697
+ expect(client.apiKey).toBe(originalApiKey);
698
+ expect(client.baseURL).toBe(originalBaseURL);
699
+
700
+ // Restore original method
701
+ parentPrototype.generateContent = originalGenerateContent;
702
+ });
703
+ });
704
+
705
+ describe('Error Handling and Retry Logic', () => {
706
+ it('should retry once on authentication errors', async () => {
707
+ const authError = { status: 401, message: 'Unauthorized' };
708
+
709
+ // Mock first call to fail with auth error
710
+ const mockGenerateContent = vi
711
+ .fn()
712
+ .mockRejectedValueOnce(authError)
713
+ .mockResolvedValueOnce(createMockResponse('Success after retry'));
714
+
715
+ // Replace the parent method
716
+ const parentPrototype = Object.getPrototypeOf(
717
+ Object.getPrototypeOf(qwenContentGenerator),
718
+ );
719
+ const originalGenerateContent = parentPrototype.generateContent;
720
+ parentPrototype.generateContent = mockGenerateContent;
721
+
722
+ // Mock getAccessToken to fail initially, then succeed
723
+ let getAccessTokenCallCount = 0;
724
+ vi.mocked(mockQwenClient.getAccessToken).mockImplementation(async () => {
725
+ getAccessTokenCallCount++;
726
+ if (getAccessTokenCallCount <= 2) {
727
+ throw authError; // Fail on first two calls (initial + retry)
728
+ }
729
+ return { token: 'refreshed-token' }; // Succeed after refresh
730
+ });
731
+
732
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
733
+ access_token: 'refreshed-token',
734
+ token_type: 'Bearer',
735
+ refresh_token: 'refresh-token',
736
+ resource_url: 'https://test-endpoint.com',
737
+ expiry_date: Date.now() + 3600000,
738
+ });
739
+
740
+ vi.mocked(mockQwenClient.refreshAccessToken).mockResolvedValue({
741
+ access_token: 'refreshed-token',
742
+ token_type: 'Bearer',
743
+ expires_in: 3600,
744
+ });
745
+
746
+ const request: GenerateContentParameters = {
747
+ model: 'qwen-turbo',
748
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
749
+ };
750
+
751
+ const result = await qwenContentGenerator.generateContent(
752
+ request,
753
+ 'test-prompt-id',
754
+ );
755
+
756
+ expect(result.text).toBe('Success after retry');
757
+ expect(mockGenerateContent).toHaveBeenCalledTimes(2);
758
+ expect(mockQwenClient.refreshAccessToken).toHaveBeenCalled();
759
+
760
+ // Restore original method
761
+ parentPrototype.generateContent = originalGenerateContent;
762
+ });
763
+
764
+ it('should not retry non-authentication errors', async () => {
765
+ const networkError = new Error('Network timeout');
766
+
767
+ const mockGenerateContent = vi.fn().mockRejectedValue(networkError);
768
+ const parentPrototype = Object.getPrototypeOf(
769
+ Object.getPrototypeOf(qwenContentGenerator),
770
+ );
771
+ const originalGenerateContent = parentPrototype.generateContent;
772
+ parentPrototype.generateContent = mockGenerateContent;
773
+
774
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
775
+ token: 'valid-token',
776
+ });
777
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
778
+
779
+ const request: GenerateContentParameters = {
780
+ model: 'qwen-turbo',
781
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
782
+ };
783
+
784
+ await expect(
785
+ qwenContentGenerator.generateContent(request, 'test-prompt-id'),
786
+ ).rejects.toThrow('Network timeout');
787
+ expect(mockGenerateContent).toHaveBeenCalledTimes(1);
788
+ expect(mockQwenClient.refreshAccessToken).not.toHaveBeenCalled();
789
+
790
+ // Restore original method
791
+ parentPrototype.generateContent = originalGenerateContent;
792
+ });
793
+
794
+ it('should handle error response from token refresh', async () => {
795
+ vi.mocked(mockQwenClient.getAccessToken).mockRejectedValue(
796
+ new Error('Token expired'),
797
+ );
798
+ vi.mocked(mockQwenClient.refreshAccessToken).mockResolvedValue({
799
+ error: 'invalid_grant',
800
+ error_description: 'Refresh token expired',
801
+ } as ErrorData);
802
+
803
+ const request: GenerateContentParameters = {
804
+ model: 'qwen-turbo',
805
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
806
+ };
807
+
808
+ await expect(
809
+ qwenContentGenerator.generateContent(request, 'test-prompt-id'),
810
+ ).rejects.toThrow('Failed to obtain valid Qwen access token');
811
+ });
812
+ });
813
+
814
+ describe('Token State Management', () => {
815
+ it('should cache and return current token', () => {
816
+ expect(qwenContentGenerator.getCurrentToken()).toBeNull();
817
+
818
+ // Simulate setting a token internally
819
+ (
820
+ qwenContentGenerator as unknown as { currentToken: string }
821
+ ).currentToken = 'cached-token';
822
+
823
+ expect(qwenContentGenerator.getCurrentToken()).toBe('cached-token');
824
+ });
825
+
826
+ it('should clear token on clearToken()', () => {
827
+ // Simulate having cached token value
828
+ const qwenInstance = qwenContentGenerator as unknown as {
829
+ currentToken: string;
830
+ };
831
+ qwenInstance.currentToken = 'cached-token';
832
+
833
+ qwenContentGenerator.clearToken();
834
+
835
+ expect(qwenContentGenerator.getCurrentToken()).toBeNull();
836
+ });
837
+
838
+ it('should handle concurrent token refresh requests', async () => {
839
+ let refreshCallCount = 0;
840
+
841
+ // Clear any existing cached token first
842
+ qwenContentGenerator.clearToken();
843
+
844
+ // Mock to simulate auth error on first parent call, which should trigger refresh
845
+ const authError = { status: 401, message: 'Unauthorized' };
846
+ let parentCallCount = 0;
847
+
848
+ vi.mocked(mockQwenClient.getAccessToken).mockRejectedValue(authError);
849
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(mockCredentials);
850
+
851
+ vi.mocked(mockQwenClient.refreshAccessToken).mockImplementation(
852
+ async () => {
853
+ refreshCallCount++;
854
+ await new Promise((resolve) => setTimeout(resolve, 50)); // Longer delay to ensure concurrency
855
+ return {
856
+ access_token: 'refreshed-token',
857
+ token_type: 'Bearer',
858
+ expires_in: 3600,
859
+ };
860
+ },
861
+ );
862
+
863
+ // Mock the parent method to fail first then succeed
864
+ const parentPrototype = Object.getPrototypeOf(
865
+ Object.getPrototypeOf(qwenContentGenerator),
866
+ );
867
+ const originalGenerateContent = parentPrototype.generateContent;
868
+ parentPrototype.generateContent = vi.fn().mockImplementation(async () => {
869
+ parentCallCount++;
870
+ if (parentCallCount === 1) {
871
+ throw authError; // First call triggers auth error
872
+ }
873
+ return createMockResponse('Generated content');
874
+ });
875
+
876
+ const request: GenerateContentParameters = {
877
+ model: 'qwen-turbo',
878
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
879
+ };
880
+
881
+ // Make multiple concurrent requests - should all use the same refresh promise
882
+ const promises = [
883
+ qwenContentGenerator.generateContent(request, 'test-prompt-id'),
884
+ qwenContentGenerator.generateContent(request, 'test-prompt-id'),
885
+ qwenContentGenerator.generateContent(request, 'test-prompt-id'),
886
+ ];
887
+
888
+ const results = await Promise.all(promises);
889
+
890
+ // All should succeed
891
+ results.forEach((result) => {
892
+ expect(result.text).toBe('Generated content');
893
+ });
894
+
895
+ // The main test is that all requests succeed without crashing
896
+ expect(results).toHaveLength(3);
897
+ // With our new implementation through SharedTokenManager, refresh should still be called
898
+ expect(refreshCallCount).toBeGreaterThanOrEqual(1);
899
+
900
+ // Restore original method
901
+ parentPrototype.generateContent = originalGenerateContent;
902
+ });
903
+ });
904
+
905
+ describe('Error Logging Suppression', () => {
906
+ it('should suppress logging for authentication errors', () => {
907
+ const authErrors = [
908
+ { status: 401 },
909
+ { code: 403 },
910
+ new Error('Unauthorized access'),
911
+ new Error('Token expired'),
912
+ new Error('Invalid API key'),
913
+ ];
914
+
915
+ authErrors.forEach((error) => {
916
+ const shouldSuppress = (
917
+ qwenContentGenerator as unknown as {
918
+ shouldSuppressErrorLogging: (
919
+ error: unknown,
920
+ request: GenerateContentParameters,
921
+ ) => boolean;
922
+ }
923
+ ).shouldSuppressErrorLogging(error, {} as GenerateContentParameters);
924
+ expect(shouldSuppress).toBe(true);
925
+ });
926
+ });
927
+
928
+ it('should not suppress logging for non-auth errors', () => {
929
+ const nonAuthErrors = [
930
+ new Error('Network timeout'),
931
+ new Error('Rate limit exceeded'),
932
+ { status: 500 },
933
+ new Error('Internal server error'),
934
+ ];
935
+
936
+ nonAuthErrors.forEach((error) => {
937
+ const shouldSuppress = (
938
+ qwenContentGenerator as unknown as {
939
+ shouldSuppressErrorLogging: (
940
+ error: unknown,
941
+ request: GenerateContentParameters,
942
+ ) => boolean;
943
+ }
944
+ ).shouldSuppressErrorLogging(error, {} as GenerateContentParameters);
945
+ expect(shouldSuppress).toBe(false);
946
+ });
947
+ });
948
+ });
949
+
950
+ describe('Integration Tests', () => {
951
+ it('should handle complete workflow: get token, use it, refresh on auth error, retry', async () => {
952
+ const authError = { status: 401, message: 'Token expired' };
953
+
954
+ // Setup complex scenario
955
+ let callCount = 0;
956
+ const mockGenerateContent = vi.fn().mockImplementation(async () => {
957
+ callCount++;
958
+ if (callCount === 1) {
959
+ throw authError; // First call fails
960
+ }
961
+ return createMockResponse('Success after refresh'); // Second call succeeds
962
+ });
963
+
964
+ const parentPrototype = Object.getPrototypeOf(
965
+ Object.getPrototypeOf(qwenContentGenerator),
966
+ );
967
+ parentPrototype.generateContent = mockGenerateContent;
968
+
969
+ // Mock getAccessToken to fail initially, then succeed
970
+ let getAccessTokenCallCount = 0;
971
+ vi.mocked(mockQwenClient.getAccessToken).mockImplementation(async () => {
972
+ getAccessTokenCallCount++;
973
+ if (getAccessTokenCallCount <= 2) {
974
+ throw authError; // Fail on first two calls (initial + retry)
975
+ }
976
+ return { token: 'new-token' }; // Succeed after refresh
977
+ });
978
+
979
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
980
+ access_token: 'new-token',
981
+ token_type: 'Bearer',
982
+ refresh_token: 'refresh-token',
983
+ resource_url: 'https://new-endpoint.com',
984
+ expiry_date: Date.now() + 7200000,
985
+ });
986
+
987
+ vi.mocked(mockQwenClient.refreshAccessToken).mockResolvedValue({
988
+ access_token: 'new-token',
989
+ token_type: 'Bearer',
990
+ expires_in: 7200,
991
+ resource_url: 'https://new-endpoint.com',
992
+ });
993
+
994
+ const request: GenerateContentParameters = {
995
+ model: 'qwen-turbo',
996
+ contents: [{ role: 'user', parts: [{ text: 'Test message' }] }],
997
+ };
998
+
999
+ const result = await qwenContentGenerator.generateContent(
1000
+ request,
1001
+ 'test-prompt-id',
1002
+ );
1003
+
1004
+ expect(result.text).toBe('Success after refresh');
1005
+ expect(mockQwenClient.getAccessToken).toHaveBeenCalled();
1006
+ expect(mockQwenClient.refreshAccessToken).toHaveBeenCalled();
1007
+ expect(callCount).toBe(2); // Initial call + retry
1008
+ });
1009
+ });
1010
+
1011
+ describe('SharedTokenManager Integration', () => {
1012
+ it('should use SharedTokenManager to get valid credentials', async () => {
1013
+ const mockTokenManager = {
1014
+ getValidCredentials: vi.fn().mockResolvedValue({
1015
+ access_token: 'manager-token',
1016
+ resource_url: 'https://manager-endpoint.com',
1017
+ }),
1018
+ getCurrentCredentials: vi.fn(),
1019
+ clearCache: vi.fn(),
1020
+ };
1021
+
1022
+ // Mock the SharedTokenManager.getInstance()
1023
+ const originalGetInstance = SharedTokenManager.getInstance;
1024
+ SharedTokenManager.getInstance = vi
1025
+ .fn()
1026
+ .mockReturnValue(mockTokenManager);
1027
+
1028
+ // Create new instance to pick up the mock
1029
+ const newGenerator = new QwenContentGenerator(
1030
+ mockQwenClient,
1031
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1032
+ mockConfig,
1033
+ );
1034
+
1035
+ const request: GenerateContentParameters = {
1036
+ model: 'qwen-turbo',
1037
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
1038
+ };
1039
+
1040
+ await newGenerator.generateContent(request, 'test-prompt-id');
1041
+
1042
+ expect(mockTokenManager.getValidCredentials).toHaveBeenCalledWith(
1043
+ mockQwenClient,
1044
+ );
1045
+
1046
+ // Restore original
1047
+ SharedTokenManager.getInstance = originalGetInstance;
1048
+ });
1049
+
1050
+ it('should handle SharedTokenManager errors gracefully', async () => {
1051
+ const mockTokenManager = {
1052
+ getValidCredentials: vi
1053
+ .fn()
1054
+ .mockRejectedValue(new Error('Token manager error')),
1055
+ getCurrentCredentials: vi.fn(),
1056
+ clearCache: vi.fn(),
1057
+ };
1058
+
1059
+ const originalGetInstance = SharedTokenManager.getInstance;
1060
+ SharedTokenManager.getInstance = vi
1061
+ .fn()
1062
+ .mockReturnValue(mockTokenManager);
1063
+
1064
+ const newGenerator = new QwenContentGenerator(
1065
+ mockQwenClient,
1066
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1067
+ mockConfig,
1068
+ );
1069
+
1070
+ const request: GenerateContentParameters = {
1071
+ model: 'qwen-turbo',
1072
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
1073
+ };
1074
+
1075
+ await expect(
1076
+ newGenerator.generateContent(request, 'test-prompt-id'),
1077
+ ).rejects.toThrow('Failed to obtain valid Qwen access token');
1078
+
1079
+ SharedTokenManager.getInstance = originalGetInstance;
1080
+ });
1081
+
1082
+ it('should handle missing access token from credentials', async () => {
1083
+ const mockTokenManager = {
1084
+ getValidCredentials: vi.fn().mockResolvedValue({
1085
+ access_token: undefined,
1086
+ resource_url: 'https://test-endpoint.com',
1087
+ }),
1088
+ getCurrentCredentials: vi.fn(),
1089
+ clearCache: vi.fn(),
1090
+ };
1091
+
1092
+ const originalGetInstance = SharedTokenManager.getInstance;
1093
+ SharedTokenManager.getInstance = vi
1094
+ .fn()
1095
+ .mockReturnValue(mockTokenManager);
1096
+
1097
+ const newGenerator = new QwenContentGenerator(
1098
+ mockQwenClient,
1099
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1100
+ mockConfig,
1101
+ );
1102
+
1103
+ const request: GenerateContentParameters = {
1104
+ model: 'qwen-turbo',
1105
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
1106
+ };
1107
+
1108
+ await expect(
1109
+ newGenerator.generateContent(request, 'test-prompt-id'),
1110
+ ).rejects.toThrow('Failed to obtain valid Qwen access token');
1111
+
1112
+ SharedTokenManager.getInstance = originalGetInstance;
1113
+ });
1114
+ });
1115
+
1116
+ describe('getCurrentEndpoint Method', () => {
1117
+ it('should handle URLs with custom ports', () => {
1118
+ const endpoints = [
1119
+ { input: 'localhost:8080', expected: 'https://localhost:8080/v1' },
1120
+ {
1121
+ input: 'http://localhost:8080',
1122
+ expected: 'http://localhost:8080/v1',
1123
+ },
1124
+ {
1125
+ input: 'https://api.example.com:443',
1126
+ expected: 'https://api.example.com:443/v1',
1127
+ },
1128
+ {
1129
+ input: 'api.example.com:9000/api',
1130
+ expected: 'https://api.example.com:9000/api/v1',
1131
+ },
1132
+ ];
1133
+
1134
+ endpoints.forEach(({ input, expected }) => {
1135
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
1136
+ token: 'test-token',
1137
+ });
1138
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
1139
+ ...mockCredentials,
1140
+ resource_url: input,
1141
+ });
1142
+
1143
+ const generator = qwenContentGenerator as unknown as {
1144
+ getCurrentEndpoint: (resourceUrl?: string) => string;
1145
+ };
1146
+
1147
+ expect(generator.getCurrentEndpoint(input)).toBe(expected);
1148
+ });
1149
+ });
1150
+
1151
+ it('should handle URLs with existing paths', () => {
1152
+ const endpoints = [
1153
+ {
1154
+ input: 'https://api.example.com/api',
1155
+ expected: 'https://api.example.com/api/v1',
1156
+ },
1157
+ {
1158
+ input: 'api.example.com/api/v2',
1159
+ expected: 'https://api.example.com/api/v2/v1',
1160
+ },
1161
+ {
1162
+ input: 'https://api.example.com/api/v1',
1163
+ expected: 'https://api.example.com/api/v1',
1164
+ },
1165
+ ];
1166
+
1167
+ endpoints.forEach(({ input, expected }) => {
1168
+ const generator = qwenContentGenerator as unknown as {
1169
+ getCurrentEndpoint: (resourceUrl?: string) => string;
1170
+ };
1171
+
1172
+ expect(generator.getCurrentEndpoint(input)).toBe(expected);
1173
+ });
1174
+ });
1175
+
1176
+ it('should handle undefined resource URL', () => {
1177
+ const generator = qwenContentGenerator as unknown as {
1178
+ getCurrentEndpoint: (resourceUrl?: string) => string;
1179
+ };
1180
+
1181
+ expect(generator.getCurrentEndpoint(undefined)).toBe(
1182
+ 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1183
+ );
1184
+ });
1185
+
1186
+ it('should handle empty resource URL', () => {
1187
+ const generator = qwenContentGenerator as unknown as {
1188
+ getCurrentEndpoint: (resourceUrl?: string) => string;
1189
+ };
1190
+
1191
+ // Empty string should fall back to default endpoint
1192
+ expect(generator.getCurrentEndpoint('')).toBe(
1193
+ 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1194
+ );
1195
+ });
1196
+ });
1197
+
1198
+ describe('isAuthError Method Enhanced', () => {
1199
+ it('should identify auth errors by numeric status codes', () => {
1200
+ const authErrors = [
1201
+ { code: 401 },
1202
+ { status: 403 },
1203
+ { code: '401' }, // String status codes
1204
+ { status: '403' },
1205
+ ];
1206
+
1207
+ authErrors.forEach((error) => {
1208
+ const generator = qwenContentGenerator as unknown as {
1209
+ isAuthError: (error: unknown) => boolean;
1210
+ };
1211
+ expect(generator.isAuthError(error)).toBe(true);
1212
+ });
1213
+
1214
+ // 400 is not typically an auth error, it's bad request
1215
+ const nonAuthError = { status: 400 };
1216
+ const generator = qwenContentGenerator as unknown as {
1217
+ isAuthError: (error: unknown) => boolean;
1218
+ };
1219
+ expect(generator.isAuthError(nonAuthError)).toBe(false);
1220
+ });
1221
+
1222
+ it('should identify auth errors by message content variations', () => {
1223
+ const authMessages = [
1224
+ 'UNAUTHORIZED access',
1225
+ 'Access is FORBIDDEN',
1226
+ 'Invalid API Key provided',
1227
+ 'Invalid Access Token',
1228
+ 'Token has Expired',
1229
+ 'Authentication Required',
1230
+ 'Access Denied by server',
1231
+ 'The token has expired and needs refresh',
1232
+ 'Bearer token expired',
1233
+ ];
1234
+
1235
+ authMessages.forEach((message) => {
1236
+ const error = new Error(message);
1237
+ const generator = qwenContentGenerator as unknown as {
1238
+ isAuthError: (error: unknown) => boolean;
1239
+ };
1240
+ expect(generator.isAuthError(error)).toBe(true);
1241
+ });
1242
+ });
1243
+
1244
+ it('should not identify non-auth errors', () => {
1245
+ const nonAuthErrors = [
1246
+ new Error('Network timeout'),
1247
+ new Error('Rate limit exceeded'),
1248
+ { status: 500 },
1249
+ { code: 429 },
1250
+ 'Internal server error',
1251
+ null,
1252
+ undefined,
1253
+ '',
1254
+ { status: 200 },
1255
+ new Error('Model not found'),
1256
+ ];
1257
+
1258
+ nonAuthErrors.forEach((error) => {
1259
+ const generator = qwenContentGenerator as unknown as {
1260
+ isAuthError: (error: unknown) => boolean;
1261
+ };
1262
+ expect(generator.isAuthError(error)).toBe(false);
1263
+ });
1264
+ });
1265
+
1266
+ it('should handle complex error objects', () => {
1267
+ const complexErrors = [
1268
+ { error: { status: 401, message: 'Unauthorized' } },
1269
+ { response: { status: 403 } },
1270
+ { details: { code: 401 } },
1271
+ ];
1272
+
1273
+ // These should not be identified as auth errors because the method only looks at top-level properties
1274
+ complexErrors.forEach((error) => {
1275
+ const generator = qwenContentGenerator as unknown as {
1276
+ isAuthError: (error: unknown) => boolean;
1277
+ };
1278
+ expect(generator.isAuthError(error)).toBe(false);
1279
+ });
1280
+ });
1281
+ });
1282
+
1283
+ describe('Stream Error Handling', () => {
1284
+ it('should restore credentials when stream generation fails', async () => {
1285
+ const client = (
1286
+ qwenContentGenerator as unknown as {
1287
+ client: { apiKey: string; baseURL: string };
1288
+ }
1289
+ ).client;
1290
+ const originalApiKey = client.apiKey;
1291
+ const originalBaseURL = client.baseURL;
1292
+
1293
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
1294
+ token: 'stream-token',
1295
+ });
1296
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue({
1297
+ ...mockCredentials,
1298
+ resource_url: 'https://stream-endpoint.com',
1299
+ });
1300
+
1301
+ // Mock parent method to throw error
1302
+ const parentPrototype = Object.getPrototypeOf(
1303
+ Object.getPrototypeOf(qwenContentGenerator),
1304
+ );
1305
+ const originalGenerateContentStream =
1306
+ parentPrototype.generateContentStream;
1307
+ parentPrototype.generateContentStream = vi
1308
+ .fn()
1309
+ .mockRejectedValue(new Error('Stream error'));
1310
+
1311
+ const request: GenerateContentParameters = {
1312
+ model: 'qwen-turbo',
1313
+ contents: [{ role: 'user', parts: [{ text: 'Stream test' }] }],
1314
+ };
1315
+
1316
+ try {
1317
+ await qwenContentGenerator.generateContentStream(
1318
+ request,
1319
+ 'test-prompt-id',
1320
+ );
1321
+ } catch (error) {
1322
+ expect(error).toBeInstanceOf(Error);
1323
+ }
1324
+
1325
+ // Credentials should be restored even on error
1326
+ expect(client.apiKey).toBe(originalApiKey);
1327
+ expect(client.baseURL).toBe(originalBaseURL);
1328
+
1329
+ // Restore original method
1330
+ parentPrototype.generateContentStream = originalGenerateContentStream;
1331
+ });
1332
+
1333
+ it('should not restore credentials in finally block for successful streams', async () => {
1334
+ const client = (
1335
+ qwenContentGenerator as unknown as {
1336
+ client: { apiKey: string; baseURL: string };
1337
+ }
1338
+ ).client;
1339
+
1340
+ // Set up the mock to return stream credentials
1341
+ const streamCredentials = {
1342
+ access_token: 'stream-token',
1343
+ refresh_token: 'stream-refresh-token',
1344
+ resource_url: 'https://stream-endpoint.com',
1345
+ expiry_date: Date.now() + 3600000,
1346
+ };
1347
+
1348
+ vi.mocked(mockQwenClient.getAccessToken).mockResolvedValue({
1349
+ token: 'stream-token',
1350
+ });
1351
+ vi.mocked(mockQwenClient.getCredentials).mockReturnValue(
1352
+ streamCredentials,
1353
+ );
1354
+
1355
+ // Set the SharedTokenManager mock to return stream credentials
1356
+ const mockTokenManager = SharedTokenManager.getInstance() as unknown as {
1357
+ setMockCredentials: (credentials: QwenCredentials | null) => void;
1358
+ };
1359
+ mockTokenManager.setMockCredentials(streamCredentials);
1360
+
1361
+ const request: GenerateContentParameters = {
1362
+ model: 'qwen-turbo',
1363
+ contents: [{ role: 'user', parts: [{ text: 'Stream test' }] }],
1364
+ };
1365
+
1366
+ const stream = await qwenContentGenerator.generateContentStream(
1367
+ request,
1368
+ 'test-prompt-id',
1369
+ );
1370
+
1371
+ // After successful stream creation, credentials should still be set for the stream
1372
+ expect(client.apiKey).toBe('stream-token');
1373
+ expect(client.baseURL).toBe('https://stream-endpoint.com/v1');
1374
+
1375
+ // Consume the stream
1376
+ const chunks = [];
1377
+ for await (const chunk of stream) {
1378
+ chunks.push(chunk);
1379
+ }
1380
+
1381
+ expect(chunks).toHaveLength(2);
1382
+
1383
+ // Clean up
1384
+ mockTokenManager.setMockCredentials(null);
1385
+ });
1386
+ });
1387
+
1388
+ describe('Token and Endpoint Management', () => {
1389
+ it('should get current token from SharedTokenManager', () => {
1390
+ const mockTokenManager = {
1391
+ getCurrentCredentials: vi.fn().mockReturnValue({
1392
+ access_token: 'current-token',
1393
+ }),
1394
+ };
1395
+
1396
+ const originalGetInstance = SharedTokenManager.getInstance;
1397
+ SharedTokenManager.getInstance = vi
1398
+ .fn()
1399
+ .mockReturnValue(mockTokenManager);
1400
+
1401
+ const newGenerator = new QwenContentGenerator(
1402
+ mockQwenClient,
1403
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1404
+ mockConfig,
1405
+ );
1406
+
1407
+ expect(newGenerator.getCurrentToken()).toBe('current-token');
1408
+
1409
+ SharedTokenManager.getInstance = originalGetInstance;
1410
+ });
1411
+
1412
+ it('should return null when no credentials available', () => {
1413
+ const mockTokenManager = {
1414
+ getCurrentCredentials: vi.fn().mockReturnValue(null),
1415
+ };
1416
+
1417
+ const originalGetInstance = SharedTokenManager.getInstance;
1418
+ SharedTokenManager.getInstance = vi
1419
+ .fn()
1420
+ .mockReturnValue(mockTokenManager);
1421
+
1422
+ const newGenerator = new QwenContentGenerator(
1423
+ mockQwenClient,
1424
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1425
+ mockConfig,
1426
+ );
1427
+
1428
+ expect(newGenerator.getCurrentToken()).toBeNull();
1429
+
1430
+ SharedTokenManager.getInstance = originalGetInstance;
1431
+ });
1432
+
1433
+ it('should return null when credentials have no access token', () => {
1434
+ const mockTokenManager = {
1435
+ getCurrentCredentials: vi.fn().mockReturnValue({
1436
+ access_token: undefined,
1437
+ }),
1438
+ };
1439
+
1440
+ const originalGetInstance = SharedTokenManager.getInstance;
1441
+ SharedTokenManager.getInstance = vi
1442
+ .fn()
1443
+ .mockReturnValue(mockTokenManager);
1444
+
1445
+ const newGenerator = new QwenContentGenerator(
1446
+ mockQwenClient,
1447
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1448
+ mockConfig,
1449
+ );
1450
+
1451
+ expect(newGenerator.getCurrentToken()).toBeNull();
1452
+
1453
+ SharedTokenManager.getInstance = originalGetInstance;
1454
+ });
1455
+
1456
+ it('should clear token through SharedTokenManager', () => {
1457
+ const mockTokenManager = {
1458
+ clearCache: vi.fn(),
1459
+ };
1460
+
1461
+ const originalGetInstance = SharedTokenManager.getInstance;
1462
+ SharedTokenManager.getInstance = vi
1463
+ .fn()
1464
+ .mockReturnValue(mockTokenManager);
1465
+
1466
+ const newGenerator = new QwenContentGenerator(
1467
+ mockQwenClient,
1468
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1469
+ mockConfig,
1470
+ );
1471
+
1472
+ newGenerator.clearToken();
1473
+
1474
+ expect(mockTokenManager.clearCache).toHaveBeenCalled();
1475
+
1476
+ SharedTokenManager.getInstance = originalGetInstance;
1477
+ });
1478
+ });
1479
+
1480
+ describe('Constructor and Initialization', () => {
1481
+ it('should initialize with default base URL', () => {
1482
+ const generator = new QwenContentGenerator(
1483
+ mockQwenClient,
1484
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1485
+ mockConfig,
1486
+ );
1487
+
1488
+ const client = (generator as unknown as { client: { baseURL: string } })
1489
+ .client;
1490
+ expect(client.baseURL).toBe(
1491
+ 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1492
+ );
1493
+ });
1494
+
1495
+ it('should get SharedTokenManager instance', () => {
1496
+ const generator = new QwenContentGenerator(
1497
+ mockQwenClient,
1498
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1499
+ mockConfig,
1500
+ );
1501
+
1502
+ const sharedManager = (
1503
+ generator as unknown as { sharedManager: SharedTokenManager }
1504
+ ).sharedManager;
1505
+ expect(sharedManager).toBeDefined();
1506
+ });
1507
+ });
1508
+
1509
+ describe('Edge Cases and Error Conditions', () => {
1510
+ it('should handle token retrieval with warning when SharedTokenManager fails', async () => {
1511
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
1512
+
1513
+ const mockTokenManager = {
1514
+ getValidCredentials: vi
1515
+ .fn()
1516
+ .mockRejectedValue(new Error('Internal token manager error')),
1517
+ };
1518
+
1519
+ const originalGetInstance = SharedTokenManager.getInstance;
1520
+ SharedTokenManager.getInstance = vi
1521
+ .fn()
1522
+ .mockReturnValue(mockTokenManager);
1523
+
1524
+ const newGenerator = new QwenContentGenerator(
1525
+ mockQwenClient,
1526
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1527
+ mockConfig,
1528
+ );
1529
+
1530
+ const request: GenerateContentParameters = {
1531
+ model: 'qwen-turbo',
1532
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
1533
+ };
1534
+
1535
+ await expect(
1536
+ newGenerator.generateContent(request, 'test-prompt-id'),
1537
+ ).rejects.toThrow('Failed to obtain valid Qwen access token');
1538
+
1539
+ expect(consoleSpy).toHaveBeenCalledWith(
1540
+ 'Failed to get token from shared manager:',
1541
+ expect.any(Error),
1542
+ );
1543
+
1544
+ consoleSpy.mockRestore();
1545
+ SharedTokenManager.getInstance = originalGetInstance;
1546
+ });
1547
+
1548
+ it('should handle all method types with token failure', async () => {
1549
+ const mockTokenManager = {
1550
+ getValidCredentials: vi
1551
+ .fn()
1552
+ .mockRejectedValue(new Error('Token error')),
1553
+ };
1554
+
1555
+ const originalGetInstance = SharedTokenManager.getInstance;
1556
+ SharedTokenManager.getInstance = vi
1557
+ .fn()
1558
+ .mockReturnValue(mockTokenManager);
1559
+
1560
+ const newGenerator = new QwenContentGenerator(
1561
+ mockQwenClient,
1562
+ { model: 'qwen-turbo', authType: AuthType.QWEN_OAUTH },
1563
+ mockConfig,
1564
+ );
1565
+
1566
+ const generateRequest: GenerateContentParameters = {
1567
+ model: 'qwen-turbo',
1568
+ contents: [{ role: 'user', parts: [{ text: 'Hello' }] }],
1569
+ };
1570
+
1571
+ const countRequest: CountTokensParameters = {
1572
+ model: 'qwen-turbo',
1573
+ contents: [{ role: 'user', parts: [{ text: 'Count' }] }],
1574
+ };
1575
+
1576
+ const embedRequest: EmbedContentParameters = {
1577
+ model: 'qwen-turbo',
1578
+ contents: [{ parts: [{ text: 'Embed' }] }],
1579
+ };
1580
+
1581
+ // All methods should fail with the same error
1582
+ await expect(
1583
+ newGenerator.generateContent(generateRequest, 'test-id'),
1584
+ ).rejects.toThrow('Failed to obtain valid Qwen access token');
1585
+
1586
+ await expect(
1587
+ newGenerator.generateContentStream(generateRequest, 'test-id'),
1588
+ ).rejects.toThrow('Failed to obtain valid Qwen access token');
1589
+
1590
+ await expect(newGenerator.countTokens(countRequest)).rejects.toThrow(
1591
+ 'Failed to obtain valid Qwen access token',
1592
+ );
1593
+
1594
+ await expect(newGenerator.embedContent(embedRequest)).rejects.toThrow(
1595
+ 'Failed to obtain valid Qwen access token',
1596
+ );
1597
+
1598
+ SharedTokenManager.getInstance = originalGetInstance;
1599
+ });
1600
+ });
1601
+ });
projects/ui/qwen-code/packages/core/src/qwen/qwenContentGenerator.ts ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { OpenAIContentGenerator } from '../core/openaiContentGenerator.js';
8
+ import { IQwenOAuth2Client } from './qwenOAuth2.js';
9
+ import { SharedTokenManager } from './sharedTokenManager.js';
10
+ import { Config } from '../config/config.js';
11
+ import {
12
+ GenerateContentParameters,
13
+ GenerateContentResponse,
14
+ CountTokensParameters,
15
+ CountTokensResponse,
16
+ EmbedContentParameters,
17
+ EmbedContentResponse,
18
+ } from '@google/genai';
19
+ import { ContentGeneratorConfig } from '../core/contentGenerator.js';
20
+
21
+ // Default fallback base URL if no endpoint is provided
22
+ const DEFAULT_QWEN_BASE_URL =
23
+ 'https://dashscope.aliyuncs.com/compatible-mode/v1';
24
+
25
+ /**
26
+ * Qwen Content Generator that uses Qwen OAuth tokens with automatic refresh
27
+ */
28
+ export class QwenContentGenerator extends OpenAIContentGenerator {
29
+ private qwenClient: IQwenOAuth2Client;
30
+ private sharedManager: SharedTokenManager;
31
+ private currentToken?: string;
32
+
33
+ constructor(
34
+ qwenClient: IQwenOAuth2Client,
35
+ contentGeneratorConfig: ContentGeneratorConfig,
36
+ config: Config,
37
+ ) {
38
+ // Initialize with empty API key, we'll override it dynamically
39
+ super(contentGeneratorConfig, config);
40
+ this.qwenClient = qwenClient;
41
+ this.sharedManager = SharedTokenManager.getInstance();
42
+
43
+ // Set default base URL, will be updated dynamically
44
+ this.client.baseURL = DEFAULT_QWEN_BASE_URL;
45
+ }
46
+
47
+ /**
48
+ * Get the current endpoint URL with proper protocol and /v1 suffix
49
+ */
50
+ private getCurrentEndpoint(resourceUrl?: string): string {
51
+ const baseEndpoint = resourceUrl || DEFAULT_QWEN_BASE_URL;
52
+ const suffix = '/v1';
53
+
54
+ // Normalize the URL: add protocol if missing, ensure /v1 suffix
55
+ const normalizedUrl = baseEndpoint.startsWith('http')
56
+ ? baseEndpoint
57
+ : `https://${baseEndpoint}`;
58
+
59
+ return normalizedUrl.endsWith(suffix)
60
+ ? normalizedUrl
61
+ : `${normalizedUrl}${suffix}`;
62
+ }
63
+
64
+ /**
65
+ * Override error logging behavior to suppress auth errors during token refresh
66
+ */
67
+ protected override shouldSuppressErrorLogging(
68
+ error: unknown,
69
+ _request: GenerateContentParameters,
70
+ ): boolean {
71
+ // Suppress logging for authentication errors that we handle with token refresh
72
+ return this.isAuthError(error);
73
+ }
74
+
75
+ /**
76
+ * Get valid token and endpoint using the shared token manager
77
+ */
78
+ private async getValidToken(): Promise<{ token: string; endpoint: string }> {
79
+ try {
80
+ // Use SharedTokenManager for consistent token/endpoint pairing and automatic refresh
81
+ const credentials = await this.sharedManager.getValidCredentials(
82
+ this.qwenClient,
83
+ );
84
+
85
+ if (!credentials.access_token) {
86
+ throw new Error('No access token available');
87
+ }
88
+
89
+ return {
90
+ token: credentials.access_token,
91
+ endpoint: this.getCurrentEndpoint(credentials.resource_url),
92
+ };
93
+ } catch (error) {
94
+ // Propagate auth errors as-is for retry logic
95
+ if (this.isAuthError(error)) {
96
+ throw error;
97
+ }
98
+ console.warn('Failed to get token from shared manager:', error);
99
+ throw new Error(
100
+ 'Failed to obtain valid Qwen access token. Please re-authenticate.',
101
+ );
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Execute an operation with automatic credential management and retry logic.
107
+ * This method handles:
108
+ * - Dynamic token and endpoint retrieval
109
+ * - Temporary client configuration updates
110
+ * - Automatic restoration of original configuration
111
+ * - Retry logic on authentication errors with token refresh
112
+ *
113
+ * @param operation - The operation to execute with updated client configuration
114
+ * @param restoreOnCompletion - Whether to restore original config after operation completes
115
+ * @returns The result of the operation
116
+ */
117
+ private async executeWithCredentialManagement<T>(
118
+ operation: () => Promise<T>,
119
+ restoreOnCompletion: boolean = true,
120
+ ): Promise<T> {
121
+ // Attempt the operation with credential management and retry logic
122
+ const attemptOperation = async (): Promise<T> => {
123
+ const { token, endpoint } = await this.getValidToken();
124
+
125
+ // Store original configuration
126
+ const originalApiKey = this.client.apiKey;
127
+ const originalBaseURL = this.client.baseURL;
128
+
129
+ // Apply dynamic configuration
130
+ this.client.apiKey = token;
131
+ this.client.baseURL = endpoint;
132
+
133
+ try {
134
+ const result = await operation();
135
+
136
+ // For streaming operations, we may need to keep the configuration active
137
+ if (restoreOnCompletion) {
138
+ this.client.apiKey = originalApiKey;
139
+ this.client.baseURL = originalBaseURL;
140
+ }
141
+
142
+ return result;
143
+ } catch (error) {
144
+ // Always restore on error
145
+ this.client.apiKey = originalApiKey;
146
+ this.client.baseURL = originalBaseURL;
147
+ throw error;
148
+ }
149
+ };
150
+
151
+ // Execute with retry logic for auth errors
152
+ try {
153
+ return await attemptOperation();
154
+ } catch (error) {
155
+ if (this.isAuthError(error)) {
156
+ try {
157
+ // Use SharedTokenManager to properly refresh and persist the token
158
+ // This ensures the refreshed token is saved to oauth_creds.json
159
+ await this.sharedManager.getValidCredentials(this.qwenClient, true);
160
+ // Retry the operation once with fresh credentials
161
+ return await attemptOperation();
162
+ } catch (_refreshError) {
163
+ throw new Error(
164
+ 'Failed to obtain valid Qwen access token. Please re-authenticate.',
165
+ );
166
+ }
167
+ }
168
+ throw error;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Override to use dynamic token and endpoint with automatic retry
174
+ */
175
+ override async generateContent(
176
+ request: GenerateContentParameters,
177
+ userPromptId: string,
178
+ ): Promise<GenerateContentResponse> {
179
+ return this.executeWithCredentialManagement(() =>
180
+ super.generateContent(request, userPromptId),
181
+ );
182
+ }
183
+
184
+ /**
185
+ * Override to use dynamic token and endpoint with automatic retry.
186
+ * Note: For streaming, the client configuration is not restored immediately
187
+ * since the generator may continue to be used after this method returns.
188
+ */
189
+ override async generateContentStream(
190
+ request: GenerateContentParameters,
191
+ userPromptId: string,
192
+ ): Promise<AsyncGenerator<GenerateContentResponse>> {
193
+ return this.executeWithCredentialManagement(
194
+ () => super.generateContentStream(request, userPromptId),
195
+ false, // Don't restore immediately for streaming
196
+ );
197
+ }
198
+
199
+ /**
200
+ * Override to use dynamic token and endpoint with automatic retry
201
+ */
202
+ override async countTokens(
203
+ request: CountTokensParameters,
204
+ ): Promise<CountTokensResponse> {
205
+ return this.executeWithCredentialManagement(() =>
206
+ super.countTokens(request),
207
+ );
208
+ }
209
+
210
+ /**
211
+ * Override to use dynamic token and endpoint with automatic retry
212
+ */
213
+ override async embedContent(
214
+ request: EmbedContentParameters,
215
+ ): Promise<EmbedContentResponse> {
216
+ return this.executeWithCredentialManagement(() =>
217
+ super.embedContent(request),
218
+ );
219
+ }
220
+
221
+ /**
222
+ * Check if an error is related to authentication/authorization
223
+ */
224
+ private isAuthError(error: unknown): boolean {
225
+ if (!error) return false;
226
+
227
+ const errorMessage =
228
+ error instanceof Error
229
+ ? error.message.toLowerCase()
230
+ : String(error).toLowerCase();
231
+
232
+ // Define a type for errors that might have status or code properties
233
+ const errorWithCode = error as {
234
+ status?: number | string;
235
+ code?: number | string;
236
+ };
237
+ const errorCode = errorWithCode?.status || errorWithCode?.code;
238
+
239
+ return (
240
+ errorCode === 401 ||
241
+ errorCode === 403 ||
242
+ errorCode === '401' ||
243
+ errorCode === '403' ||
244
+ errorMessage.includes('unauthorized') ||
245
+ errorMessage.includes('forbidden') ||
246
+ errorMessage.includes('invalid api key') ||
247
+ errorMessage.includes('invalid access token') ||
248
+ errorMessage.includes('token expired') ||
249
+ errorMessage.includes('authentication') ||
250
+ errorMessage.includes('access denied') ||
251
+ (errorMessage.includes('token') && errorMessage.includes('expired'))
252
+ );
253
+ }
254
+
255
+ /**
256
+ * Get the current cached token (may be expired)
257
+ */
258
+ getCurrentToken(): string | null {
259
+ // First check internal state for backwards compatibility with tests
260
+ if (this.currentToken) {
261
+ return this.currentToken;
262
+ }
263
+ // Fall back to SharedTokenManager
264
+ const credentials = this.sharedManager.getCurrentCredentials();
265
+ return credentials?.access_token || null;
266
+ }
267
+
268
+ /**
269
+ * Clear the cached token
270
+ */
271
+ clearToken(): void {
272
+ // Clear internal state for backwards compatibility with tests
273
+ this.currentToken = undefined;
274
+ // Also clear SharedTokenManager
275
+ this.sharedManager.clearCache();
276
+ }
277
+ }