import { isIP } from 'node:net' import { homedir } from 'node:os' import { basename, resolve } from 'node:path' import { createPrivateKey } from 'node:crypto' import { accessSync, constants as fsConstants, existsSync, readFileSync, statSync } from 'node:fs' export interface APNsProviderConfig { keyFile: string keyId: string teamId: string topic: string } export interface ServerConfig { host: string port: number upstream: URL allowedHosts: ReadonlySet home: string mediaRoot: string attachmentsRoot: string imagesRoot: string mediaOwner: string tlsCert?: string tlsKey?: string allowInsecureLan: boolean insecureLan: boolean production: boolean superviseDashboard?: boolean yaoyaoPluginSource?: string releaseSource?: string releaseRoot?: string allowRemoteUpdate?: boolean upstreamUsername?: string upstreamPassword?: string apns?: APNsProviderConfig apnsConfigurationError?: string } export const DEFAULT_YAOYAO_PLUGIN_SOURCE = 'https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao' export const DEFAULT_YAOYAO_RELEASE_SOURCE = 'https://git.samien.cn/samien/hermes-yaoyao.git' export const DEFAULT_APNS_TOPIC = 'cn.samien.yaoyao.hermes' function flag(value: string | undefined): boolean { return value === '1' || value?.toLowerCase() === 'true' } function parsePort(value: string | undefined): number { const port = Number(value ?? '8800') if (!Number.isInteger(port) || port < 1 || port > 65_535) { throw new Error('HERMES_YAOYAO_PORT must be an integer between 1 and 65535') } return port } function parseUpstream(value: string | undefined): URL { const upstream = new URL(value ?? 'http://127.0.0.1:9119') if (!['http:', 'https:'].includes(upstream.protocol)) { throw new Error('HERMES_YAOYAO_UPSTREAM must use http or https') } if (upstream.username || upstream.password || upstream.search || upstream.hash) { throw new Error('HERMES_YAOYAO_UPSTREAM must not contain credentials, query, or fragment') } upstream.pathname = upstream.pathname.replace(/\/+$/, '') || '/' return upstream } function parsePluginSource(value: string | undefined): string { const source = value?.trim() || DEFAULT_YAOYAO_PLUGIN_SOURCE if (source.length > 2_048 || /[\u0000-\u001f\u007f]/.test(source)) { throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE is invalid') } if (source.startsWith('https://') || source.startsWith('http://')) { const url = new URL(source) if (url.username || url.password) { throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE must not contain credentials') } } else if (!source.startsWith('git@') && !source.startsWith('ssh://')) { throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE must be an HTTPS or SSH Git source') } return source } function parseReleaseSource(value: string | undefined): string { const source = value?.trim() || DEFAULT_YAOYAO_RELEASE_SOURCE if (source.length > 2_048 || /[\u0000-\u001f\u007f]/.test(source)) { throw new Error('HERMES_YAOYAO_RELEASE_SOURCE is invalid') } if (source.startsWith('https://')) { const url = new URL(source) if (url.username || url.password || url.search || url.hash) { throw new Error('HERMES_YAOYAO_RELEASE_SOURCE must not contain credentials, query, or fragment') } } else if (!source.startsWith('git@') && !source.startsWith('ssh://')) { throw new Error('HERMES_YAOYAO_RELEASE_SOURCE must be an HTTPS or SSH Git source') } return source } function parseAPNsConfiguration(env: NodeJS.ProcessEnv): { apns?: APNsProviderConfig apnsConfigurationError?: string } { const rawKeyFile = env.HERMES_YAOYAO_APNS_KEY_FILE?.trim() const keyId = env.HERMES_YAOYAO_APNS_KEY_ID?.trim() const teamId = env.HERMES_YAOYAO_APNS_TEAM_ID?.trim() const topic = env.HERMES_YAOYAO_APNS_TOPIC?.trim() || DEFAULT_APNS_TOPIC if (!rawKeyFile && !keyId && !teamId && !env.HERMES_YAOYAO_APNS_TOPIC?.trim()) return {} if (!rawKeyFile || !keyId || !teamId) { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_KEY_FILE, HERMES_YAOYAO_APNS_KEY_ID, and HERMES_YAOYAO_APNS_TEAM_ID must be set together' } } if (!/^[A-Za-z0-9]{1,128}$/.test(keyId)) { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_KEY_ID is invalid' } } if (!/^[A-Za-z0-9]{1,128}$/.test(teamId)) { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_TEAM_ID is invalid' } } if (topic.length > 255 || !/^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/.test(topic)) { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_TOPIC is invalid' } } const keyFile = resolve(rawKeyFile) try { if (!existsSync(keyFile) || !statSync(keyFile).isFile()) { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_KEY_FILE must point to a readable file' } } accessSync(keyFile, fsConstants.R_OK) const key = createPrivateKey(readFileSync(keyFile)) if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_KEY_FILE must contain an ES256 private key' } } } catch { return { apnsConfigurationError: 'HERMES_YAOYAO_APNS_KEY_FILE must contain a readable ES256 private key' } } return { apns: { keyFile, keyId, teamId, topic } } } function normalizeConfiguredHost(raw: string): string { const value = raw.trim().toLowerCase() if (!value) return '' if (value.startsWith('[') && value.endsWith(']')) return value.slice(1, -1) return value.replace(/\.$/, '') } export function isLoopbackHost(host: string): boolean { const normalized = normalizeConfiguredHost(host) if (normalized === 'localhost' || normalized === '::1') return true if (isIP(normalized) === 4) return normalized.split('.')[0] === '127' return false } export function isPrivateHost(host: string): boolean { const normalized = normalizeConfiguredHost(host) if (isLoopbackHost(normalized)) return true if (isIP(normalized) === 4) { const parts = normalized.split('.').map(Number) return parts[0] === 10 || (parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) || (parts[0] === 169 && parts[1] === 254) || (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) || (parts[0] === 192 && parts[1] === 168) } if (isIP(normalized) === 6) { return normalized.startsWith('fc') || normalized.startsWith('fd') || /^fe[89ab]/.test(normalized) } return false } export function isLoopbackUpstream(upstream: URL): boolean { return isLoopbackHost(upstream.hostname) } export function loadServerConfig( env: NodeJS.ProcessEnv = process.env, ): ServerConfig { const host = env.HERMES_YAOYAO_HOST?.trim() || '127.0.0.1' const port = parsePort(env.HERMES_YAOYAO_PORT) const upstream = parseUpstream(env.HERMES_YAOYAO_UPSTREAM) const home = resolve(env.HERMES_YAOYAO_HOME?.trim() || `${homedir()}/.hermes-yaoyao`) const mediaRoot = resolve(env.HERMES_YAOYAO_MEDIA_ROOT?.trim() || `${homedir()}/Agents`) const attachmentsRoot = resolve(`${homedir()}/.hermes/attachments`) const imagesRoot = resolve(`${homedir()}/.hermes/images`) const tlsCert = env.HERMES_YAOYAO_TLS_CERT?.trim() || undefined const tlsKey = env.HERMES_YAOYAO_TLS_KEY?.trim() || undefined if (Boolean(tlsCert) !== Boolean(tlsKey)) { throw new Error('HERMES_YAOYAO_TLS_CERT and HERMES_YAOYAO_TLS_KEY must be set together') } const allowInsecureLan = flag(env.HERMES_YAOYAO_ALLOW_INSECURE_LAN) const production = env.NODE_ENV === 'production' const superviseDashboard = flag(env.HERMES_YAOYAO_SUPERVISE_DASHBOARD) const yaoyaoPluginSource = parsePluginSource(env.HERMES_YAOYAO_PLUGIN_SOURCE) const releaseSource = parseReleaseSource(env.HERMES_YAOYAO_RELEASE_SOURCE) const releaseRoot = resolve(env.HERMES_YAOYAO_RELEASE_ROOT?.trim() || `${homedir()}/.local/share/hermes-yaoyao`) const allowRemoteUpdate = flag(env.HERMES_YAOYAO_ALLOW_REMOTE_UPDATE) const upstreamUsername = env.HERMES_YAOYAO_UPSTREAM_USERNAME?.trim() || undefined const upstreamPasswordFile = env.HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE?.trim() if (env.HERMES_YAOYAO_UPSTREAM_PASSWORD && upstreamPasswordFile) { throw new Error('Set only one of HERMES_YAOYAO_UPSTREAM_PASSWORD or HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE') } const upstreamPassword = env.HERMES_YAOYAO_UPSTREAM_PASSWORD || (upstreamPasswordFile ? readFileSync(resolve(upstreamPasswordFile), 'utf8').replace(/[\r\n]+$/, '') : undefined) const apnsConfiguration = parseAPNsConfiguration(env) const insecureLan = !tlsCert && !isLoopbackHost(host) if (production && insecureLan && !allowInsecureLan) { throw new Error( 'Plain HTTP on a non-loopback host requires HERMES_YAOYAO_ALLOW_INSECURE_LAN=1', ) } const allowedHosts = new Set( (env.HERMES_YAOYAO_ALLOWED_HOSTS ?? '') .split(',') .map(normalizeConfiguredHost) .filter(Boolean), ) return { host, port, upstream, allowedHosts, home, mediaRoot, attachmentsRoot, imagesRoot, mediaOwner: basename(homedir()), tlsCert, tlsKey, allowInsecureLan, insecureLan, production, superviseDashboard, yaoyaoPluginSource, releaseSource, releaseRoot, allowRemoteUpdate, upstreamUsername, upstreamPassword, ...apnsConfiguration, } }