diff --git a/README.md b/README.md
index ae84faa2..69391b4f 100644
--- a/README.md
+++ b/README.md
@@ -50,9 +50,23 @@ bun add -g @kaitranntt/ccs # bun (30x faster)
```bash
ccs config
-# Opens http://localhost:3000
+# Opens a local browser URL
```
+CCS uses the runtime's system-default bind. If that bind is reachable beyond loopback,
+the CLI also prints bind/network details plus an auth reminder.
+
+Force all-interface binding for remote devices:
+
+```bash
+ccs config --host 0.0.0.0
+# Terminal prints the reachable URLs to open from the other device
+```
+
+If you expose the dashboard beyond localhost, protect it first with `ccs config auth setup`.
+
+Use `ccs config --host 127.0.0.1` to force local-only binding.
+
Dashboard updates hub: `http://localhost:3000/updates`
Want to run the dashboard in Docker or pull the prebuilt image? See `docker/README.md`.
diff --git a/docs/dashboard-auth-cli.md b/docs/dashboard-auth-cli.md
index 1449e0ec..df381442 100644
--- a/docs/dashboard-auth-cli.md
+++ b/docs/dashboard-auth-cli.md
@@ -1,12 +1,12 @@
# Dashboard Authentication CLI
-Last Updated: 2026-02-26
+Last Updated: 2026-03-17
CLI commands for managing CCS dashboard authentication.
## Overview
-The CCS dashboard (`ccs config`) can be protected with username/password authentication. This is useful when running the dashboard on a network-accessible machine.
+The CCS dashboard (`ccs config`) can be protected with username/password authentication. This is useful whenever the dashboard is reachable from another device, including when the runtime's default bind is network-accessible or when you explicitly bind it beyond loopback with `ccs config --host 0.0.0.0`.
Authentication is **disabled by default** for backward compatibility. Use the CLI to configure and enable it.
diff --git a/docs/project-roadmap.md b/docs/project-roadmap.md
index 5d47170a..17e2bd27 100644
--- a/docs/project-roadmap.md
+++ b/docs/project-roadmap.md
@@ -43,6 +43,7 @@ All major modularization work is complete. The codebase evolved from monolithic
- **#724**: Codex startup is now free-plan safe. CCS defaults new Codex sessions to a cross-plan model and auto-repairs stale paid-only Codex defaults when the active account is on the free plan.
- **#737**: Dashboard model pickers in Cursor, Copilot, and CLIProxy now use a searchable combobox with autofocus and explicit no-results states for large model catalogs.
+- **#736**: `ccs config` now supports explicit dashboard bind hosts via `--host`, and surfaces remote-access warnings plus reachable URLs when the effective bind is non-loopback.
### Maintainability Hardening Kickoff
diff --git a/src/commands/config-command-options.ts b/src/commands/config-command-options.ts
new file mode 100644
index 00000000..100f7076
--- /dev/null
+++ b/src/commands/config-command-options.ts
@@ -0,0 +1,112 @@
+import { extractOption, hasAnyFlag } from './arg-extractor';
+
+const CONFIG_COMMAND_FLAGS = ['--help', '-h', '--port', '-p', '--host', '-H', '--dev'] as const;
+
+export interface ConfigCommandOptions {
+ port?: number;
+ host?: string;
+ hostProvided: boolean;
+ dev: boolean;
+}
+
+export interface ConfigCommandParseResult {
+ help: boolean;
+ error?: string;
+ options: ConfigCommandOptions;
+}
+
+export function parseConfigCommandArgs(args: string[]): ConfigCommandParseResult {
+ const options: ConfigCommandOptions = {
+ hostProvided: false,
+ dev: false,
+ };
+
+ if (hasAnyFlag(args, ['--help', '-h'])) {
+ return { help: true, options };
+ }
+
+ const portOption = extractOption(args, ['--port', '-p'], {
+ knownFlags: CONFIG_COMMAND_FLAGS,
+ });
+ if (portOption.found) {
+ if (portOption.missingValue || !portOption.value) {
+ return { help: false, error: 'Invalid port number', options };
+ }
+
+ const port = parseInt(portOption.value, 10);
+ if (Number.isNaN(port) || port <= 0 || port >= 65536) {
+ return { help: false, error: 'Invalid port number', options };
+ }
+
+ options.port = port;
+ }
+
+ const hostOption = extractOption(portOption.remainingArgs, ['--host', '-H'], {
+ knownFlags: CONFIG_COMMAND_FLAGS,
+ });
+ if (hostOption.found) {
+ const host = hostOption.value?.trim();
+ if (hostOption.missingValue || !host) {
+ return { help: false, error: 'Invalid host value', options };
+ }
+
+ options.host = host;
+ options.hostProvided = true;
+ }
+
+ options.dev = hasAnyFlag(hostOption.remainingArgs, ['--dev']);
+
+ return { help: false, options };
+}
+
+export function showConfigCommandHelp(): void {
+ console.log('');
+ console.log('Usage: ccs config [command] [options]');
+ console.log('');
+ console.log('Open web-based configuration dashboard');
+ console.log('Includes a dedicated Claude IDE Extension page for VS Code-compatible hosts.');
+ console.log('');
+ console.log('Commands:');
+ console.log(' auth Manage dashboard authentication');
+ console.log(' auth setup Configure username and password');
+ console.log(' auth show Display current auth status');
+ console.log(' auth disable Disable authentication');
+ console.log('');
+ console.log(' image-analysis Manage image analysis settings');
+ console.log(' --enable Enable image analysis via CLIProxy');
+ console.log(' --disable Disable image analysis');
+ console.log(' --timeout Set analysis timeout (seconds)');
+ console.log(' --set-model
Set model for provider');
+ console.log('');
+ console.log(' Claude IDE Extension');
+ console.log(' Dashboard page Generate copy-ready setup for VS Code, Cursor, Windsurf');
+ console.log(' Shared settings Shows preferred ~/.claude/settings.json setup');
+ console.log(' IDE-local JSON Shows extension-specific environmentVariables snippets');
+ console.log('');
+ console.log(' thinking Manage thinking/reasoning settings');
+ console.log(' --mode Set mode (auto, off, manual)');
+ console.log(' --override Set persistent override level');
+ console.log(' --clear-override Remove persistent override');
+ console.log(' --tier Set tier default level');
+ console.log(' --provider-override Set provider tier override');
+ console.log(' --clear-provider-override [t] Remove provider override');
+ console.log('');
+ console.log('Options:');
+ console.log(' --port, -p PORT Specify server port (default: auto-detect)');
+ console.log(' --host, -H HOST Bind dashboard server host (default: system default)');
+ console.log(' --dev Development mode with Vite HMR');
+ console.log(' --help, -h Show this help message');
+ console.log('');
+ console.log('Examples:');
+ console.log(' ccs config Auto-detect available port');
+ console.log(' ccs config --port 3000 Use specific port');
+ console.log(' ccs config --host 0.0.0.0 Force all-interface binding for remote devices');
+ console.log(' ccs config --host 127.0.0.1 Restrict dashboard to this machine');
+ console.log(' ccs config --dev Development mode with hot reload');
+ console.log(' ccs config auth setup Configure dashboard login');
+ console.log(' ccs config image-analysis Show image settings');
+ console.log(' ccs config image-analysis --enable Enable feature');
+ console.log(' ccs config thinking Show thinking settings');
+ console.log(' ccs config thinking --mode auto Set auto mode');
+ console.log('');
+}
diff --git a/src/commands/config-command.ts b/src/commands/config-command.ts
index 7a7f5f4c..87afcdd5 100644
--- a/src/commands/config-command.ts
+++ b/src/commands/config-command.ts
@@ -3,7 +3,7 @@
*
* Launches web-based configuration dashboard.
* Ensures CLIProxy service is running for dashboard features.
- * Usage: ccs config [--port PORT] [--dev]
+ * Usage: ccs config [--port PORT] [--host HOST] [--dev]
*/
import getPort from 'get-port';
@@ -12,97 +12,15 @@ import { startServer } from '../web-server';
import { setupGracefulShutdown } from '../web-server/shutdown';
import { ensureCliproxyService } from '../cliproxy/service-manager';
import { CLIPROXY_DEFAULT_PORT } from '../cliproxy/config-generator';
+import { getDashboardAuthConfig } from '../config/unified-config-loader';
import { initUI, header, ok, info, warn, fail } from '../utils/ui';
-import { extractOption, hasAnyFlag } from './arg-extractor';
-
-interface ConfigOptions {
- port?: number;
- dev?: boolean;
-}
-
-/**
- * Parse command line arguments
- */
-function parseArgs(args: string[]): ConfigOptions {
- const result: ConfigOptions = {};
-
- if (hasAnyFlag(args, ['--help', '-h'])) {
- showHelp();
- process.exit(0);
- }
-
- const portOption = extractOption(args, ['--port', '-p']);
- if (portOption.found) {
- if (portOption.missingValue || !portOption.value) {
- console.error(fail('Invalid port number'));
- process.exit(1);
- }
-
- const port = parseInt(portOption.value, 10);
- if (!isNaN(port) && port > 0 && port < 65536) {
- result.port = port;
- } else {
- console.error(fail('Invalid port number'));
- process.exit(1);
- }
- }
-
- result.dev = hasAnyFlag(args, ['--dev']);
- return result;
-}
-
-/**
- * Show help message
- */
-function showHelp(): void {
- console.log('');
- console.log('Usage: ccs config [command] [options]');
- console.log('');
- console.log('Open web-based configuration dashboard');
- console.log('Includes a dedicated Claude IDE Extension page for VS Code-compatible hosts.');
- console.log('');
- console.log('Commands:');
- console.log(' auth Manage dashboard authentication');
- console.log(' auth setup Configure username and password');
- console.log(' auth show Display current auth status');
- console.log(' auth disable Disable authentication');
- console.log('');
- console.log(' image-analysis Manage image analysis settings');
- console.log(' --enable Enable image analysis via CLIProxy');
- console.log(' --disable Disable image analysis');
- console.log(' --timeout Set analysis timeout (seconds)');
- console.log(' --set-model
Set model for provider');
- console.log('');
- console.log(' Claude IDE Extension');
- console.log(' Dashboard page Generate copy-ready setup for VS Code, Cursor, Windsurf');
- console.log(' Shared settings Shows preferred ~/.claude/settings.json setup');
- console.log(' IDE-local JSON Shows extension-specific environmentVariables snippets');
- console.log('');
- console.log(' thinking Manage thinking/reasoning settings');
- console.log(' --mode Set mode (auto, off, manual)');
- console.log(' --override Set persistent override level');
- console.log(' --clear-override Remove persistent override');
- console.log(' --tier Set tier default level');
- console.log(' --provider-override Set provider tier override');
- console.log(' --clear-provider-override [t] Remove provider override');
- console.log('');
- console.log('Options:');
- console.log(' --port, -p PORT Specify server port (default: auto-detect)');
- console.log(' --dev Development mode with Vite HMR');
- console.log(' --help, -h Show this help message');
- console.log('');
- console.log('Examples:');
- console.log(' ccs config Auto-detect available port');
- console.log(' ccs config --port 3000 Use specific port');
- console.log(' ccs config --dev Development mode with hot reload');
- console.log(' ccs config auth setup Configure dashboard login');
- console.log(' ccs config Open dashboard, then choose Claude IDE Extension');
- console.log(' ccs config image-analysis Show image settings');
- console.log(' ccs config image-analysis --enable Enable feature');
- console.log(' ccs config thinking Show thinking settings');
- console.log(' ccs config thinking --mode auto Set auto mode');
- console.log('');
-}
+import {
+ isLoopbackHost,
+ isWildcardHost,
+ normalizeDashboardHost,
+ resolveDashboardUrls,
+} from './config-dashboard-host';
+import { parseConfigCommandArgs, showConfigCommandHelp } from './config-command-options';
/**
* Handle config command
@@ -131,8 +49,18 @@ export async function handleConfigCommand(args: string[]): Promise {
await initUI();
- const options = parseArgs(args);
- const verbose = options.dev || false;
+ const parsed = parseConfigCommandArgs(args);
+ if (parsed.help) {
+ showConfigCommandHelp();
+ process.exit(0);
+ }
+ if (parsed.error) {
+ console.error(fail(parsed.error));
+ process.exit(1);
+ }
+
+ const options = parsed.options;
+ const verbose = options.dev;
console.log(header('CCS Config Dashboard'));
console.log('');
@@ -167,28 +95,62 @@ export async function handleConfigCommand(args: string[]): Promise {
try {
// Start server
- const { server, wss, cleanup } = await startServer({ port, dev: options.dev });
+ const serverOptions: Parameters[0] = {
+ port,
+ dev: options.dev,
+ };
+ if (options.hostProvided && options.host) {
+ serverOptions.host = normalizeDashboardHost(options.host);
+ }
+
+ const { server, wss, cleanup } = await startServer(serverOptions);
// Setup graceful shutdown
setupGracefulShutdown(server, wss, cleanup);
- const url = `http://localhost:${port}`;
+ const urls = resolveDashboardUrls(resolveServerBindHost(server) ?? options.host, port);
+ const shouldWarnAboutExposure = urls.bindHost ? !isLoopbackHost(urls.bindHost) : false;
if (options.dev) {
- console.log(ok(`Dev Server: ${url}`));
+ console.log(ok(`Dev Server: ${urls.browserUrl}`));
console.log('');
console.log(info('HMR enabled - UI changes will hot-reload'));
} else {
- console.log(ok(`Dashboard: ${url}`));
+ console.log(ok(`Dashboard: ${urls.browserUrl}`));
+ }
+
+ if (shouldWarnAboutExposure && urls.bindHost) {
+ console.log(info(`Bind host: ${urls.bindHost}`));
+ if (urls.networkUrls?.length === 1) {
+ console.log(info(`Network URL: ${urls.networkUrls[0]}`));
+ } else if (urls.networkUrls && urls.networkUrls.length > 1) {
+ console.log(info('Network URLs:'));
+ for (const networkUrl of urls.networkUrls) {
+ console.log(info(` ${networkUrl}`));
+ }
+ }
+ }
+
+ if (shouldWarnAboutExposure && urls.bindHost) {
+ const authConfig = getDashboardAuthConfig();
+ console.log(
+ warn('Dashboard may be reachable from other devices that can connect to this machine.')
+ );
+ if (!authConfig.enabled) {
+ console.log(info('Protect it before sharing: ccs config auth setup'));
+ }
+ if (isWildcardHost(urls.bindHost) && !urls.networkUrls?.length) {
+ console.log(info('Use your machine IP or hostname from the other device.'));
+ }
}
console.log('');
// Open browser
try {
- await open(url, { wait: false });
+ await open(urls.browserUrl, { wait: false });
console.log(info('Browser opened automatically'));
} catch {
- console.log(info(`Open manually: ${url}`));
+ console.log(info(`Open manually: ${urls.browserUrl}`));
}
console.log('');
@@ -198,3 +160,14 @@ export async function handleConfigCommand(args: string[]): Promise {
process.exit(1);
}
}
+
+function resolveServerBindHost(server: {
+ address(): string | { address: string } | null;
+}): string | undefined {
+ const address = server.address();
+ if (!address || typeof address === 'string') {
+ return undefined;
+ }
+
+ return address.address;
+}
diff --git a/src/commands/config-dashboard-host.ts b/src/commands/config-dashboard-host.ts
new file mode 100644
index 00000000..e4dd8703
--- /dev/null
+++ b/src/commands/config-dashboard-host.ts
@@ -0,0 +1,106 @@
+import * as os from 'os';
+
+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
+const WILDCARD_HOSTS = new Set(['0.0.0.0', '::', '[::]']);
+
+interface NetworkInterfaceCandidate {
+ address: string;
+ family: string | number;
+ internal: boolean;
+}
+
+type NetworkInterfacesMap = Record;
+
+export interface DashboardUrls {
+ bindHost?: string;
+ browserUrl: string;
+ networkUrls?: string[];
+}
+
+export function isLoopbackHost(host: string): boolean {
+ return LOOPBACK_HOSTS.has(normalizeDashboardHost(host)?.toLowerCase() ?? '');
+}
+
+export function isWildcardHost(host: string): boolean {
+ return WILDCARD_HOSTS.has(normalizeDashboardHost(host)?.toLowerCase() ?? '');
+}
+
+export function normalizeDashboardHost(host: string | undefined): string | undefined {
+ if (!host) {
+ return undefined;
+ }
+
+ const trimmedHost = host.trim();
+ if (!trimmedHost) {
+ return undefined;
+ }
+
+ if (trimmedHost.startsWith('[') && trimmedHost.endsWith(']') && trimmedHost.includes(':')) {
+ return trimmedHost.slice(1, -1);
+ }
+
+ return trimmedHost;
+}
+
+export function resolveDashboardUrls(
+ host: string | undefined,
+ port: number,
+ networkInterfaces: NetworkInterfacesMap = os.networkInterfaces()
+): DashboardUrls {
+ const bindHost = normalizeDashboardHost(host);
+ if (!bindHost) {
+ return {
+ browserUrl: `http://localhost:${port}`,
+ };
+ }
+
+ if (isWildcardHost(bindHost)) {
+ return {
+ bindHost,
+ browserUrl: `http://localhost:${port}`,
+ networkUrls: getExternalIpv4Urls(port, networkInterfaces),
+ };
+ }
+
+ return {
+ bindHost,
+ browserUrl: `http://${formatHostForUrl(bindHost)}:${port}`,
+ };
+}
+
+function getExternalIpv4Urls(
+ port: number,
+ networkInterfaces: NetworkInterfacesMap
+): string[] | undefined {
+ const urls: string[] = [];
+ const seen = new Set();
+
+ for (const interfaceName of Object.keys(networkInterfaces)) {
+ const candidates = networkInterfaces[interfaceName];
+ if (!candidates) {
+ continue;
+ }
+
+ for (const candidate of candidates) {
+ const family =
+ typeof candidate.family === 'string' ? candidate.family : String(candidate.family);
+ if (family === 'IPv4' && !candidate.internal) {
+ const url = `http://${candidate.address}:${port}`;
+ if (!seen.has(url)) {
+ seen.add(url);
+ urls.push(url);
+ }
+ }
+ }
+ }
+
+ return urls.length > 0 ? urls : undefined;
+}
+
+function formatHostForUrl(host: string): string {
+ if (host.includes(':') && !host.startsWith('[') && !host.endsWith(']')) {
+ return `[${host}]`;
+ }
+
+ return host;
+}
diff --git a/src/commands/help-command.ts b/src/commands/help-command.ts
index 6eb794c0..85eb4aba 100644
--- a/src/commands/help-command.ts
+++ b/src/commands/help-command.ts
@@ -314,6 +314,7 @@ Run ${color('ccs config', 'command')} for web dashboard`.trim();
['ccs config thinking --mode auto', 'Set thinking mode'],
['ccs config thinking --clear-provider-override codex', 'Clear provider overrides'],
['ccs config --port 3000', 'Use specific port'],
+ ['ccs config --host 0.0.0.0', 'Force all-interface binding for remote devices'],
['ccs persist ', 'Write profile setup to ~/.claude/settings.json'],
['ccs persist --list-backups', 'List available settings.json backups'],
['ccs persist --restore', 'Restore settings.json from latest backup'],
diff --git a/src/web-server/index.ts b/src/web-server/index.ts
index 61dd2941..6ec39e00 100644
--- a/src/web-server/index.ts
+++ b/src/web-server/index.ts
@@ -17,6 +17,7 @@ import { shutdownUsageAggregator } from './usage/aggregator';
export interface ServerOptions {
port: number;
+ host?: string;
staticDir?: string;
dev?: boolean;
}
@@ -112,11 +113,56 @@ export async function startServer(options: ServerOptions): Promise((resolve) => {
- server.listen(options.port, () => {
+ return new Promise((resolve, reject) => {
+ const onError = (error: NodeJS.ErrnoException) => {
+ cleanup();
+ reject(new Error(formatListenError(error, options)));
+ };
+
+ server.once('error', onError);
+
+ const onListening = () => {
+ server.off('error', onError);
// Usage cache loads on-demand when Analytics page is visited
// This keeps server startup instant for users who don't need analytics
resolve({ server, wss, cleanup });
- });
+ };
+
+ try {
+ if (options.host) {
+ server.listen(options.port, options.host, onListening);
+ return;
+ }
+
+ server.listen(options.port, onListening);
+ } catch (error) {
+ server.off('error', onError);
+ cleanup();
+ reject(new Error(formatListenError(error as NodeJS.ErrnoException, options)));
+ }
});
}
+
+function formatListenError(error: NodeJS.ErrnoException, options: ServerOptions): string {
+ if (error.code === 'EADDRINUSE' && options.host) {
+ return `Unable to bind ${options.host}:${options.port}; the address may be unavailable or the port may already be in use`;
+ }
+
+ if (error.code === 'EADDRINUSE') {
+ return `Port ${options.port} is already in use`;
+ }
+
+ if (error.code === 'EADDRNOTAVAIL' && options.host) {
+ return `Cannot bind to ${options.host}:${options.port} on this machine`;
+ }
+
+ if (error.code === 'EACCES') {
+ return `Permission denied while binding to port ${options.port}`;
+ }
+
+ if (options.host) {
+ return `Cannot bind to ${options.host}:${options.port}: ${error.message}`;
+ }
+
+ return error.message;
+}
diff --git a/src/web-server/routes/profile-routes.ts b/src/web-server/routes/profile-routes.ts
index f26071a1..81a63055 100644
--- a/src/web-server/routes/profile-routes.ts
+++ b/src/web-server/routes/profile-routes.ts
@@ -458,3 +458,4 @@ router.delete('/:name', (req: Request, res: Response): void => {
});
export default router;
+export { parseTarget } from './route-helpers';
diff --git a/src/web-server/routes/variant-routes.ts b/src/web-server/routes/variant-routes.ts
index 7e9013ef..483bf11d 100644
--- a/src/web-server/routes/variant-routes.ts
+++ b/src/web-server/routes/variant-routes.ts
@@ -295,3 +295,4 @@ router.delete('/:name', (req: Request, res: Response): void => {
});
export default router;
+export { parseTarget } from './route-helpers';
diff --git a/tests/unit/commands/config-command-options.test.ts b/tests/unit/commands/config-command-options.test.ts
new file mode 100644
index 00000000..9c8d94ff
--- /dev/null
+++ b/tests/unit/commands/config-command-options.test.ts
@@ -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');
+ });
+});
diff --git a/tests/unit/commands/config-command.test.ts b/tests/unit/commands/config-command.test.ts
new file mode 100644
index 00000000..14d76c51
--- /dev/null
+++ b/tests/unit/commands/config-command.test.ts
@@ -0,0 +1,196 @@
+import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
+
+const startServerCalls: Array> = [];
+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) => {
+ 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'
+ );
+ });
+});
diff --git a/tests/unit/commands/config-dashboard-host.test.ts b/tests/unit/commands/config-dashboard-host.test.ts
new file mode 100644
index 00000000..a0f85c4e
--- /dev/null
+++ b/tests/unit/commands/config-dashboard-host.test.ts
@@ -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');
+ });
+});
diff --git a/tests/unit/commands/help-command-parity.test.ts b/tests/unit/commands/help-command-parity.test.ts
index 27cd4de6..2b3f6740 100644
--- a/tests/unit/commands/help-command-parity.test.ts
+++ b/tests/unit/commands/help-command-parity.test.ts
@@ -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);
+ });
});
diff --git a/tests/unit/web-server/start-server-host.test.ts b/tests/unit/web-server/start-server-host.test.ts
new file mode 100644
index 00000000..7c1204c6
--- /dev/null
+++ b/tests/unit/web-server/start-server-host.test.ts
@@ -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>> = [];
+
+afterEach(async () => {
+ while (instances.length > 0) {
+ const instance = instances.pop();
+ if (!instance) {
+ continue;
+ }
+
+ instance.cleanup();
+ await new Promise((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);
+ });
+});
diff --git a/ui/README.md b/ui/README.md
index cc1d3800..5c395658 100644
--- a/ui/README.md
+++ b/ui/README.md
@@ -18,7 +18,20 @@ From project root:
bun run dev
```
-This starts the CCS server and serves the dashboard at `http://localhost:3000`.
+This starts the CCS server, opens a local browser URL, and prints bind/network details for the dashboard.
+If the runtime bind is reachable beyond loopback, CCS also prints an auth reminder.
+
+For remote device access during development, run:
+
+```bash
+bun run dev -- --host 0.0.0.0
+```
+
+For local-only development, run:
+
+```bash
+bun run dev -- --host 127.0.0.1
+```
From `ui/` only (frontend dev server):