mirror of
https://github.com/tiennm99/ccs.git
synced 2026-10-14 22:17:20 +00:00
Merge pull request #741 from kaitranntt/kai/feat/736-dashboard-remote-host-support
feat: add dashboard host binding option
This commit is contained in:
16 files changed
+734
-106
No files matched your search
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { parseConfigCommandArgs } from '../../../src/commands/config-command-options';
|
||||
|
||||
describe('config command options parser', () => {
|
||||
it('defaults to system bind behavior without explicit host', () => {
|
||||
const result = parseConfigCommandArgs([]);
|
||||
|
||||
expect(result.help).toBe(false);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.options.host).toBeUndefined();
|
||||
expect(result.options.hostProvided).toBe(false);
|
||||
});
|
||||
|
||||
it('parses explicit host and port overrides', () => {
|
||||
const result = parseConfigCommandArgs(['--host', '0.0.0.0', '--port', '4100']);
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.options.host).toBe('0.0.0.0');
|
||||
expect(result.options.hostProvided).toBe(true);
|
||||
expect(result.options.port).toBe(4100);
|
||||
});
|
||||
|
||||
it('rejects missing host values', () => {
|
||||
const result = parseConfigCommandArgs(['--host']);
|
||||
|
||||
expect(result.error).toBe('Invalid host value');
|
||||
});
|
||||
|
||||
it('accepts port 65535 and rejects port 65536', () => {
|
||||
const accepted = parseConfigCommandArgs(['--port', '65535']);
|
||||
const rejected = parseConfigCommandArgs(['--port', '65536']);
|
||||
|
||||
expect(accepted.error).toBeUndefined();
|
||||
expect(accepted.options.port).toBe(65535);
|
||||
expect(rejected.error).toBe('Invalid port number');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
const startServerCalls: Array<Record<string, unknown>> = [];
|
||||
const resolveDashboardUrlsCalls: Array<[string | undefined, number]> = [];
|
||||
let logLines: string[] = [];
|
||||
let errorLines: string[] = [];
|
||||
let dashboardAuthEnabled = false;
|
||||
let startServerError: Error | null = null;
|
||||
let mockServerBindHost = '::';
|
||||
let originalConsoleLog: typeof console.log;
|
||||
let originalConsoleError: typeof console.error;
|
||||
let originalProcessExit: typeof process.exit;
|
||||
|
||||
beforeEach(() => {
|
||||
startServerCalls.length = 0;
|
||||
resolveDashboardUrlsCalls.length = 0;
|
||||
logLines = [];
|
||||
errorLines = [];
|
||||
dashboardAuthEnabled = false;
|
||||
startServerError = null;
|
||||
mockServerBindHost = '::';
|
||||
|
||||
originalConsoleLog = console.log;
|
||||
originalConsoleError = console.error;
|
||||
originalProcessExit = process.exit;
|
||||
|
||||
console.log = (...args: unknown[]) => {
|
||||
logLines.push(args.map(String).join(' '));
|
||||
};
|
||||
console.error = (...args: unknown[]) => {
|
||||
errorLines.push(args.map(String).join(' '));
|
||||
};
|
||||
|
||||
mock.module('get-port', () => ({
|
||||
default: async () => 3000,
|
||||
}));
|
||||
|
||||
mock.module('open', () => ({
|
||||
default: async () => undefined,
|
||||
}));
|
||||
|
||||
mock.module('../../../src/web-server', () => ({
|
||||
startServer: async (options: Record<string, unknown>) => {
|
||||
startServerCalls.push({ ...options });
|
||||
if (startServerError) {
|
||||
throw startServerError;
|
||||
}
|
||||
return {
|
||||
server: {
|
||||
address: () => ({ address: mockServerBindHost }),
|
||||
} as never,
|
||||
wss: {} as never,
|
||||
cleanup: () => {},
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
mock.module('../../../src/web-server/shutdown', () => ({
|
||||
setupGracefulShutdown: () => {},
|
||||
}));
|
||||
|
||||
mock.module('../../../src/cliproxy/service-manager', () => ({
|
||||
ensureCliproxyService: async () => ({
|
||||
started: true,
|
||||
alreadyRunning: true,
|
||||
port: 8317,
|
||||
configRegenerated: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
mock.module('../../../src/cliproxy/config-generator', () => ({
|
||||
CLIPROXY_DEFAULT_PORT: 8317,
|
||||
}));
|
||||
|
||||
mock.module('../../../src/config/unified-config-loader', () => ({
|
||||
getDashboardAuthConfig: () => ({
|
||||
enabled: dashboardAuthEnabled,
|
||||
}),
|
||||
}));
|
||||
|
||||
mock.module('../../../src/utils/ui', () => ({
|
||||
initUI: async () => {},
|
||||
header: (message: string) => message,
|
||||
ok: (message: string) => message,
|
||||
info: (message: string) => message,
|
||||
warn: (message: string) => message,
|
||||
fail: (message: string) => message,
|
||||
}));
|
||||
|
||||
mock.module('../../../src/commands/config-dashboard-host', () => ({
|
||||
normalizeDashboardHost: (host: string | undefined) => {
|
||||
if (!host) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (host.startsWith('[') && host.endsWith(']') && host.includes(':')) {
|
||||
return host.slice(1, -1);
|
||||
}
|
||||
|
||||
return host;
|
||||
},
|
||||
isLoopbackHost: (host: string) =>
|
||||
['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.trim().toLowerCase()),
|
||||
isWildcardHost: (host: string) => ['0.0.0.0', '::', '[::]'].includes(host.trim().toLowerCase()),
|
||||
resolveDashboardUrls: (host: string | undefined, port: number) => {
|
||||
resolveDashboardUrlsCalls.push([host, port]);
|
||||
if (!host) {
|
||||
return { browserUrl: `http://localhost:${port}` };
|
||||
}
|
||||
|
||||
if (host === '0.0.0.0' || host === '::') {
|
||||
return {
|
||||
bindHost: host,
|
||||
browserUrl: `http://localhost:${port}`,
|
||||
networkUrls: [`http://192.168.1.25:${port}`, `http://100.64.0.12:${port}`],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
bindHost: host,
|
||||
browserUrl: `http://${host}:${port}`,
|
||||
};
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalConsoleLog;
|
||||
console.error = originalConsoleError;
|
||||
process.exit = originalProcessExit;
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
async function loadHandleConfigCommand() {
|
||||
const mod = await import(`../../../src/commands/config-command?test=${Date.now()}-${Math.random()}`);
|
||||
return mod.handleConfigCommand;
|
||||
}
|
||||
|
||||
describe('config command dashboard startup', () => {
|
||||
it('keeps the default startup path free of an explicit host override', async () => {
|
||||
const handleConfigCommand = await loadHandleConfigCommand();
|
||||
|
||||
await handleConfigCommand([]);
|
||||
|
||||
expect(startServerCalls).toHaveLength(1);
|
||||
expect(startServerCalls[0]).toEqual({ port: 3000, dev: false });
|
||||
expect(resolveDashboardUrlsCalls).toEqual([['::', 3000]]);
|
||||
|
||||
const rendered = logLines.join('\n');
|
||||
expect(rendered).toContain('Dashboard: http://localhost:3000');
|
||||
expect(rendered).toContain('Bind host: ::');
|
||||
expect(rendered).toContain('Network URLs:');
|
||||
expect(rendered).toContain('Protect it before sharing: ccs config auth setup');
|
||||
expect(errorLines).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('passes explicit wildcard hosts through and prints exposure guidance', async () => {
|
||||
const handleConfigCommand = await loadHandleConfigCommand();
|
||||
mockServerBindHost = '0.0.0.0';
|
||||
|
||||
await handleConfigCommand(['--host', '0.0.0.0', '--port', '4100']);
|
||||
|
||||
expect(startServerCalls).toHaveLength(1);
|
||||
expect(startServerCalls[0]).toEqual({ port: 4100, dev: false, host: '0.0.0.0' });
|
||||
expect(resolveDashboardUrlsCalls).toEqual([['0.0.0.0', 4100]]);
|
||||
|
||||
const rendered = logLines.join('\n');
|
||||
expect(rendered).toContain('Bind host: 0.0.0.0');
|
||||
expect(rendered).toContain('Network URLs:');
|
||||
expect(rendered).toContain('http://192.168.1.25:4100');
|
||||
expect(rendered).toContain('http://100.64.0.12:4100');
|
||||
expect(rendered).toContain(
|
||||
'Dashboard may be reachable from other devices that can connect to this machine.'
|
||||
);
|
||||
expect(rendered).toContain('Protect it before sharing: ccs config auth setup');
|
||||
expect(errorLines).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('fails cleanly when the server cannot bind the requested host', async () => {
|
||||
const handleConfigCommand = await loadHandleConfigCommand();
|
||||
startServerError = new Error(
|
||||
'Unable to bind 192.0.2.123:4100; the address may be unavailable or the port may already be in use'
|
||||
);
|
||||
process.exit = ((code?: number) => {
|
||||
throw new Error(`process.exit(${code ?? 0})`);
|
||||
}) as typeof process.exit;
|
||||
|
||||
await expect(handleConfigCommand(['--host', '192.0.2.123', '--port', '4100'])).rejects.toThrow(
|
||||
'process.exit(1)'
|
||||
);
|
||||
|
||||
expect(errorLines.join('\n')).toContain(
|
||||
'Failed to start server: Unable to bind 192.0.2.123:4100; the address may be unavailable or the port may already be in use'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import {
|
||||
isLoopbackHost,
|
||||
isWildcardHost,
|
||||
normalizeDashboardHost,
|
||||
resolveDashboardUrls,
|
||||
} from '../../../src/commands/config-dashboard-host';
|
||||
|
||||
describe('config dashboard host helpers', () => {
|
||||
it('detects loopback and wildcard hosts', () => {
|
||||
expect(isLoopbackHost('localhost')).toBe(true);
|
||||
expect(isLoopbackHost('127.0.0.1')).toBe(true);
|
||||
expect(isLoopbackHost('::1')).toBe(true);
|
||||
expect(isLoopbackHost('[::1]')).toBe(true);
|
||||
expect(isWildcardHost('0.0.0.0')).toBe(true);
|
||||
expect(isWildcardHost('::')).toBe(true);
|
||||
expect(isWildcardHost('[::]')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns localhost browser URL without network details when host is omitted', () => {
|
||||
const urls = resolveDashboardUrls(undefined, 3000, {});
|
||||
|
||||
expect(urls.bindHost).toBeUndefined();
|
||||
expect(urls.browserUrl).toBe('http://localhost:3000');
|
||||
expect(urls.networkUrls).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns localhost browser URL and all detected external URLs for wildcard host', () => {
|
||||
const urls = resolveDashboardUrls('0.0.0.0', 3000, {
|
||||
en0: [
|
||||
{
|
||||
address: '192.168.1.25',
|
||||
netmask: '255.255.255.0',
|
||||
family: 'IPv4',
|
||||
mac: '00:00:00:00:00:00',
|
||||
internal: false,
|
||||
cidr: '192.168.1.25/24',
|
||||
},
|
||||
],
|
||||
utun5: [
|
||||
{
|
||||
address: '100.64.0.12',
|
||||
family: 'IPv4',
|
||||
internal: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(urls.browserUrl).toBe('http://localhost:3000');
|
||||
expect(urls.networkUrls).toEqual(['http://192.168.1.25:3000', 'http://100.64.0.12:3000']);
|
||||
});
|
||||
|
||||
it('returns explicit host URL for loopback bindings', () => {
|
||||
const urls = resolveDashboardUrls('127.0.0.1', 3000, {});
|
||||
|
||||
expect(urls.bindHost).toBe('127.0.0.1');
|
||||
expect(urls.browserUrl).toBe('http://127.0.0.1:3000');
|
||||
expect(urls.networkUrls).toBeUndefined();
|
||||
});
|
||||
|
||||
it('normalizes bracketed IPv6 host literals for binding and URL output', () => {
|
||||
const urls = resolveDashboardUrls('[::1]', 3000, {});
|
||||
|
||||
expect(normalizeDashboardHost('[::1]')).toBe('::1');
|
||||
expect(urls.bindHost).toBe('::1');
|
||||
expect(urls.browserUrl).toBe('http://[::1]:3000');
|
||||
});
|
||||
});
|
||||
@@ -58,4 +58,17 @@ describe('help command parity', () => {
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('root help documents dashboard host binding example', async () => {
|
||||
const lines: string[] = [];
|
||||
console.log = (...args: unknown[]) => {
|
||||
lines.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
|
||||
await handleHelpCommand();
|
||||
|
||||
const rendered = stripAnsi(lines.join('\n'));
|
||||
expect(rendered.includes('ccs config --host 0.0.0.0')).toBe(true);
|
||||
expect(rendered.includes('Force all-interface binding for remote devices')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { afterEach, describe, expect, it } from 'bun:test';
|
||||
import type { AddressInfo } from 'net';
|
||||
|
||||
import { startServer } from '../../../src/web-server';
|
||||
|
||||
const instances: Array<Awaited<ReturnType<typeof startServer>>> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (instances.length > 0) {
|
||||
const instance = instances.pop();
|
||||
if (!instance) {
|
||||
continue;
|
||||
}
|
||||
|
||||
instance.cleanup();
|
||||
await new Promise<void>((resolve) => instance.server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
describe('startServer host binding', () => {
|
||||
it('binds with system-default host when no host is provided', async () => {
|
||||
const instance = await startServer({ port: 0 });
|
||||
instances.push(instance);
|
||||
|
||||
const address = instance.server.address() as AddressInfo;
|
||||
expect(address.port).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('binds to an explicit loopback host', async () => {
|
||||
const instance = await startServer({ port: 0, host: '127.0.0.1' });
|
||||
instances.push(instance);
|
||||
|
||||
const address = instance.server.address() as AddressInfo;
|
||||
expect(address.address).toBe('127.0.0.1');
|
||||
});
|
||||
|
||||
it('binds to wildcard host when requested', async () => {
|
||||
const instance = await startServer({ port: 0, host: '0.0.0.0' });
|
||||
instances.push(instance);
|
||||
|
||||
const address = instance.server.address() as AddressInfo;
|
||||
expect(['0.0.0.0', '::']).toContain(address.address);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user