fix: 更新默认主机地址获取逻辑,支持Docker环境

This commit is contained in:
时瑾 2025-09-12 21:56:12 +08:00
parent 69c5b78678
commit b2ff556aa6
No known key found for this signature in database
GPG Key ID: 023F70A1B8F8C196
2 changed files with 62 additions and 14 deletions

View File

@ -7,12 +7,12 @@ import { resolve } from 'node:path';
import { deepMerge } from '../utils/object';
import { themeType } from '../types/theme';
import { getRandomToken } from '../utils/url'
import { getRandomToken, getDefaultHost } from '../utils/url'
// 限制尝试端口的次数,避免死循环
// 定义配置的类型
const WebUiConfigSchema = Type.Object({
host: Type.String({ default: '127.0.0.1' }),
host: Type.String({ default: getDefaultHost() }),
port: Type.Number({ default: 6099 }),
token: Type.String({ default: getRandomToken(8) }),
loginRate: Type.Number({ default: 10 }),

View File

@ -1,10 +1,58 @@
/**
* @file URL工具
*/
import { isIP } from 'node:net';
import fs from 'node:fs'
import { isIP } from 'node:net'
import { randomBytes } from 'node:crypto'
type Protocol = 'http' | 'https'
let isDockerCached: boolean
function hasDockerEnv () {
try {
fs.statSync('/.dockerenv')
return true
} catch {
return false
}
}
function hasDockerCGroup () {
try {
return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker')
} catch {
return false
}
}
const hasContainerEnv = () => {
try {
fs.statSync('/run/.containerenv')
return true
} catch {
return false
}
}
const isDocker = () => {
if (isDockerCached === undefined) {
isDockerCached = hasContainerEnv() || hasDockerEnv() || hasDockerCGroup()
}
return isDockerCached
}
/**
* host地址
* @returns host地址
* @example getDefaultHost() => '127.0.0.1' // 非Docker环境
* @example getDefaultHost() => '0.0.0.0' // Docker环境
*/
export const getDefaultHost = (): string => {
return isDocker() ? '0.0.0.0' : '127.0.0.1'
}
/**
* host
* @param host
@ -14,9 +62,9 @@ import { randomBytes } from 'node:crypto'
* @example normalizeHost('2001:4860:4801:51::27') => '[2001:4860:4801:51::27]'
*/
export const normalizeHost = (host: string) => {
if (isIP(host) === 6) return `[${host}]`;
return host;
};
if (isIP(host) === 6) return `[${host}]`
return host
}
/**
* URL
@ -35,16 +83,16 @@ export const createUrl = (
search?: Record<string, any>,
protocol: Protocol = 'http'
) => {
const url = new URL(`${protocol}://${normalizeHost(host)}`);
url.port = port;
url.pathname = path;
const url = new URL(`${protocol}://${normalizeHost(host)}`)
url.port = port
url.pathname = path
if (search) {
for (const key in search) {
url.searchParams.set(key, search[key]);
url.searchParams.set(key, search[key])
}
}
return url.toString();
};
return url.toString()
}
/**
* Token
@ -53,5 +101,5 @@ export const createUrl = (
* @example getRandomToken
*/
export const getRandomToken = (length = 8) => {
return randomBytes(36).toString('hex').slice(0, length);
return randomBytes(36).toString('hex').slice(0, length)
}