fix(webui): make listener exposure explicit

Use a local-only default while preserving saved operator choices and keeping broader network access available from the settings panel.

Treat enabled encrypted transport as a startup requirement and present a dismissible notice when remote browser access is not protected.
This commit is contained in:
DrSmoothl committed 2026-08-01 16:50:08 +08:00
1 parent e4179ffb47
commit ea841d929e
12 files changed
+193 -36

No files matched your search

+3 -3
View File
@@ -7,8 +7,8 @@ export interface RuntimeConfig {
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
* Defaults to false; the Docker image flips it on in supervisord.conf. */
hookAutoLoad?: boolean;
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
/** WebUI listener bind address. '127.0.0.1' = localhost-only (default),
* '0.0.0.0' = all IPv4 interfaces. Listener-level: change needs a restart. */
webuiHost?: string;
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
* only flips serving on/off. Listener-level: change needs a restart. */
@@ -28,7 +28,7 @@ const CONFIG_DIR = 'config';
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_WEBUI_PORT = 5099;
const DEFAULT_WEBUI_HOST = '0.0.0.0';
const DEFAULT_WEBUI_HOST = '127.0.0.1';
export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
export const DEFAULT_LOG_RETAIN_DAYS = 7;
export const DEFAULT_LOG_PER_UIN = false;
+4 -4
View File
@@ -8,7 +8,7 @@ describe('normalizeRuntimeConfig', () => {
expect(normalizeRuntimeConfig({})).toEqual({
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
@@ -47,7 +47,7 @@ describe('normalizeRuntimeConfig', () => {
trustProxy: 5, // non-string → default
});
expect(out.webuiPort).toBe(5099);
expect(out.webuiHost).toBe('0.0.0.0');
expect(out.webuiHost).toBe('127.0.0.1');
expect(out.webuiTls).toEqual({ enabled: false });
expect(out.trustProxy).toBe('');
});
@@ -69,12 +69,12 @@ describe('normalizeRuntimeConfig', () => {
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
});
it('rejects a non-object input back to full defaults', () => {
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
});
});
+7 -3
View File
@@ -1,6 +1,6 @@
import net from 'net';
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
@@ -27,11 +27,15 @@ function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
* Skips reserved/invalid port numbers.
*/
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
export async function findAvailablePort(
start: number,
options: { maxTries?: number; host?: string } = {},
): Promise<number> {
const { maxTries = 50, host = '127.0.0.1' } = options;
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) break;
if (await isPortAvailable(port)) return port;
if (await isPortAvailable(port, host)) return port;
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
+8 -13
View File
@@ -47,7 +47,7 @@ import {
recordConsent,
resolveEnvironmentConsent,
} from './consent';
import { resolveTlsContext, validateTlsPair } from './tls';
import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch } from './system-settings';
import { buildBackup } from './backup';
import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore';
@@ -1538,26 +1538,21 @@ export async function initWebUI(
);
});
const finalPort = await findAvailablePort(desiredPort);
const host = listener.host || '127.0.0.1';
const finalPort = await findAvailablePort(desiredPort, { host });
if (finalPort !== desiredPort) {
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
}
boundPort = finalPort;
const host = listener.host || '0.0.0.0';
// TLS: only when explicitly enabled AND the on-disk cert/key load. A bad
// or missing cert must never brick the WebUI — fall back to HTTP + warn.
// TLS is an explicit transport promise. Once enabled, an unusable pair must
// abort startup instead of silently exposing the listener over plaintext.
let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined;
let scheme = 'http';
if (listener.tlsEnabled) {
const tls = resolveTlsContext('config');
if (tls.ok && tls.cert && tls.key) {
tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } };
scheme = 'https';
} else {
log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason);
}
const tls = requireTlsContext('config');
tlsServe = { createServer: createHttpsServer, serverOptions: tls };
scheme = 'https';
}
await new Promise<void>((resolve) => {
+14
View File
@@ -20,6 +20,11 @@ export interface TlsResolution {
reason?: string;
}
export interface RequiredTlsContext {
cert: Buffer;
key: Buffer;
}
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
@@ -55,3 +60,12 @@ export function resolveTlsContext(configDir: string): TlsResolution {
if (!valid.ok) return { ok: false, reason: valid.reason };
return { ok: true, cert, key };
}
/** Resolve the configured pair for an enabled listener or abort startup. */
export function requireTlsContext(configDir: string): RequiredTlsContext {
const resolved = resolveTlsContext(configDir);
if (!resolved.ok || !resolved.cert || !resolved.key) {
throw new Error(`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`);
}
return { cert: resolved.cert, key: resolved.key };
}
+1 -1
View File
@@ -111,7 +111,7 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
expect(JSON.parse(prepared.restore[0].data.toString('utf8'))).toEqual({
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
+18 -1
View File
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { validateTlsPair, resolveTlsContext } from '../src/webui/tls';
import { requireTlsContext, validateTlsPair, resolveTlsContext } from '../src/webui/tls';
// A throwaway self-signed pair (openssl, CN=snowluma-test). createSecureContext
// only parses — expiry is irrelevant — so this stays valid for the test forever.
@@ -99,4 +99,21 @@ describe('resolveTlsContext', () => {
expect(r.ok).toBe(false);
expect(r.reason).toBeTruthy();
});
it('refuses to start an enabled TLS listener with an unusable certificate pair', () => {
expect(() => requireTlsContext(dir)).toThrow(/TLS.*missing/i);
fs.writeFileSync(path.join(dir, 'cert.pem'), 'garbage');
fs.writeFileSync(path.join(dir, 'key.pem'), 'garbage');
expect(() => requireTlsContext(dir)).toThrow(/TLS.*invalid/i);
});
it('returns a validated certificate pair for an enabled TLS listener', () => {
fs.writeFileSync(path.join(dir, 'cert.pem'), CERT);
fs.writeFileSync(path.join(dir, 'key.pem'), KEY);
const tls = requireTlsContext(dir);
expect(tls.cert.toString()).toContain('BEGIN CERTIFICATE');
expect(tls.key.toString()).toContain('PRIVATE KEY');
});
});
+2
View File
@@ -17,6 +17,7 @@ import { DebugTaskProvider } from '@/contexts/DebugTaskContext';
import { TaskBadge } from '@/components/debug/task-badge';
import { AdaptivePointer } from '@/components/ui/adaptive-pointer';
import { GlobalContextMenu } from '@/components/ui/global-context-menu';
import { InsecureRemoteAccessBanner } from '@/components/insecure-remote-access-banner';
import {
actionErrorMessage,
ActionFeedbackProvider,
@@ -43,6 +44,7 @@ export default function App({ onboardingSteps = [] }: AppProps) {
return (
<ActionFeedbackProvider>
<ThemeProvider>
<InsecureRemoteAccessBanner />
<ActionFeedbackViewport />
<AdaptivePointer />
<GlobalContextMenu />
@@ -0,0 +1,53 @@
import { useState } from 'react';
import { AlertTriangle, X } from 'lucide-react';
import { shouldWarnAboutInsecureRemoteAccess } from '@/lib/transport-security';
const DISMISS_KEY = 'snowluma.insecure-remote-access.dismissed.v1';
function readDismissed(): boolean {
if (typeof window === 'undefined') return false;
try {
return window.localStorage.getItem(DISMISS_KEY) === '1';
} catch (error) {
console.warn('failed to read insecure transport notice preference', error);
return false;
}
}
export function InsecureRemoteAccessBanner() {
const [dismissed, setDismissed] = useState(readDismissed);
const visible = typeof window !== 'undefined'
&& shouldWarnAboutInsecureRemoteAccess(window.location)
&& !dismissed;
if (!visible) return null;
const dismiss = () => {
setDismissed(true);
try {
window.localStorage.setItem(DISMISS_KEY, '1');
} catch (error) {
console.warn('failed to persist insecure transport notice preference', error);
}
};
return (
<div
role="alert"
className="sticky top-0 z-[100] flex items-center justify-center gap-3 border-b border-amber-500/35 bg-amber-100 px-4 py-2.5 text-sm text-amber-950 shadow-sm dark:bg-amber-950 dark:text-amber-100"
>
<AlertTriangle className="size-4 shrink-0" aria-hidden="true" />
<p className="max-w-4xl leading-relaxed">
当前页面通过远程 HTTP 访问,登录凭据和操作内容可能被同网络设备读取;请在设置中启用 HTTPS,或通过受信任的 HTTPS 反向代理访问。
</p>
<button
type="button"
aria-label="关闭远程 HTTP 访问提醒"
className="ml-auto inline-flex size-8 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-amber-500/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-700"
onClick={dismiss}
>
<X className="size-4" aria-hidden="true" />
</button>
</div>
);
}
@@ -10,7 +10,6 @@ import { AlertTriangle, Database, Download, Loader2, Lock, Pencil, Save, ShieldC
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
import { Dropdown } from '@/components/interior/dropdown';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -33,7 +32,7 @@ export function SystemPanel() {
// editable form state
const [port, setPort] = useState('');
const [host, setHost] = useState('0.0.0.0');
const [host, setHost] = useState('127.0.0.1');
const [trustProxy, setTrustProxy] = useState('');
const [tlsEnabled, setTlsEnabled] = useState(false);
const [certPem, setCertPem] = useState('');
@@ -281,16 +280,28 @@ export function SystemPanel() {
</div>
<div className="flex flex-col gap-1.5">
<Label className="flex items-center">绑定地址<EnvBadge field="webuiHost" /></Label>
<Dropdown
<Input
value={host}
onChange={setHost}
label="绑定地址"
items={[
{ value: '0.0.0.0', label: '0.0.0.0(所有网卡)' },
{ value: '127.0.0.1', label: '127.0.0.1(仅本机)' },
]}
className="w-full"
onChange={(event) => setHost(event.target.value)}
placeholder="127.0.0.1"
spellCheck={false}
/>
<div className="flex flex-wrap gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => setHost('127.0.0.1')}>
仅本机
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => setHost('0.0.0.0')}>
所有网卡
</Button>
</div>
<p className={cn(
'text-xs',
host.trim() === '0.0.0.0' ? 'text-amber-700 dark:text-amber-300' : 'text-muted-foreground',
)}>
{host.trim() === '0.0.0.0'
? '所有网卡会允许局域网访问;建议同时启用 HTTPS,并设置强访问凭据。'
: '默认仅本机访问;也可填写其他明确的绑定地址。'}
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label className="flex items-center">信任代理 (trust-proxy)<EnvBadge field="trustProxy" /></Label>
@@ -358,7 +369,7 @@ export function SystemPanel() {
)}
</div>
<p className="text-xs text-muted-foreground">
私钥仅写入服务器 config/key.pem(0600 权限),不会回显。证书无效时保存会被拒绝;若启用了 TLS 但证书加载失败,启动时会自动回退到 HTTP。
私钥仅写入服务器 config/key.pem(0600 权限),不会回显。证书无效时保存会被拒绝;启用 TLS 后证书无法加载将阻止 WebUI 启动,不会降级为 HTTP。
</p>
</>
)}
@@ -0,0 +1,23 @@
const LOOPBACK_V4 = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u;
function isLoopbackIpv4(hostname: string): boolean {
const match = LOOPBACK_V4.exec(hostname);
if (!match) return false;
return match.slice(1).every((part) => Number(part) <= 255);
}
export function isLoopbackHostname(hostname: string): boolean {
const host = hostname.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '');
if (host === 'localhost' || host.endsWith('.localhost')) return true;
if (isLoopbackIpv4(host)) return true;
if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true;
if (host.startsWith('::ffff:')) return isLoopbackIpv4(host.slice('::ffff:'.length));
return false;
}
export function shouldWarnAboutInsecureRemoteAccess(location: {
protocol: string;
hostname: string;
}): boolean {
return location.protocol !== 'https:' && !isLoopbackHostname(location.hostname);
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import {
isLoopbackHostname,
shouldWarnAboutInsecureRemoteAccess,
} from '../src/lib/transport-security';
describe('WebUI transport security notice', () => {
it.each([
'localhost',
'dashboard.localhost',
'127.0.0.1',
'127.42.1.9',
'[::1]',
'0:0:0:0:0:0:0:1',
'::ffff:127.0.0.1',
])('recognizes %s as a loopback browser hostname', (hostname) => {
expect(isLoopbackHostname(hostname)).toBe(true);
});
it.each([
'0.0.0.0',
'192.168.1.20',
'10.0.0.8',
'snowluma.example.com',
'::ffff:192.168.1.20',
])('does not treat %s as loopback', (hostname) => {
expect(isLoopbackHostname(hostname)).toBe(false);
});
it('warns only when a non-loopback page is accessed without HTTPS', () => {
expect(shouldWarnAboutInsecureRemoteAccess({ protocol: 'http:', hostname: '192.168.1.20' }))
.toBe(true);
expect(shouldWarnAboutInsecureRemoteAccess({ protocol: 'https:', hostname: '192.168.1.20' }))
.toBe(false);
expect(shouldWarnAboutInsecureRemoteAccess({ protocol: 'http:', hostname: '127.0.0.1' }))
.toBe(false);
});
});