🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✅ test: add unit tests for network proxy module (#10104)
LobeHub Bot17efa0bd5246
diff --git a/apps/desktop/src/main/modules/networkProxy/__tests__/dispatcher.test.ts b/apps/desktop/src/main/modules/networkProxy/__tests__/dispatcher.test.tsnew file mode 100644index 00000000000..87113daeb26--- /dev/null+++ b/apps/desktop/src/main/modules/networkProxy/__tests__/dispatcher.test.ts@@ -0,0 +1,401 @@+import { NetworkProxySettings } from '@lobechat/electron-client-ipc';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ProxyDispatcherManager } from '../dispatcher';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));++// Mock undici+vi.mock('undici', () => ({+ Agent: vi.fn(),+ ProxyAgent: vi.fn(),+ getGlobalDispatcher: vi.fn(),+ setGlobalDispatcher: vi.fn(),+}));++// Mock fetch-socks+vi.mock('fetch-socks', () => ({+ socksDispatcher: vi.fn(),+}));++// Mock ProxyUrlBuilder+vi.mock('../urlBuilder', () => ({+ ProxyUrlBuilder: {+ build: vi.fn(),+ },+}));++describe('ProxyDispatcherManager', () => {+ let mockDispatcher: any;+ let mockAgent: any;+ let mockProxyAgent: any;+ let mockGetGlobalDispatcher: any;+ let mockSetGlobalDispatcher: any;+ let mockSocksDispatcher: any;+ let mockProxyUrlBuilder: any;++ beforeEach(async () => {+ vi.clearAllMocks();++ // Import mocked modules+ const undici = await import('undici');+ const fetchSocks = await import('fetch-socks');+ const urlBuilder = await import('../urlBuilder');++ mockAgent = vi.mocked(undici.Agent);+ mockProxyAgent = vi.mocked(undici.ProxyAgent);+ mockGetGlobalDispatcher = vi.mocked(undici.getGlobalDispatcher);+ mockSetGlobalDispatcher = vi.mocked(undici.setGlobalDispatcher);+ mockSocksDispatcher = vi.mocked(fetchSocks.socksDispatcher);+ mockProxyUrlBuilder = vi.mocked(urlBuilder.ProxyUrlBuilder.build);++ // Setup mock dispatcher with destroy method+ mockDispatcher = {+ destroy: vi.fn().mockResolvedValue(undefined),+ };++ mockGetGlobalDispatcher.mockReturnValue(mockDispatcher);+ mockAgent.mockReturnValue({ destroy: vi.fn().mockResolvedValue(undefined) });+ mockProxyAgent.mockReturnValue({ destroy: vi.fn().mockResolvedValue(undefined) });+ mockSocksDispatcher.mockReturnValue({ destroy: vi.fn().mockResolvedValue(undefined) });++ // Setup ProxyUrlBuilder mock to return properly formatted URLs+ mockProxyUrlBuilder.mockImplementation((config: NetworkProxySettings) => {+ if (config.proxyRequireAuth && config.proxyUsername && config.proxyPassword) {+ return `${config.proxyType}://${config.proxyUsername}:${config.proxyPassword}@${config.proxyServer}:${config.proxyPort}`;+ }+ return `${config.proxyType}://${config.proxyServer}:${config.proxyPort}`;+ });+ });++ describe('createProxyAgent', () => {+ describe('HTTP/HTTPS proxy', () => {+ it('should create ProxyAgent for http proxy', () => {+ const proxyUrl = 'http://proxy.example.com:8080';++ ProxyDispatcherManager.createProxyAgent('http', proxyUrl);++ expect(mockProxyAgent).toHaveBeenCalledWith({ uri: proxyUrl });+ });++ it('should create ProxyAgent for https proxy', () => {+ const proxyUrl = 'https://proxy.example.com:8080';++ ProxyDispatcherManager.createProxyAgent('https', proxyUrl);++ expect(mockProxyAgent).toHaveBeenCalledWith({ uri: proxyUrl });+ });++ it('should create ProxyAgent with authentication', () => {+ const proxyUrl = 'http://user:[email protected]:8080';++ ProxyDispatcherManager.createProxyAgent('http', proxyUrl);++ expect(mockProxyAgent).toHaveBeenCalledWith({ uri: proxyUrl });+ });+ });++ describe('SOCKS5 proxy', () => {+ it('should create socksDispatcher for socks5 proxy without auth', () => {+ const proxyUrl = 'socks5://proxy.example.com:1080';++ ProxyDispatcherManager.createProxyAgent('socks5', proxyUrl);++ expect(mockSocksDispatcher).toHaveBeenCalledWith([+ {+ host: 'proxy.example.com',+ port: 1080,+ type: 5,+ },+ ]);+ });++ it('should create socksDispatcher for socks5 proxy with auth', () => {+ const proxyUrl = 'socks5://user:[email protected]:1080';++ ProxyDispatcherManager.createProxyAgent('socks5', proxyUrl);++ expect(mockSocksDispatcher).toHaveBeenCalledWith([+ {+ host: 'proxy.example.com',+ port: 1080,+ type: 5,+ userId: 'user',+ password: 'pass',+ },+ ]);+ });++ it('should create socksDispatcher with IPv4 address', () => {+ const proxyUrl = 'socks5://192.168.1.1:1080';++ ProxyDispatcherManager.createProxyAgent('socks5', proxyUrl);++ expect(mockSocksDispatcher).toHaveBeenCalledWith([+ {+ host: '192.168.1.1',+ port: 1080,+ type: 5,+ },+ ]);+ });++ it('should create socksDispatcher with different port', () => {+ const proxyUrl = 'socks5://proxy.example.com:9050';++ ProxyDispatcherManager.createProxyAgent('socks5', proxyUrl);++ expect(mockSocksDispatcher).toHaveBeenCalledWith([+ {+ host: 'proxy.example.com',+ port: 9050,+ type: 5,+ },+ ]);+ });+ });++ describe('error handling', () => {+ it('should throw error when ProxyAgent creation fails', () => {+ mockProxyAgent.mockImplementationOnce(() => {+ throw new Error('ProxyAgent creation failed');+ });++ expect(() => {+ ProxyDispatcherManager.createProxyAgent('http', 'http://invalid');+ }).toThrow('Failed to create proxy agent: ProxyAgent creation failed');+ });++ it('should throw error when socksDispatcher creation fails', () => {+ mockSocksDispatcher.mockImplementationOnce(() => {+ throw new Error('SOCKS dispatcher creation failed');+ });++ expect(() => {+ ProxyDispatcherManager.createProxyAgent('socks5', 'socks5://invalid');+ }).toThrow('Failed to create proxy agent: SOCKS dispatcher creation failed');+ });++ it('should throw error with unknown error type', () => {+ mockProxyAgent.mockImplementationOnce(() => {+ throw 'String error';+ });++ expect(() => {+ ProxyDispatcherManager.createProxyAgent('http', 'http://invalid');+ }).toThrow('Failed to create proxy agent: Unknown error');+ });+ });+ });++ describe('applyProxySettings', () => {+ const validConfig: NetworkProxySettings = {+ enableProxy: true,+ proxyType: 'http',+ proxyServer: 'proxy.example.com',+ proxyPort: '8080',+ proxyRequireAuth: false,+ proxyBypass: 'localhost,127.0.0.1,::1',+ };++ describe('disable proxy', () => {+ it('should reset to direct connection when proxy is disabled', async () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ enableProxy: false,+ };++ await ProxyDispatcherManager.applyProxySettings(config);++ expect(mockDispatcher.destroy).toHaveBeenCalled();+ expect(mockAgent).toHaveBeenCalled();+ expect(mockSetGlobalDispatcher).toHaveBeenCalled();+ });++ it('should handle dispatcher destruction failure gracefully', async () => {+ mockDispatcher.destroy.mockRejectedValueOnce(new Error('Destroy failed'));++ const config: NetworkProxySettings = {+ ...validConfig,+ enableProxy: false,+ };++ // Should not throw even if destroy fails+ await expect(ProxyDispatcherManager.applyProxySettings(config)).resolves.not.toThrow();+ });++ it('should handle dispatcher without destroy method', async () => {+ mockGetGlobalDispatcher.mockReturnValueOnce({});++ const config: NetworkProxySettings = {+ ...validConfig,+ enableProxy: false,+ };++ await expect(ProxyDispatcherManager.applyProxySettings(config)).resolves.not.toThrow();+ });+ });++ describe('enable proxy', () => {+ it('should apply http proxy settings', async () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'http',+ };++ await ProxyDispatcherManager.applyProxySettings(config);++ expect(mockDispatcher.destroy).toHaveBeenCalled();+ expect(mockProxyAgent).toHaveBeenCalledWith({+ uri: 'http://proxy.example.com:8080',+ });+ expect(mockSetGlobalDispatcher).toHaveBeenCalled();+ });++ it('should apply https proxy settings', async () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'https',+ };++ await ProxyDispatcherManager.applyProxySettings(config);++ expect(mockProxyAgent).toHaveBeenCalledWith({+ uri: 'https://proxy.example.com:8080',+ });+ });++ it('should apply socks5 proxy settings', async () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'socks5',+ };++ await ProxyDispatcherManager.applyProxySettings(config);++ expect(mockSocksDispatcher).toHaveBeenCalled();+ expect(mockSetGlobalDispatcher).toHaveBeenCalled();+ });++ it('should apply proxy with authentication', async () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: 'testpass',+ };++ await ProxyDispatcherManager.applyProxySettings(config);++ expect(mockProxyAgent).toHaveBeenCalledWith({+ uri: 'http://testuser:[email protected]:8080',+ });+ });++ it('should destroy old dispatcher before applying new proxy', async () => {+ const destroySpy = vi.fn().mockResolvedValue(undefined);+ mockGetGlobalDispatcher.mockReturnValue({ destroy: destroySpy });++ await ProxyDispatcherManager.applyProxySettings(validConfig);++ expect(destroySpy).toHaveBeenCalled();+ expect(mockSetGlobalDispatcher).toHaveBeenCalled();+ });+ });++ describe('concurrent proxy changes', () => {+ it('should queue concurrent proxy setting changes', async () => {+ const config1: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '8080',+ };++ const config2: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '8081',+ };++ // Start both operations concurrently+ const promise1 = ProxyDispatcherManager.applyProxySettings(config1);+ const promise2 = ProxyDispatcherManager.applyProxySettings(config2);++ await Promise.all([promise1, promise2]);++ // Both operations should complete successfully+ expect(mockSetGlobalDispatcher).toHaveBeenCalled();+ });++ it('should process queued operations sequentially', async () => {+ const operations: Promise<void>[] = [];++ // Queue multiple operations+ for (let i = 0; i < 5; i++) {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: `${8080 + i}`,+ };+ operations.push(ProxyDispatcherManager.applyProxySettings(config));+ }++ await Promise.all(operations);++ // All operations should complete+ expect(mockSetGlobalDispatcher).toHaveBeenCalledTimes(5);+ });++ it('should handle errors in queued operations', async () => {+ mockProxyAgent.mockReturnValueOnce({ destroy: vi.fn() }).mockImplementationOnce(() => {+ throw new Error('Agent creation failed');+ });++ const config1: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '8080',+ };++ const config2: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '8081',+ };++ const promise1 = ProxyDispatcherManager.applyProxySettings(config1);+ const promise2 = ProxyDispatcherManager.applyProxySettings(config2);++ await expect(promise1).resolves.not.toThrow();+ await expect(promise2).rejects.toThrow();+ });+ });++ describe('error handling', () => {+ it('should propagate error when agent creation fails', async () => {+ mockProxyAgent.mockImplementationOnce(() => {+ throw new Error('Agent creation failed');+ });++ await expect(ProxyDispatcherManager.applyProxySettings(validConfig)).rejects.toThrow(+ 'Failed to create proxy agent',+ );+ });++ it('should handle null dispatcher gracefully', async () => {+ mockGetGlobalDispatcher.mockReturnValueOnce(null);++ await expect(ProxyDispatcherManager.applyProxySettings(validConfig)).resolves.not.toThrow();+ });++ it('should handle undefined dispatcher gracefully', async () => {+ mockGetGlobalDispatcher.mockReturnValueOnce(undefined);++ await expect(ProxyDispatcherManager.applyProxySettings(validConfig)).resolves.not.toThrow();+ });+ });+ });+});diff --git a/apps/desktop/src/main/modules/networkProxy/__tests__/tester.test.ts b/apps/desktop/src/main/modules/networkProxy/__tests__/tester.test.tsnew file mode 100644index 00000000000..b591086bca7--- /dev/null+++ b/apps/desktop/src/main/modules/networkProxy/__tests__/tester.test.ts@@ -0,0 +1,531 @@+import { NetworkProxySettings } from '@lobechat/electron-client-ipc';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ProxyConnectionTester } from '../tester';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));++// Mock undici+vi.mock('undici', () => ({+ fetch: vi.fn(),+ getGlobalDispatcher: vi.fn(),+ setGlobalDispatcher: vi.fn(),+}));++// Mock ProxyConfigValidator+vi.mock('../validator', () => ({+ ProxyConfigValidator: {+ validate: vi.fn(),+ },+}));++// Mock ProxyUrlBuilder+vi.mock('../urlBuilder', () => ({+ ProxyUrlBuilder: {+ build: vi.fn(),+ },+}));++// Mock ProxyDispatcherManager+vi.mock('../dispatcher', () => ({+ ProxyDispatcherManager: {+ createProxyAgent: vi.fn(),+ },+}));++describe('ProxyConnectionTester', () => {+ let mockAgent: any;+ let mockOriginalDispatcher: any;+ let mockFetch: any;+ let mockGetGlobalDispatcher: any;+ let mockSetGlobalDispatcher: any;+ let mockProxyDispatcherManager: any;+ let mockProxyConfigValidator: any;+ let mockProxyUrlBuilder: any;++ beforeEach(async () => {+ vi.clearAllMocks();++ // Import mocked modules+ const undici = await import('undici');+ const dispatcher = await import('../dispatcher');+ const validator = await import('../validator');+ const urlBuilder = await import('../urlBuilder');++ mockFetch = vi.mocked(undici.fetch);+ mockGetGlobalDispatcher = vi.mocked(undici.getGlobalDispatcher);+ mockSetGlobalDispatcher = vi.mocked(undici.setGlobalDispatcher);+ mockProxyDispatcherManager = vi.mocked(dispatcher.ProxyDispatcherManager);+ mockProxyConfigValidator = vi.mocked(validator.ProxyConfigValidator);+ mockProxyUrlBuilder = vi.mocked(urlBuilder.ProxyUrlBuilder.build);++ // Setup mock agent+ mockAgent = {+ destroy: vi.fn().mockResolvedValue(undefined),+ };++ mockOriginalDispatcher = {+ destroy: vi.fn().mockResolvedValue(undefined),+ };++ mockGetGlobalDispatcher.mockReturnValue(mockOriginalDispatcher);+ mockProxyDispatcherManager.createProxyAgent.mockReturnValue(mockAgent);+ mockProxyConfigValidator.validate.mockReturnValue({ isValid: true, errors: [] });+ mockProxyUrlBuilder.mockImplementation((config: NetworkProxySettings) => {+ return `${config.proxyType}://${config.proxyServer}:${config.proxyPort}`;+ });+ });++ describe('testConnection', () => {+ describe('successful connection', () => {+ it('should return success for successful HTTP request', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testConnection();++ expect(result.success).toBe(true);+ expect(result.responseTime).toBeGreaterThanOrEqual(0);+ expect(result.message).toBeUndefined();+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://www.google.com',+ expect.objectContaining({+ headers: expect.objectContaining({+ 'User-Agent': 'LobeChat-Desktop/1.0.0',+ }),+ signal: expect.any(AbortSignal),+ }),+ );+ });++ it('should return success with custom URL', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const customUrl = 'https://api.example.com';+ const result = await ProxyConnectionTester.testConnection(customUrl);++ expect(result.success).toBe(true);+ expect(mockFetch).toHaveBeenCalledWith(customUrl, expect.any(Object));+ });++ it('should return success with custom timeout', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testConnection('https://www.google.com', 5000);++ expect(result.success).toBe(true);+ });++ it('should include response time in result', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testConnection();++ expect(result.responseTime).toBeDefined();+ expect(typeof result.responseTime).toBe('number');+ expect(result.responseTime).toBeGreaterThanOrEqual(0);+ });+ });++ describe('connection failures', () => {+ it('should return failure for HTTP error status', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 404,+ statusText: 'Not Found',+ });++ const result = await ProxyConnectionTester.testConnection();++ expect(result.success).toBe(false);+ expect(result.message).toContain('HTTP 404');+ expect(result.message).toContain('Not Found');+ expect(result.responseTime).toBeGreaterThanOrEqual(0);+ });++ it('should return failure for HTTP 500 error', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 500,+ statusText: 'Internal Server Error',+ });++ const result = await ProxyConnectionTester.testConnection();++ expect(result.success).toBe(false);+ expect(result.message).toContain('HTTP 500');+ });++ it('should return failure for network error', async () => {+ mockFetch.mockRejectedValueOnce(new Error('Network error'));++ const result = await ProxyConnectionTester.testConnection();++ expect(result.success).toBe(false);+ expect(result.message).toBe('Network error');+ expect(result.responseTime).toBeGreaterThanOrEqual(0);+ });++ it('should return failure for timeout', async () => {+ mockFetch.mockImplementationOnce(() => {+ return new Promise((_, reject) => {+ const error = new Error('Request aborted');+ error.name = 'AbortError';+ setTimeout(() => reject(error), 50);+ });+ });++ const result = await ProxyConnectionTester.testConnection('https://www.google.com', 100);++ expect(result.success).toBe(false);+ expect(result.message).toBeTruthy();+ });++ it('should return failure for connection refused', async () => {+ mockFetch.mockRejectedValueOnce(new Error('ECONNREFUSED'));++ const result = await ProxyConnectionTester.testConnection();++ expect(result.success).toBe(false);+ expect(result.message).toBe('ECONNREFUSED');+ });++ it('should handle unknown error type', async () => {+ mockFetch.mockRejectedValueOnce('String error');++ const result = await ProxyConnectionTester.testConnection();++ expect(result.success).toBe(false);+ expect(result.message).toBe('Unknown error');+ });+ });+ });++ describe('testProxyConfig', () => {+ const validConfig: NetworkProxySettings = {+ enableProxy: true,+ proxyType: 'http',+ proxyServer: 'proxy.example.com',+ proxyPort: '8080',+ proxyRequireAuth: false,+ proxyBypass: 'localhost,127.0.0.1,::1',+ };++ describe('config validation', () => {+ it('should return failure for invalid config', async () => {+ mockProxyConfigValidator.validate.mockReturnValueOnce({+ isValid: false,+ errors: ['Proxy server is required', 'Invalid port'],+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(false);+ expect(result.message).toContain('Invalid proxy configuration');+ expect(result.message).toContain('Proxy server is required');+ expect(result.message).toContain('Invalid port');+ });++ it('should validate config before testing', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(mockProxyConfigValidator.validate).toHaveBeenCalledWith(validConfig);+ });+ });++ describe('disabled proxy', () => {+ it('should test direct connection when proxy is disabled', async () => {+ const disabledConfig: NetworkProxySettings = {+ ...validConfig,+ enableProxy: false,+ };++ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testProxyConfig(disabledConfig);++ expect(result.success).toBe(true);+ expect(mockFetch).toHaveBeenCalled();+ });++ it('should use custom test URL for disabled proxy', async () => {+ const disabledConfig: NetworkProxySettings = {+ ...validConfig,+ enableProxy: false,+ };++ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const customUrl = 'https://api.example.com';+ await ProxyConnectionTester.testProxyConfig(disabledConfig, customUrl);++ expect(mockFetch).toHaveBeenCalledWith(customUrl, expect.any(Object));+ });+ });++ describe('enabled proxy', () => {+ it('should test proxy connection successfully', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(true);+ expect(result.responseTime).toBeGreaterThanOrEqual(0);+ });++ it('should create temporary proxy agent for testing', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(mockProxyDispatcherManager.createProxyAgent).toHaveBeenCalledWith(+ 'http',+ 'http://proxy.example.com:8080',+ );+ });++ it('should restore original dispatcher after test', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(mockSetGlobalDispatcher).toHaveBeenCalledWith(mockOriginalDispatcher);+ });++ it('should destroy temporary agent after test', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(mockAgent.destroy).toHaveBeenCalled();+ });++ it('should restore dispatcher even if test fails', async () => {+ mockFetch.mockRejectedValueOnce(new Error('Connection failed'));++ await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(mockSetGlobalDispatcher).toHaveBeenCalledWith(mockOriginalDispatcher);+ });++ it('should destroy agent even if test fails', async () => {+ mockFetch.mockRejectedValueOnce(new Error('Connection failed'));++ await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(mockAgent.destroy).toHaveBeenCalled();+ });++ it('should handle agent destroy failure gracefully', async () => {+ mockAgent.destroy.mockRejectedValueOnce(new Error('Destroy failed'));+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(true);+ });++ it('should test with custom URL', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const customUrl = 'https://httpbin.org/ip';+ await ProxyConnectionTester.testProxyConfig(validConfig, customUrl);++ expect(mockFetch).toHaveBeenCalledWith(+ customUrl,+ expect.objectContaining({+ dispatcher: mockAgent,+ }),+ );+ });++ it('should test socks5 proxy', async () => {+ const socks5Config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'socks5',+ };++ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ await ProxyConnectionTester.testProxyConfig(socks5Config);++ expect(mockProxyDispatcherManager.createProxyAgent).toHaveBeenCalledWith(+ 'socks5',+ expect.any(String),+ );+ });++ it('should test proxy with authentication', async () => {+ const authConfig: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: 'user',+ proxyPassword: 'pass',+ };++ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ await ProxyConnectionTester.testProxyConfig(authConfig);++ expect(mockProxyUrlBuilder).toHaveBeenCalledWith(authConfig);+ });+ });++ describe('error handling', () => {+ it('should return failure when agent creation fails', async () => {+ mockProxyDispatcherManager.createProxyAgent.mockImplementationOnce(() => {+ throw new Error('Agent creation failed');+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(false);+ expect(result.message).toContain('Proxy test failed');+ expect(result.message).toContain('Agent creation failed');+ });++ it('should return failure when fetch fails', async () => {+ mockFetch.mockRejectedValueOnce(new Error('Connection timeout'));++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(false);+ expect(result.message).toContain('Connection timeout');+ });++ it('should return failure for HTTP error response', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 407,+ statusText: 'Proxy Authentication Required',+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(false);+ expect(result.message).toContain('HTTP 407');+ });++ it('should handle timeout correctly', async () => {+ mockFetch.mockImplementationOnce(() => {+ return new Promise((_, reject) => {+ setTimeout(() => reject(new Error('Timeout')), 50);+ });+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(false);+ });++ it('should handle unknown error type', async () => {+ mockProxyDispatcherManager.createProxyAgent.mockImplementationOnce(() => {+ throw 'String error';+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(false);+ expect(result.message).toContain('Unknown error');+ });++ it('should handle null agent', async () => {+ mockProxyDispatcherManager.createProxyAgent.mockReturnValueOnce(null);++ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ // Should handle gracefully+ expect(result).toBeDefined();+ });++ it('should handle agent without destroy method', async () => {+ mockProxyDispatcherManager.createProxyAgent.mockReturnValueOnce({});++ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ statusText: 'OK',+ });++ const result = await ProxyConnectionTester.testProxyConfig(validConfig);++ expect(result.success).toBe(true);+ });+ });+ });+});diff --git a/apps/desktop/src/main/modules/networkProxy/__tests__/urlBuilder.test.ts b/apps/desktop/src/main/modules/networkProxy/__tests__/urlBuilder.test.tsnew file mode 100644index 00000000000..e5718582774--- /dev/null+++ b/apps/desktop/src/main/modules/networkProxy/__tests__/urlBuilder.test.ts@@ -0,0 +1,349 @@+import { NetworkProxySettings } from '@lobechat/electron-client-ipc';+import { describe, expect, it } from 'vitest';++import { ProxyUrlBuilder } from '../urlBuilder';++describe('ProxyUrlBuilder', () => {+ const baseConfig: NetworkProxySettings = {+ enableProxy: true,+ proxyType: 'http',+ proxyServer: 'proxy.example.com',+ proxyPort: '8080',+ proxyRequireAuth: false,+ proxyBypass: 'localhost,127.0.0.1,::1',+ };++ describe('build', () => {+ describe('without authentication', () => {+ it('should build URL with http proxy type', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyType: 'http',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:8080');+ });++ it('should build URL with https proxy type', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyType: 'https',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('https://proxy.example.com:8080');+ });++ it('should build URL with socks5 proxy type', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyType: 'socks5',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('socks5://proxy.example.com:8080');+ });++ it('should build URL with IPv4 address', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyServer: '192.168.1.1',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://192.168.1.1:8080');+ });++ it('should build URL with localhost', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyServer: 'localhost',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://localhost:8080');+ });++ it('should build URL with different port', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyPort: '3128',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:3128');+ });+ });++ describe('with authentication', () => {+ it('should build URL with username and password', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: 'testpass',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://testuser:[email protected]:8080');+ });++ it('should build URL with encoded username containing @ symbol', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: '[email protected]',+ proxyPassword: 'password',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://user%40domain.com:[email protected]:8080');+ // Verify encoding+ expect(url).toContain('user%40domain.com');+ });++ it('should build URL with encoded password containing colon', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'user',+ proxyPassword: 'pass:word',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://user:pass%[email protected]:8080');+ // Verify encoding+ expect(url).toContain('pass%3Aword');+ });++ it('should build URL with encoded special characters in username', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'user name',+ proxyPassword: 'password',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://user%20name:[email protected]:8080');+ // Verify encoding+ expect(url).toContain('user%20name');+ });++ it('should build URL with encoded special characters in password', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'user',+ proxyPassword: 'p@ss w0rd!',+ };++ const url = ProxyUrlBuilder.build(config);++ // Verify encoding of special characters+ expect(url).toContain(encodeURIComponent('p@ss w0rd!'));+ expect(url).toContain('user:');+ expect(url).toContain('@proxy.example.com:8080');+ });++ it('should build URL with encoded slash in credentials', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'domain/user',+ proxyPassword: 'pass/word',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://domain%2Fuser:pass%[email protected]:8080');+ // Verify encoding+ expect(url).toContain('domain%2Fuser');+ expect(url).toContain('pass%2Fword');+ });++ it('should build URL with encoded hash in credentials', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'user#123',+ proxyPassword: 'pass#word',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://user%23123:pass%[email protected]:8080');+ // Verify encoding+ expect(url).toContain('user%23123');+ expect(url).toContain('pass%23word');+ });++ it('should build URL with encoded question mark in credentials', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'user?name',+ proxyPassword: 'pass?word',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://user%3Fname:pass%[email protected]:8080');+ // Verify encoding+ expect(url).toContain('user%3Fname');+ expect(url).toContain('pass%3Fword');+ });++ it('should build URL with https proxy type and auth', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyType: 'https',+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: 'testpass',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('https://testuser:[email protected]:8080');+ });++ it('should build URL with socks5 proxy type and auth', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyType: 'socks5',+ proxyRequireAuth: true,+ proxyUsername: 'sockuser',+ proxyPassword: 'sockpass',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('socks5://sockuser:[email protected]:8080');+ });+ });++ describe('edge cases', () => {+ it('should not include auth when proxyRequireAuth is false but credentials are provided', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: false,+ proxyUsername: 'testuser',+ proxyPassword: 'testpass',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:8080');+ expect(url).not.toContain('testuser');+ expect(url).not.toContain('testpass');+ });++ it('should not include auth when username is empty', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: '',+ proxyPassword: 'testpass',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:8080');+ expect(url).not.toContain('@');+ });++ it('should not include auth when password is empty', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: '',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:8080');+ expect(url).not.toContain('@');+ });++ it('should not include auth when username is undefined', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: undefined,+ proxyPassword: 'testpass',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:8080');+ expect(url).not.toContain('@');+ });++ it('should not include auth when password is undefined', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: undefined,+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:8080');+ expect(url).not.toContain('@');+ });++ it('should handle minimum port number', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyPort: '1',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:1');+ });++ it('should handle maximum port number', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyPort: '65535',+ };++ const url = ProxyUrlBuilder.build(config);++ expect(url).toBe('http://proxy.example.com:65535');+ });++ it('should handle complex URL encoding scenario', () => {+ const config: NetworkProxySettings = {+ ...baseConfig,+ proxyRequireAuth: true,+ proxyUsername: '[email protected]:admin',+ proxyPassword: 'p@ss:w0rd#123',+ };++ const url = ProxyUrlBuilder.build(config);++ // Verify all special characters are encoded+ const expectedUsername = encodeURIComponent('[email protected]:admin');+ const expectedPassword = encodeURIComponent('p@ss:w0rd#123');++ expect(url).toBe(`http://${expectedUsername}:${expectedPassword}@proxy.example.com:8080`);+ });+ });+ });+});diff --git a/apps/desktop/src/main/modules/networkProxy/__tests__/validator.test.ts b/apps/desktop/src/main/modules/networkProxy/__tests__/validator.test.tsnew file mode 100644index 00000000000..5b5ecb7e123--- /dev/null+++ b/apps/desktop/src/main/modules/networkProxy/__tests__/validator.test.ts@@ -0,0 +1,492 @@+import { NetworkProxySettings } from '@lobechat/electron-client-ipc';+import { describe, expect, it } from 'vitest';++import { ProxyConfigValidator } from '../validator';++describe('ProxyConfigValidator', () => {+ const validConfig: NetworkProxySettings = {+ enableProxy: true,+ proxyType: 'http',+ proxyServer: 'proxy.example.com',+ proxyPort: '8080',+ proxyRequireAuth: false,+ proxyBypass: 'localhost,127.0.0.1,::1',+ };++ describe('validate', () => {+ describe('disabled proxy', () => {+ it('should validate successfully when proxy is disabled', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ enableProxy: false,+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should skip validation for disabled proxy even with invalid fields', () => {+ const config: NetworkProxySettings = {+ enableProxy: false,+ proxyType: 'invalid' as any,+ proxyServer: '',+ proxyPort: 'invalid',+ proxyRequireAuth: false,+ proxyBypass: 'localhost',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });+ });++ describe('proxy type validation', () => {+ it('should accept http proxy type', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'http',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept https proxy type', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'https',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept socks5 proxy type', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'socks5',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should reject unsupported proxy type', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'socks4' as any,+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toHaveLength(1);+ expect(result.errors[0]).toContain('Unsupported proxy type');+ expect(result.errors[0]).toContain('socks4');+ });++ it('should reject invalid proxy type', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyType: 'ftp' as any,+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors[0]).toContain('Supported types: http, https, socks5');+ });+ });++ describe('proxy server validation', () => {+ it('should accept valid domain name', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: 'proxy.example.com',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept valid IPv4 address', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: '192.168.1.1',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept localhost', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: 'localhost',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept subdomain', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: 'proxy.subdomain.example.com',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should reject empty proxy server', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: '',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy server is required when proxy is enabled');+ });++ it('should reject whitespace-only proxy server', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: ' ',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy server is required when proxy is enabled');+ });++ it('should reject invalid domain format', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: 'invalid..domain',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Invalid proxy server format');+ });++ it('should reject domain starting with hyphen', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: '-proxy.com',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Invalid proxy server format');+ });++ it('should reject domain with invalid characters', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: '[email protected]',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Invalid proxy server format');+ });+ });++ describe('proxy port validation', () => {+ it('should accept valid port 1', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '1',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept valid port 65535', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '65535',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should accept common proxy port 8080', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '8080',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should reject empty proxy port', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy port is required when proxy is enabled');+ });++ it('should reject whitespace-only proxy port', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: ' ',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy port is required when proxy is enabled');+ });++ it('should reject port 0', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '0',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy port must be a valid number between 1 and 65535');+ });++ it('should reject port above 65535', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '65536',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy port must be a valid number between 1 and 65535');+ });++ it('should reject negative port', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: '-1',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy port must be a valid number between 1 and 65535');+ });++ it('should reject non-numeric port', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyPort: 'abc',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain('Proxy port must be a valid number between 1 and 65535');+ });+ });++ describe('authentication validation', () => {+ it('should validate successfully with auth disabled', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: false,+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should validate successfully with auth enabled and credentials provided', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: 'testpass',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should reject when auth is enabled but username is missing', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: '',+ proxyPassword: 'testpass',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain(+ 'Proxy username is required when authentication is enabled',+ );+ });++ it('should reject when auth is enabled but username is whitespace', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: ' ',+ proxyPassword: 'testpass',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain(+ 'Proxy username is required when authentication is enabled',+ );+ });++ it('should reject when auth is enabled but password is missing', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: '',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain(+ 'Proxy password is required when authentication is enabled',+ );+ });++ it('should reject when auth is enabled but password is whitespace', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: 'testuser',+ proxyPassword: ' ',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toContain(+ 'Proxy password is required when authentication is enabled',+ );+ });++ it('should reject when auth is enabled but both username and password are missing', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: true,+ proxyUsername: '',+ proxyPassword: '',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toHaveLength(2);+ expect(result.errors).toContain(+ 'Proxy username is required when authentication is enabled',+ );+ expect(result.errors).toContain(+ 'Proxy password is required when authentication is enabled',+ );+ });++ it('should allow missing credentials when auth is disabled', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyRequireAuth: false,+ proxyUsername: undefined,+ proxyPassword: undefined,+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });+ });++ describe('multiple validation errors', () => {+ it('should collect all validation errors', () => {+ const config: NetworkProxySettings = {+ enableProxy: true,+ proxyType: 'invalid' as any,+ proxyServer: '',+ proxyPort: 'abc',+ proxyRequireAuth: true,+ proxyUsername: '',+ proxyPassword: '',+ proxyBypass: 'localhost',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors.length).toBeGreaterThan(1);+ });++ it('should collect errors for invalid server and port', () => {+ const config: NetworkProxySettings = {+ ...validConfig,+ proxyServer: 'invalid..domain',+ proxyPort: '99999',+ };++ const result = ProxyConfigValidator.validate(config);++ expect(result.isValid).toBe(false);+ expect(result.errors).toHaveLength(2);+ expect(result.errors).toContain('Invalid proxy server format');+ expect(result.errors).toContain('Proxy port must be a valid number between 1 and 65535');+ });+ });+ });+});