lynx-proxy 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["parseToml","loadYAML","asOptionalRecord","asRecord","PROFILE_EXTENSIONS","asRecord","legacyState","requireArg","stringifyToml","dumpYaml","stringifyToml","dumpYaml","ipv6ToBuffer"],"sources":["../src/config/models.ts","../src/router/rules.ts","../src/config/validator.ts","../src/config/loader.ts","../src/config/subscription.ts","../src/config/user-config.ts","../src/cli/config-cli.ts","../src/runtime/daemon-state.ts","../src/runtime/control.ts","../src/cli/groups-cli.ts","../src/logging/logger.ts","../src/transport/tcp.ts","../src/protocol/direct.ts","../src/protocol/socks5.ts","../src/utils/Crypto.ts","../src/protocol/trojan.ts","../src/protocol/base.ts","../src/http/parser.ts","../src/router/matcher.ts","../src/transport/relay.ts","../src/server/handler.ts","../src/server/http-server.ts","../src/runtime/proxy-runner.ts","../src/cli/proxy-cli.ts","../src/cli/index.ts","../src/index.ts"],"sourcesContent":["export class ConfigError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nexport type RouteAction = \"DIRECT\" | \"PROXY\";\n\nexport type ProxyType = \"direct\" | \"socks5\" | \"trojan\";\n\nexport type RuleMatchType =\n | \"domain\"\n | \"domain_suffix\"\n | \"domain_keyword\"\n | \"ip\"\n | \"ip_cidr\"\n | \"ip_cidr6\"\n | \"port\"\n | \"scheme\"\n | \"geoip\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type ClashLogLevel = LogLevel | \"silent\" | \"warning\";\n\nexport type ClashProxyType = ProxyType | \"socks\";\n\nexport type ProxyGroupType = \"select\";\n\nexport type ProfileMode = \"global\" | \"rule\" | \"direct\" | \"script\";\n\nexport interface UserProfileConfig {\n port: number;\n \"socks-port\"?: number;\n \"allow-lan\"?: boolean;\n \"bind-address\"?: string;\n mode?: ProfileMode;\n \"log-level\"?: ClashLogLevel;\n \"access-log\"?: boolean;\n \"log-file\"?: string;\n \"connect-timeout-ms\"?: number;\n \"idle-timeout-ms\"?: number;\n proxies?: ClashProxyConfig[];\n \"proxy-groups\"?: ProxyGroupConfig[];\n rules?: string[];\n}\n\nexport interface ProxySelectionConfig {\n \"proxy-groups\"?: Record<string, string>;\n}\n\nexport interface LynxConfigState {\n version: 1;\n files: ProfileStateEntry[];\n}\n\nexport interface ProfileStateEntry {\n name: string;\n time?: string | undefined;\n url?: string | undefined;\n selected: ProxyGroupSelection[];\n interval?: number | undefined;\n subInfo?: SubscriptionInfo | undefined;\n homeWeb?: string | undefined;\n mode?: ProfileMode | undefined;\n cron?: string | undefined;\n headers?: string | undefined;\n}\n\nexport interface ProxyGroupSelection {\n name: string;\n now: string;\n}\n\nexport interface SubscriptionInfo {\n upload: number;\n download: number;\n total: number;\n expire: number;\n}\n\nexport interface RuntimeUserConfig {\n profile: string;\n}\n\nexport type LynxStateConfig = LynxConfigState;\n\nexport interface BaseClashProxyConfig {\n name: string;\n type: ClashProxyType;\n}\n\nexport interface DirectClashProxyConfig extends BaseClashProxyConfig {\n type: \"direct\";\n}\n\nexport interface SocksClashProxyConfig extends BaseClashProxyConfig {\n type: \"socks\" | \"socks5\";\n server: string;\n port: number;\n username?: string;\n password?: string;\n}\n\nexport interface TrojanClashProxyConfig extends BaseClashProxyConfig {\n type: \"trojan\";\n server: string;\n port: number;\n password: string;\n sni?: string;\n \"skip-cert-verify\"?: boolean;\n}\n\nexport type ClashProxyConfig =\n | DirectClashProxyConfig\n | SocksClashProxyConfig\n | TrojanClashProxyConfig;\n\nexport interface ProxyGroupConfig {\n name: string;\n type: ProxyGroupType;\n proxies: string[];\n}\n\nexport interface ServerConfig {\n host: string;\n port: number;\n connectTimeoutMs: number;\n idleTimeoutMs: number;\n}\n\nexport interface RouteConfig {\n default: RouteAction;\n defaultProxy?: string;\n}\n\nexport interface UserConfig {\n proxyGroupSelections: Record<string, string>;\n}\n\nexport interface LogConfig {\n level: LogLevel;\n access: boolean;\n file?: string;\n}\n\nexport interface BaseProxyConfig {\n name: string;\n type: ProxyType;\n}\n\nexport interface DirectProxyConfig extends BaseProxyConfig {\n type: \"direct\";\n}\n\nexport interface Socks5ProxyConfig extends BaseProxyConfig {\n type: \"socks5\";\n host: string;\n port: number;\n username?: string;\n password?: string;\n}\n\nexport interface TrojanProxyConfig extends BaseProxyConfig {\n type: \"trojan\";\n host: string;\n port: number;\n password: string;\n serverName: string;\n allowInvalidCert: boolean;\n}\n\nexport type ProxyConfig =\n | DirectProxyConfig\n | Socks5ProxyConfig\n | TrojanProxyConfig;\n\nexport interface RuleConfig {\n name: string;\n action: RouteAction;\n match: RuleMatchType;\n value: string;\n proxy?: string; // 代理组名(如 \"PROXY\")或具体代理名,运行时根据当前选择解析\n}\n\nexport interface AppConfig {\n server: ServerConfig;\n route: RouteConfig;\n user: UserConfig;\n log: LogConfig;\n proxies: ProxyConfig[];\n proxyGroups: ProxyGroupConfig[];\n rules: RuleConfig[];\n mode?: ProfileMode;\n}\n","import type { AppConfig, RuleMatchType } from \"../config/models.js\";\nimport { ConfigError } from \"../config/models.js\";\n\nexport interface RouteTarget {\n host: string;\n port: number;\n scheme?: string;\n method?: string;\n}\n\nexport interface RouteResult {\n action: \"DIRECT\" | \"PROXY\";\n ruleName: string;\n proxyName?: string;\n}\n\nexport interface ClashRuleTarget {\n action: \"DIRECT\" | \"PROXY\";\n targetName: string; // 代理组名(如 \"PROXY\")或具体代理名\n}\n\nexport interface ClashMatchRule {\n kind: \"match\";\n target: ClashRuleTarget;\n}\n\nexport type ClashRuleParseResult = AppConfig[\"rules\"][number] | ClashMatchRule;\n\nexport type ClashTargetResolver = (target: string) => ClashRuleTarget;\n\nconst MATCH_TYPES: ReadonlySet<string> = new Set([\n \"domain\",\n \"domain_suffix\",\n \"domain_keyword\",\n \"ip\",\n \"ip_cidr\",\n \"ip_cidr6\",\n \"port\",\n \"scheme\",\n \"geoip\"\n]);\n\nconst DIRECT_MATCH_TYPES: ReadonlySet<RuleMatchType> = new Set([\n \"domain\",\n \"domain_suffix\",\n \"domain_keyword\",\n \"ip\",\n \"ip_cidr\",\n \"ip_cidr6\",\n \"port\",\n \"scheme\",\n \"geoip\"\n]);\n\nconst CLASH_RULE_TYPES: ReadonlyMap<string, RuleMatchType> = new Map([\n [\"DOMAIN\", \"domain\"],\n [\"DOMAIN-SUFFIX\", \"domain_suffix\"],\n [\"DOMAIN-KEYWORD\", \"domain_keyword\"],\n [\"IP-CIDR\", \"ip_cidr\"],\n [\"IP-CIDR6\", \"ip_cidr6\"],\n [\"GEOIP\", 'geoip']\n]);\n\nexport function isRuleMatchType(value: string): value is RuleMatchType {\n return MATCH_TYPES.has(value);\n}\n\nexport function isDirectMatchType(value: RuleMatchType): boolean {\n return DIRECT_MATCH_TYPES.has(value);\n}\n\nexport function parseRuleItem(\n item: string,\n defaultProxy?: string,\n): AppConfig[\"rules\"][number] {\n const parts = item.split(\",\").map((part: string): string => part.trim());\n const action = parts[0];\n\n if (action === \"DIRECT\") {\n if (parts.length !== 4) {\n throw new ConfigError(`DIRECT rule must have 4 fields: ${item}`);\n }\n\n const match = parts[1];\n const value = parts[2];\n const name = parts[3];\n ensureNonEmpty(match, \"match\", item);\n ensureNonEmpty(value, \"value\", item);\n ensureNonEmpty(name, \"name\", item);\n\n if (!isRuleMatchType(match)) {\n throw new ConfigError(\n `Unknown rule match type \"${match}\" in: ${item}`,\n );\n }\n if (!isDirectMatchType(match)) {\n throw new ConfigError(\n `DIRECT rule uses unsupported match type in: ${item}`,\n );\n }\n\n return { action: \"DIRECT\", match, value, name };\n }\n\n if (action === \"PROXY\") {\n if (parts.length !== 4 && parts.length !== 5) {\n throw new ConfigError(\n `PROXY rule must have 4 or 5 fields: ${item}`,\n );\n }\n\n const match = parts[1];\n const value = parts[2];\n const proxyOrName = parts[3];\n ensureNonEmpty(match, \"match\", item);\n ensureNonEmpty(value, \"value\", item);\n ensureNonEmpty(\n proxyOrName,\n parts.length === 5 ? \"proxy\" : \"name\",\n item,\n );\n\n if (!isRuleMatchType(match)) {\n throw new ConfigError(\n `Unknown rule match type \"${match}\" in: ${item}`,\n );\n }\n\n if (parts.length === 5) {\n const name = parts[4];\n ensureNonEmpty(name, \"name\", item);\n return { action: \"PROXY\", match, value, proxy: proxyOrName, name };\n }\n\n if (defaultProxy === undefined || defaultProxy.length === 0) {\n throw new ConfigError(\n `PROXY rule without proxy requires route.default_proxy: ${item}`,\n );\n }\n\n return {\n action: \"PROXY\",\n match,\n value,\n proxy: defaultProxy,\n name: proxyOrName,\n };\n }\n\n throw new ConfigError(\n `Unknown rule action \"${String(action)}\" in: ${item}`,\n );\n}\n\nexport function parseClashRuleItem(\n item: string,\n index: number,\n resolveTarget: ClashTargetResolver,\n): ClashRuleParseResult {\n const parts = item.split(\",\").map((part: string): string => part.trim());\n const type = parts[0]?.toUpperCase();\n\n if (type === \"MATCH\") {\n if (parts.length !== 2) {\n throw new ConfigError(`MATCH rule must have 2 fields: ${item}`);\n }\n const target = parts[1];\n ensureNonEmpty(target, \"target\", item);\n return { kind: \"match\", target: resolveTarget(target) };\n }\n\n if (type === undefined) {\n throw new ConfigError(\n `Unsupported Clash rule type \"${String(parts[0])}\" in: ${item}`,\n );\n }\n\n const match = CLASH_RULE_TYPES.get(type);\n if (match === undefined) {\n throw new ConfigError(\n `Unsupported Clash rule type \"${String(parts[0])}\" in: ${item}`,\n );\n }\n if (parts.length < 3) {\n throw new ConfigError(\n `Clash rule must have at least 3 fields: ${item}`,\n );\n }\n\n const value = parts[1];\n const target = parts[2];\n ensureNonEmpty(value, \"value\", item);\n ensureNonEmpty(target, \"target\", item);\n\n const resolved = resolveTarget(target);\n const name = `${type}:${value || index}`;\n if (resolved.action === \"DIRECT\") {\n return { action: \"DIRECT\", match, value, name };\n }\n return { action: \"PROXY\", match, value, proxy: resolved.targetName, name };\n}\n\nfunction ensureNonEmpty(\n value: string | undefined,\n field: string,\n item: string,\n): asserts value is string {\n if (value === undefined || value.length === 0) {\n throw new ConfigError(`Rule field ${field} is empty in: ${item}`);\n }\n}\n","import { ConfigError } from \"./models.js\";\nimport type {\n AppConfig,\n DirectProxyConfig,\n LogConfig,\n LogLevel,\n ProxyConfig,\n ProxyType,\n RouteAction,\n RouteConfig,\n ServerConfig,\n TrojanProxyConfig,\n UserConfig,\n} from \"./models.js\";\nimport { isRuleMatchType } from \"../router/rules.js\";\n\nconst ROUTE_ACTIONS: ReadonlySet<string> = new Set([\"DIRECT\", \"PROXY\"]);\nconst PROXY_TYPES: ReadonlySet<string> = new Set([\n \"direct\",\n \"socks5\",\n \"trojan\",\n]);\nconst LOG_LEVELS: ReadonlySet<string> = new Set([\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n]);\n\nexport function validateConfig(config: AppConfig): void {\n validateServer(config.server);\n validateRoute(config.route);\n validateLog(config.log);\n validateUser(config.user);\n validateProxies(config.proxies);\n validateRules(config);\n}\n\nexport function assertRouteAction(\n value: string,\n field: string,\n): asserts value is RouteAction {\n if (!ROUTE_ACTIONS.has(value)) {\n throw new ConfigError(`${field} must be DIRECT or PROXY`);\n }\n}\n\nexport function assertProxyType(\n value: string,\n field: string,\n): asserts value is ProxyType {\n if (!PROXY_TYPES.has(value)) {\n throw new ConfigError(`${field} has unsupported proxy type: ${value}`);\n }\n}\n\nexport function assertLogLevel(\n value: string,\n field: string,\n): asserts value is LogLevel {\n if (!LOG_LEVELS.has(value)) {\n throw new ConfigError(`${field} has unsupported log level: ${value}`);\n }\n}\n\nexport function validatePort(port: number, field: string): void {\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new ConfigError(`${field} must be an integer from 1 to 65535`);\n }\n}\n\nfunction validateServer(server: ServerConfig): void {\n validateNonEmptyString(server.host, \"server.host\");\n validatePort(server.port, \"server.port\");\n validatePositiveInteger(\n server.connectTimeoutMs,\n \"server.connect_timeout_ms\",\n );\n validatePositiveInteger(server.idleTimeoutMs, \"server.idle_timeout_ms\");\n}\n\nfunction validateRoute(route: RouteConfig): void {\n assertRouteAction(route.default, \"route.default\");\n if (route.default === \"PROXY\") {\n validateNonEmptyString(route.defaultProxy, \"route.default_proxy\");\n }\n}\n\nfunction validateLog(log: LogConfig): void {\n assertLogLevel(log.level, \"log.level\");\n if (log.file !== undefined) {\n validateNonEmptyString(log.file, \"log.file\");\n }\n}\n\nfunction validateUser(user: UserConfig): void {\n for (const [groupName, proxyName] of Object.entries(user.proxyGroupSelections)) {\n validateNonEmptyString(groupName, \"user.proxyGroupSelections group name\");\n validateNonEmptyString(\n proxyName,\n `user.proxyGroupSelections.${groupName}`,\n );\n }\n}\n\nfunction validateProxies(proxies: ProxyConfig[]): void {\n const names = new Set<string>();\n for (const proxy of proxies) {\n validateNonEmptyString(proxy.name, \"proxy.name\");\n assertProxyType(proxy.type, `proxy ${proxy.name}.type`);\n\n if (names.has(proxy.name)) {\n throw new ConfigError(`Duplicate proxy name: ${proxy.name}`);\n }\n names.add(proxy.name);\n\n if (proxy.type === \"socks5\") {\n validateNonEmptyString(proxy.host, `proxy ${proxy.name}.host`);\n validatePort(proxy.port, `proxy ${proxy.name}.port`);\n validateOptionalPair(proxy.username, proxy.password, proxy.name);\n } else if (proxy.type === \"trojan\") {\n validateTrojanProxy(proxy);\n } else {\n validateDirectProxy(proxy);\n }\n }\n}\n\nfunction validateDirectProxy(proxy: DirectProxyConfig): void {\n if (proxy.type !== \"direct\") {\n throw new ConfigError(`Invalid direct proxy type: ${proxy.name}`);\n }\n}\n\nfunction validateTrojanProxy(proxy: TrojanProxyConfig): void {\n validateNonEmptyString(proxy.host, `proxy ${proxy.name}.host`);\n validatePort(proxy.port, `proxy ${proxy.name}.port`);\n validateNonEmptyString(proxy.password, `proxy ${proxy.name}.password`);\n validateNonEmptyString(proxy.serverName, `proxy ${proxy.name}.server_name`);\n}\n\nfunction validateRules(config: AppConfig): void {\n const proxyNames = new Set(\n config.proxies.map((proxy: ProxyConfig): string => proxy.name),\n );\n const proxyGroupNames = new Set(\n config.proxyGroups.map((group): string => group.name),\n );\n\n // Validate route.defaultProxy: can be a proxy name or proxy group name\n if (\n config.route.defaultProxy !== undefined &&\n !proxyNames.has(config.route.defaultProxy) &&\n !proxyGroupNames.has(config.route.defaultProxy)\n ) {\n throw new ConfigError(\n `route.default_proxy references unknown proxy or proxy-group: ${config.route.defaultProxy}`,\n );\n }\n\n for (const rule of config.rules) {\n validateNonEmptyString(rule.name, \"rule.name\");\n if (!isRuleMatchType(rule.match)) {\n throw new ConfigError(\n `Rule ${rule.name} has unsupported match type: ${rule.match}`,\n );\n }\n\n if (rule.action === \"DIRECT\") {\n if (rule.proxy !== undefined) {\n throw new ConfigError(\n `DIRECT rule ${rule.name} must not specify proxy`,\n );\n }\n } else {\n const proxyName = rule.proxy ?? config.route.defaultProxy;\n if (proxyName === undefined || proxyName.length === 0) {\n throw new ConfigError(\n `PROXY rule ${rule.name} requires a proxy or route.default_proxy`,\n );\n }\n // PROXY rule target can be a proxy name OR a proxy group name\n if (!proxyNames.has(proxyName) && !proxyGroupNames.has(proxyName)) {\n throw new ConfigError(\n `Rule ${rule.name} references unknown proxy or proxy-group: ${proxyName}`,\n );\n }\n }\n\n if (rule.match === \"port\") {\n validatePort(Number(rule.value), `rule ${rule.name}.value`);\n }\n }\n}\n\nfunction validateNonEmptyString(\n value: string | undefined,\n field: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ConfigError(`${field} must be a non-empty string`);\n }\n}\n\nfunction validatePositiveInteger(value: number, field: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new ConfigError(`${field} must be a positive integer`);\n }\n}\n\nfunction validateOptionalPair(\n username: string | undefined,\n password: string | undefined,\n proxyName: string,\n): void {\n if ((username === undefined) !== (password === undefined)) {\n throw new ConfigError(\n `SOCKS5 proxy ${proxyName} requires both username and password when using authentication`,\n );\n }\n}\n","import { load as loadYAML } from 'js-yaml';\nimport { readFileSync } from \"node:fs\";\nimport { extname } from \"node:path\";\nimport { parse as parseToml } from 'smol-toml';\nimport type { ClashRuleTarget } from \"../router/rules.js\";\nimport { parseClashRuleItem } from \"../router/rules.js\";\nimport type {\n AppConfig,\n LogConfig,\n ProxyConfig,\n ProxyGroupConfig,\n ProxySelectionConfig,\n RouteConfig,\n ServerConfig,\n Socks5ProxyConfig,\n UserConfig\n} from \"./models.js\";\nimport { ConfigError } from \"./models.js\";\nimport { validateConfig } from \"./validator.js\";\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 10_000;\nconst DEFAULT_IDLE_TIMEOUT_MS = 60_000;\n\nexport function parseConfigFile(file: string, content: string): unknown {\n const ext = extname(file);\n switch (ext) {\n case \".json\":\n return JSON.parse(content);\n case \".toml\":\n return parseToml(content);\n case \".yml\":\n case \".yaml\":\n return loadYAML(content);\n default:\n throw new ConfigError(`Unsupported config file extension: ${ext}`);\n }\n}\n\nexport function loadConfig(configPath: string): AppConfig {\n const content = readFileSync(configPath, \"utf8\");\n const raw = parseConfigFile(configPath, content) as unknown;\n return loadConfigFromRaw(raw);\n}\n\nexport function loadConfigFromRaw(raw: unknown): AppConfig {\n const config = parseAppConfig(raw);\n validateConfig(config);\n return config;\n}\n\nexport function applyProfileState(\n raw: Record<string, unknown>,\n state: ProxySelectionConfig | undefined,\n): Record<string, unknown> {\n if (state === undefined) {\n return cloneRecord(raw);\n }\n\n const effective = cloneRecord(raw);\n\n if (state[\"proxy-groups\"] !== undefined) {\n const baseUser = asOptionalRecord(effective[\"user\"], \"user\");\n const user: Record<string, unknown> = { ...baseUser };\n const baseSelections = asOptionalRecord(\n user[\"proxy-groups\"],\n \"user.proxy-groups\",\n );\n user[\"proxy-groups\"] = {\n ...baseSelections,\n ...state[\"proxy-groups\"],\n };\n effective[\"user\"] = user;\n }\n\n return effective;\n}\n\nexport default class Loader {\n public config: AppConfig | null = null;\n\n public loadConfig(path: string): AppConfig {\n const config = loadConfig(path);\n this.config = config;\n return config;\n }\n}\n\nfunction parseAppConfig(raw: unknown): AppConfig {\n const object = asRecord(raw, \"config\");\n rejectLegacyAppConfig(object);\n return parseClashStyleAppConfig(object);\n}\n\nfunction rejectLegacyAppConfig(object: Record<string, unknown>): void {\n if (object[\"server\"] !== undefined || object[\"route\"] !== undefined) {\n throw new ConfigError(\n \"Legacy internal config shape is no longer supported. Profile configs must use Clash-style fields such as top-level port, proxies[].server, proxy-groups, and rules[].\",\n );\n }\n\n const rules = object[\"rules\"];\n if (\n typeof rules === \"object\" &&\n rules !== null &&\n !Array.isArray(rules) &&\n \"items\" in rules\n ) {\n throw new ConfigError(\n \"Legacy rules.items config shape is no longer supported. Use Clash-style top-level rules as a string array.\",\n );\n }\n\n const proxies = object[\"proxies\"];\n if (!Array.isArray(proxies)) {\n return;\n }\n proxies.forEach((proxy: unknown, index: number): void => {\n if (typeof proxy !== \"object\" || proxy === null || Array.isArray(proxy)) {\n return;\n }\n if (\n \"host\" in proxy ||\n \"server_name\" in proxy ||\n \"allow_invalid_cert\" in proxy\n ) {\n throw new ConfigError(\n `Legacy proxy fields are no longer supported at proxies[${index}]. Use Clash-style server, sni, and skip-cert-verify fields.`,\n );\n }\n });\n}\n\nfunction parseClashStyleAppConfig(object: Record<string, unknown>): AppConfig {\n const proxies = parseClashProxies(object[\"proxies\"]);\n const proxyNames = new Set(\n proxies.map((proxy: ProxyConfig): string => proxy.name),\n );\n const proxyGroups = parseProxyGroups(object[\"proxy-groups\"]);\n const user = parseUserConfig(object[\"user\"]);\n resolveProxyGroups(proxyGroups, proxyNames); // validate group structure\n const resolveTarget = (target: string): ClashRuleTarget => {\n if (target === \"DIRECT\") {\n return { action: \"DIRECT\", targetName: \"DIRECT\" };\n }\n if (proxyNames.has(target)) {\n return { action: \"PROXY\", targetName: target };\n }\n if (proxyGroups.some((g) => g.name === target)) {\n return { action: \"PROXY\", targetName: target };\n }\n throw new ConfigError(`Unknown Clash rule target: ${target}`);\n };\n const parsedRules = parseClashRules(object[\"rules\"], resolveTarget);\n const userConfig = toUserConfig(user);\n\n return {\n server: parseClashServerConfig(object),\n route: parsedRules.route,\n user: userConfig,\n log: parseClashLogConfig(object),\n proxies,\n proxyGroups,\n rules: parsedRules.rules,\n };\n}\n\nfunction parseClashServerConfig(object: Record<string, unknown>): ServerConfig {\n const allowLan = getOptionalBoolean(object, \"allow-lan\", false);\n return {\n host:\n getOptionalString(object, \"bind-address\") ??\n (allowLan ? \"0.0.0.0\" : \"127.0.0.1\"),\n port: getRequiredNumber(object, \"port\", \"port\"),\n connectTimeoutMs: getOptionalNumber(\n object,\n \"connect-timeout-ms\",\n DEFAULT_CONNECT_TIMEOUT_MS,\n ),\n idleTimeoutMs: getOptionalNumber(\n object,\n \"idle-timeout-ms\",\n DEFAULT_IDLE_TIMEOUT_MS,\n ),\n };\n}\n\nfunction parseClashLogConfig(object: Record<string, unknown>): LogConfig {\n if (process.env[\"NODE_ENV\"] == \"development\") {\n return withOptionalLogFile(\n { level: \"debug\", access: true },\n getOptionalString(object, \"log-file\"),\n );\n }\n\n const rawLevel = getOptionalString(object, \"log-level\") ?? \"debug\";\n const access = getOptionalBoolean(\n object,\n \"access-log\",\n true,\n );\n if (rawLevel === \"silent\") {\n return withOptionalLogFile(\n { level: \"error\", access },\n getOptionalString(object, \"log-file\"),\n );\n }\n if (rawLevel === \"warning\") {\n return withOptionalLogFile(\n { level: \"warn\", access },\n getOptionalString(object, \"log-file\"),\n );\n }\n if (\n rawLevel !== \"debug\" &&\n rawLevel !== \"info\" &&\n rawLevel !== \"warn\" &&\n rawLevel !== \"error\"\n ) {\n throw new ConfigError(\n \"log-level must be silent, debug, info, warning, warn or error\",\n );\n }\n return withOptionalLogFile(\n { level: rawLevel, access },\n getOptionalString(object, \"log-file\"),\n );\n}\n\nfunction withOptionalLogFile(config: LogConfig, file: string | undefined): LogConfig {\n if (file === undefined) {\n return config;\n }\n return { ...config, file };\n}\n\nfunction parseClashProxies(raw: unknown): ProxyConfig[] {\n if (raw === undefined) {\n return [];\n }\n if (!Array.isArray(raw)) {\n throw new ConfigError(\"proxies must be an array\");\n }\n\n return raw.map(\n (item: unknown, index: number): ProxyConfig =>\n parseClashProxy(item, index),\n );\n}\n\nfunction parseClashProxy(raw: unknown, index: number): ProxyConfig {\n const object = asRecord(raw, `proxies[${index}]`);\n const name = getRequiredString(object, \"name\", `proxies[${index}].name`);\n const rawType = getRequiredString(object, \"type\", `proxy ${name}.type`);\n const type = rawType === \"socks\" ? \"socks5\" : rawType;\n\n if (type === \"direct\") {\n return { name, type };\n }\n\n if (type === \"socks5\") {\n const username = getOptionalString(object, \"username\");\n const password = getOptionalString(object, \"password\");\n const proxy: Socks5ProxyConfig = {\n name,\n type,\n host: getRequiredString(object, \"server\", `proxy ${name}.server`),\n port: getRequiredNumber(object, \"port\", `proxy ${name}.port`),\n };\n if (username !== undefined) {\n proxy.username = username;\n }\n if (password !== undefined) {\n proxy.password = password;\n }\n return proxy;\n }\n\n if (type === \"trojan\") {\n const host = getRequiredString(\n object,\n \"server\",\n `proxy ${name}.server`,\n );\n const serverName = getOptionalString(object, \"sni\") ?? host;\n return {\n name,\n type,\n host,\n port: getRequiredNumber(object, \"port\", `proxy ${name}.port`),\n password: getRequiredString(\n object,\n \"password\",\n `proxy ${name}.password`,\n ),\n serverName,\n allowInvalidCert: getOptionalBoolean(\n object,\n \"skip-cert-verify\",\n false,\n ),\n };\n }\n\n throw new ConfigError(\n `Unsupported proxy type \"${rawType}\" for proxy ${name}`,\n );\n}\n\nfunction parseUserConfig(raw: unknown): ProxySelectionConfig {\n if (raw === undefined) {\n return { \"proxy-groups\": {} };\n }\n\n const object = asRecord(raw, \"user\");\n const proxyGroupSelections = parseStringRecord(\n object[\"proxy-groups\"],\n \"user.proxy-groups\",\n );\n return { \"proxy-groups\": proxyGroupSelections };\n}\n\nfunction toUserConfig(user: ProxySelectionConfig): UserConfig {\n const proxyGroupSelections = user[\"proxy-groups\"] ?? {};\n return { proxyGroupSelections };\n}\n\nfunction parseProxyGroups(raw: unknown): ProxyGroupConfig[] {\n if (raw === undefined) {\n return [];\n }\n if (!Array.isArray(raw)) {\n throw new ConfigError(\"proxy-groups must be an array\");\n }\n\n return raw.map((item: unknown, index: number): ProxyGroupConfig => {\n const object = asRecord(item, `proxy-groups[${index}]`);\n const name = getRequiredString(\n object,\n \"name\",\n `proxy-groups[${index}].name`,\n );\n const type = getRequiredString(\n object,\n \"type\",\n `proxy-group ${name}.type`,\n );\n if (type !== \"select\") {\n throw new ConfigError(\n `Unsupported proxy-group type \"${type}\" for ${name}`,\n );\n }\n return {\n name,\n type,\n proxies: getRequiredStringArray(\n object,\n \"proxies\",\n `proxy-group ${name}.proxies`,\n ),\n };\n });\n}\n\nfunction resolveProxyGroups(\n groups: ProxyGroupConfig[],\n proxyNames: ReadonlySet<string>,\n): Map<string, string[]> {\n const groupsByName = new Map(\n groups.map((group: ProxyGroupConfig): [string, ProxyGroupConfig] => [\n group.name,\n group,\n ]),\n );\n const resolved = new Map<string, string[]>();\n const visiting = new Set<string>();\n\n const resolveGroup = (name: string): string[] => {\n const cached = resolved.get(name);\n if (cached !== undefined) {\n return cached;\n }\n if (visiting.has(name)) {\n throw new ConfigError(`proxy-groups contains a cycle at ${name}`);\n }\n\n const group = groupsByName.get(name);\n if (group === undefined) {\n throw new ConfigError(`Unknown proxy-group: ${name}`);\n }\n\n visiting.add(name);\n const resolvedProxies: string[] = [];\n for (const candidate of group.proxies) {\n if (candidate === \"DIRECT\") {\n resolvedProxies.push(\"DIRECT\");\n } else if (proxyNames.has(candidate)) {\n resolvedProxies.push(candidate);\n } else if (groupsByName.has(candidate)) {\n const nested = resolveGroup(candidate);\n resolvedProxies.push(...nested);\n }\n }\n\n visiting.delete(name);\n if (resolvedProxies.length === 0) {\n throw new ConfigError(\n `proxy-group ${name} has no resolvable proxy`,\n );\n }\n resolved.set(name, resolvedProxies);\n return resolvedProxies;\n };\n\n for (const group of groups) {\n resolveGroup(group.name);\n }\n return resolved;\n}\n\nfunction parseClashRules(\n raw: unknown,\n resolveTarget: (target: string) => ClashRuleTarget,\n): { route: RouteConfig; rules: AppConfig[\"rules\"] } {\n if (raw === undefined) {\n return { route: { default: \"DIRECT\" }, rules: [] };\n }\n if (!Array.isArray(raw)) {\n throw new ConfigError(\"rules must be an array\");\n }\n\n let route: RouteConfig = { default: \"DIRECT\" };\n const rules: AppConfig[\"rules\"] = [];\n raw.forEach((item: unknown, index: number): void => {\n if (typeof item !== \"string\") {\n throw new ConfigError(`rules[${index}] must be a string`);\n }\n\n const rule = parseClashRuleItem(item, index, resolveTarget);\n if (\"kind\" in rule) {\n route = routeFromTarget(rule.target);\n return;\n }\n rules.push(rule);\n });\n\n return { route, rules };\n}\n\nfunction routeFromTarget(target: ClashRuleTarget): RouteConfig {\n if (target.action === \"DIRECT\") {\n return { default: \"DIRECT\" };\n }\n return { default: \"PROXY\", defaultProxy: target.targetName };\n}\n\nfunction parseStringRecord(raw: unknown, field: string): Record<string, string> {\n if (raw === undefined) {\n return {};\n }\n const object = asRecord(raw, field);\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(object)) {\n if (key.trim().length === 0) {\n throw new ConfigError(`${field} keys must be non-empty strings`);\n }\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ConfigError(`${field}.${key} must be a non-empty string`);\n }\n result[key] = value;\n }\n return result;\n}\n\nfunction asRecord(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigError(`${field} must be a table`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction asOptionalRecord(value: unknown, field: string): Record<string, unknown> {\n if (value === undefined) {\n return {};\n }\n return asRecord(value, field);\n}\n\nfunction cloneRecord(raw: Record<string, unknown>): Record<string, unknown> {\n return structuredClone(raw) as Record<string, unknown>;\n}\n\nfunction getRequiredString(\n object: Record<string, unknown>,\n key: string,\n field: string,\n): string {\n const value = object[key];\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ConfigError(`${field} must be a non-empty string`);\n }\n return value;\n}\n\nfunction getOptionalString(\n object: Record<string, unknown>,\n key: string,\n): string | undefined {\n const value = object[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\") {\n throw new ConfigError(`${key} must be a string`);\n }\n return value;\n}\n\nfunction getRequiredNumber(\n object: Record<string, unknown>,\n key: string,\n field: string,\n): number {\n const value = object[key];\n if (typeof value !== \"number\") {\n throw new ConfigError(`${field} must be a number`);\n }\n return value;\n}\n\nfunction getOptionalNumber(\n object: Record<string, unknown>,\n key: string,\n defaultValue: number,\n): number {\n const value = object[key];\n if (value === undefined) {\n return defaultValue;\n }\n if (typeof value !== \"number\") {\n throw new ConfigError(`${key} must be a number`);\n }\n return value;\n}\n\nfunction getOptionalBoolean(\n object: Record<string, unknown>,\n key: string,\n defaultValue: boolean,\n): boolean {\n const value = object[key];\n if (value === undefined) {\n return defaultValue;\n }\n if (typeof value !== \"boolean\") {\n throw new ConfigError(`${key} must be a boolean`);\n }\n return value;\n}\n\nfunction getRequiredStringArray(\n object: Record<string, unknown>,\n key: string,\n field: string,\n): string[] {\n const value = object[key];\n if (!Array.isArray(value) || value.length === 0) {\n throw new ConfigError(`${field} must be a non-empty array`);\n }\n\n return value.map((item: unknown, index: number): string => {\n if (typeof item !== \"string\" || item.trim().length === 0) {\n throw new ConfigError(\n `${field}[${index}] must be a non-empty string`,\n );\n }\n return item;\n });\n}\n","import type { SubscriptionInfo } from \"./models.js\";\nimport { ConfigError } from \"./models.js\";\n\n// 机场通常按 User-Agent 决定是否返回 Clash 格式,这里默认使用类 clash 的 UA。\nconst DEFAULT_USER_AGENT = \"clash-verge/v1.6.0\";\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nexport interface FetchSubscriptionOptions {\n userAgent?: string | undefined;\n timeoutMs?: number | undefined;\n}\n\nexport interface SubscriptionResult {\n content: string;\n subInfo?: SubscriptionInfo | undefined;\n fileName?: string | undefined;\n}\n\n// 从订阅 URL 抓取配置文本与元数据。只负责 “URL → 文本 + 元数据”,\n// 解析、校验、落盘仍由调用方走现有路径。\nexport async function fetchSubscription(\n url: string,\n options: FetchSubscriptionOptions = {},\n): Promise<SubscriptionResult> {\n const userAgent = options.userAgent ?? DEFAULT_USER_AGENT;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n let response: Response;\n try {\n response = await fetch(url, {\n headers: { \"User-Agent\": userAgent },\n redirect: \"follow\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new ConfigError(`Failed to fetch subscription ${url}: ${reason}`);\n }\n\n if (!response.ok) {\n throw new ConfigError(\n `Subscription request failed: ${response.status} ${response.statusText} (${url})`,\n );\n }\n\n const content = await response.text();\n const subInfo = parseSubscriptionUserinfo(\n response.headers.get(\"subscription-userinfo\"),\n );\n const fileName = parseContentDispositionFilename(\n response.headers.get(\"content-disposition\"),\n );\n\n return { content, subInfo, fileName };\n}\n\n// 解析 Subscription-Userinfo 响应头,格式形如:\n// \"upload=123; download=456; total=789; expire=1700000000\"\n// 缺失字段按 0 处理;整个头缺失时返回 undefined。\nexport function parseSubscriptionUserinfo(\n header: string | null | undefined,\n): SubscriptionInfo | undefined {\n if (header === null || header === undefined || header.trim().length === 0) {\n return undefined;\n }\n\n const fields: Record<string, number> = {};\n for (const part of header.split(\";\")) {\n const [rawKey, rawValue] = part.split(\"=\");\n if (rawKey === undefined || rawValue === undefined) {\n continue;\n }\n const key = rawKey.trim().toLowerCase();\n const value = Number(rawValue.trim());\n if (key.length > 0 && Number.isFinite(value)) {\n fields[key] = value;\n }\n }\n\n return {\n upload: fields[\"upload\"] ?? 0,\n download: fields[\"download\"] ?? 0,\n total: fields[\"total\"] ?? 0,\n expire: fields[\"expire\"] ?? 0,\n };\n}\n\n// 解析 Content-Disposition 响应头中的 filename,支持 filename=\"x\" 和\n// RFC 5987 的 filename*=UTF-8''x 两种形式。无法解析时返回 undefined。\nexport function parseContentDispositionFilename(\n header: string | null | undefined,\n): string | undefined {\n if (header === null || header === undefined) {\n return undefined;\n }\n\n const extended = /filename\\*\\s*=\\s*(?:UTF-8'')?([^;]+)/i.exec(header);\n if (extended?.[1] !== undefined) {\n const value = extended[1].trim().replace(/^[\"']|[\"']$/g, \"\");\n try {\n return decodeURIComponent(value) || undefined;\n } catch {\n return value || undefined;\n }\n }\n\n const plain = /filename\\s*=\\s*(\"?)([^\";]+)\\1/i.exec(header);\n if (plain?.[2] !== undefined) {\n return plain[2].trim() || undefined;\n }\n\n return undefined;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, extname, isAbsolute, join } from \"node:path\";\nimport {\n applyProfileState,\n loadConfig,\n loadConfigFromRaw,\n parseConfigFile,\n} from \"./loader.js\";\nimport type {\n AppConfig,\n LynxConfigState,\n ProfileStateEntry,\n ProxyGroupSelection,\n ProxySelectionConfig,\n RuntimeUserConfig,\n} from \"./models.js\";\nimport { ConfigError } from \"./models.js\";\n\nconst APP_CONFIG_DIR = \"lynx-proxy\";\nconst USER_CONFIG_FILE = \"user.json\";\nconst STATE_CONFIG_FILE = \"state.json\";\nconst PROFILE_DIR = \"profile\";\nconst LEGACY_CONFIG_PATH = \"config.toml\";\nconst DEFAULT_USER_CONFIG: RuntimeUserConfig = { profile: \"default\" };\nconst PROFILE_EXTENSIONS = [\".toml\", \".yaml\", \".yml\", \".json\"] as const;\n\nexport function getLynxConfigHome(): string {\n const xdgConfigHome = process.env[\"XDG_CONFIG_HOME\"];\n if (xdgConfigHome !== undefined && xdgConfigHome.length > 0) {\n return join(xdgConfigHome, APP_CONFIG_DIR);\n }\n return join(homedir(), \".config\", APP_CONFIG_DIR);\n}\n\nexport function getDefaultUserConfigPath(): string {\n return join(getLynxConfigHome(), USER_CONFIG_FILE);\n}\n\nexport function getDefaultStateConfigPath(): string {\n return join(getLynxConfigHome(), STATE_CONFIG_FILE);\n}\n\nexport function getDefaultProfileDir(): string {\n return join(getLynxConfigHome(), PROFILE_DIR);\n}\n\nexport function loadLynxUserConfig(\n userConfigPath: string = getDefaultUserConfigPath(),\n): RuntimeUserConfig {\n ensureDefaultUserConfig(userConfigPath);\n const content = readFileSync(userConfigPath, \"utf8\");\n const raw = parseConfigFile(userConfigPath, content);\n const object = asRecord(raw, \"user config\");\n const profile = object[\"profile\"];\n if (typeof profile !== \"string\" || profile.trim().length === 0) {\n throw new ConfigError(\"user config profile must be a non-empty string\");\n }\n return { profile: profile.trim() };\n}\n\nexport function ensureDefaultUserConfig(\n userConfigPath: string = getDefaultUserConfigPath(),\n): void {\n mkdirSync(dirname(userConfigPath), { recursive: true });\n mkdirSync(getDefaultProfileDir(), { recursive: true });\n if (existsSync(userConfigPath)) {\n return;\n }\n writeLynxUserConfig(DEFAULT_USER_CONFIG, userConfigPath);\n}\n\nexport function writeLynxUserConfig(\n config: RuntimeUserConfig,\n userConfigPath: string = getDefaultUserConfigPath(),\n): void {\n mkdirSync(dirname(userConfigPath), { recursive: true });\n writeFileSync(\n userConfigPath,\n `${JSON.stringify(config, null, 2)}\\n`,\n \"utf8\",\n );\n}\n\nexport function loadLynxStateConfig(\n stateConfigPath: string = getDefaultStateConfigPath(),\n): LynxConfigState {\n if (!existsSync(stateConfigPath)) {\n return { version: 1, files: [] };\n }\n const content = readFileSync(stateConfigPath, \"utf8\");\n const raw = parseConfigFile(stateConfigPath, content);\n const object = asRecord(raw, \"state config\");\n const version = object[\"version\"];\n if (version !== undefined && version !== 1) {\n throw new ConfigError(\"state config version must be 1\");\n }\n\n if (object[\"profiles\"] !== undefined) {\n const legacyState = object as Record<string, unknown> & {\n profiles: Record<string, Record<string, unknown>>;\n };\n const files: ProfileStateEntry[] = Object.entries(\n legacyState.profiles,\n ).map(([name, legacyProfile]): ProfileStateEntry => {\n const profile = asRecord(\n legacyProfile,\n `state config profiles.${name}`,\n );\n const selected: ProxyGroupSelection[] = [];\n const user = asOptionalRecord(profile[\"user\"], \"user\");\n if (user !== undefined) {\n const activeGroup = user[\"proxy-group\"];\n if (typeof activeGroup === \"string\") {\n selected.push({ name: \"GLOBAL\", now: activeGroup });\n }\n const selections = asOptionalRecord(\n user[\"proxy-groups\"],\n \"user.proxy-groups\",\n );\n if (selections !== undefined) {\n for (const [groupName, proxyName] of Object.entries(\n selections,\n )) {\n if (typeof proxyName === \"string\") {\n selected.push({ name: groupName, now: proxyName });\n }\n }\n }\n }\n return { name, selected };\n });\n return { version: 1, files };\n }\n\n const filesRaw = object[\"files\"];\n if (!Array.isArray(filesRaw)) {\n return { version: 1, files: [] };\n }\n\n const files: ProfileStateEntry[] = filesRaw.map(\n (item: unknown, index: number): ProfileStateEntry => {\n const entry = asRecord(item, `state config files[${index}]`);\n const name = entry[\"name\"];\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw new ConfigError(\n `state config files[${index}].name must be a non-empty string`,\n );\n }\n\n const selectedRaw = entry[\"selected\"];\n const selected: ProxyGroupSelection[] = Array.isArray(\n selectedRaw,\n )\n ? selectedRaw\n .map(\n (\n sel: unknown,\n selIndex: number,\n ): ProxyGroupSelection | null => {\n const selObj = asRecord(\n sel,\n `state config files[${index}].selected[${selIndex}]`,\n );\n const selName = selObj[\"name\"];\n const now = selObj[\"now\"];\n if (\n typeof selName === \"string\" &&\n typeof now === \"string\"\n ) {\n return { name: selName, now };\n }\n return null;\n },\n )\n .filter(\n (sel): sel is ProxyGroupSelection => sel !== null,\n )\n : [];\n\n const time =\n typeof entry[\"time\"] === \"string\" ? entry[\"time\"] : undefined;\n const url =\n typeof entry[\"url\"] === \"string\" ? entry[\"url\"] : undefined;\n const interval =\n typeof entry[\"interval\"] === \"number\"\n ? entry[\"interval\"]\n : undefined;\n const mode =\n typeof entry[\"mode\"] === \"string\" &&\n [\"global\", \"rule\", \"direct\", \"script\"].includes(entry[\"mode\"])\n ? (entry[\"mode\"] as ProfileStateEntry[\"mode\"])\n : undefined;\n const cron =\n typeof entry[\"cron\"] === \"string\"\n ? entry[\"cron\"]\n : undefined;\n const headers =\n typeof entry[\"headers\"] === \"string\"\n ? entry[\"headers\"]\n : undefined;\n const homeWeb =\n typeof entry[\"homeWeb\"] === \"string\"\n ? entry[\"homeWeb\"]\n : undefined;\n const subInfo = entry[\"subInfo\"];\n const subInfoParsed =\n subInfo !== undefined &&\n typeof subInfo === \"object\" &&\n subInfo !== null\n ? {\n upload: (subInfo as Record<string, unknown>)[\n \"upload\"\n ] as number,\n download: (subInfo as Record<string, unknown>)[\n \"download\"\n ] as number,\n total: (subInfo as Record<string, unknown>)[\n \"total\"\n ] as number,\n expire: (subInfo as Record<string, unknown>)[\n \"expire\"\n ] as number,\n }\n : undefined;\n\n return {\n name,\n time,\n url,\n selected,\n interval,\n subInfo: subInfoParsed,\n homeWeb,\n mode,\n cron,\n headers,\n };\n },\n );\n\n return { version: 1, files };\n}\n\nexport function writeLynxStateConfig(\n config: LynxConfigState,\n stateConfigPath: string = getDefaultStateConfigPath(),\n): void {\n mkdirSync(dirname(stateConfigPath), { recursive: true });\n writeFileSync(\n stateConfigPath,\n `${JSON.stringify(config, null, 2)}\\n`,\n \"utf8\",\n );\n}\n\nexport function findProfileStateEntry(\n state: LynxConfigState,\n profileName: string,\n): ProfileStateEntry | undefined {\n return state.files.find(\n (entry: ProfileStateEntry): boolean => entry.name === profileName,\n );\n}\n\nexport function selectedToProxySelection(\n selected: ProxyGroupSelection[],\n): ProxySelectionConfig {\n const user: ProxySelectionConfig = {};\n const proxyGroups: Record<string, string> = {};\n\n for (const item of selected) {\n proxyGroups[item.name] = item.now;\n }\n\n if (Object.keys(proxyGroups).length > 0) {\n user[\"proxy-groups\"] = proxyGroups;\n }\n return user;\n}\n\nexport function getProfileStateKey(profilePath: string): string {\n return basename(profilePath);\n}\n\nexport function resolveProfileStateKey(profile: string): string {\n return getProfileStateKey(resolveProfilePath(profile));\n}\n\nexport function updateProfileState(\n profilePath: string,\n updater: (state: ProfileStateEntry) => ProfileStateEntry,\n): ProfileStateEntry {\n const stateConfig = loadLynxStateConfig();\n const profileName = getProfileStateKey(profilePath);\n const existingIndex = stateConfig.files.findIndex(\n (entry: ProfileStateEntry): boolean => entry.name === profileName,\n );\n const currentState =\n existingIndex >= 0\n ? stateConfig.files[existingIndex]!\n : { name: profileName, selected: [] };\n const nextState = updater(currentState);\n\n if (existingIndex >= 0) {\n stateConfig.files[existingIndex] = nextState;\n } else {\n stateConfig.files.push(nextState);\n }\n\n writeLynxStateConfig(stateConfig);\n return nextState;\n}\n\nexport function loadEffectiveProfileConfig(profilePath: string): AppConfig {\n const content = readFileSync(profilePath, \"utf8\");\n const raw = parseConfigFile(profilePath, content);\n const object = asRecord(raw, \"profile config\");\n const profileName = getProfileStateKey(profilePath);\n const state = loadLynxStateConfig();\n const stateEntry = findProfileStateEntry(state, profileName);\n // selected 转换为 ProxySelectionConfig 时不过滤,保留所有代理组选择\n // mode 在运行时路由匹配时生效\n const userState =\n stateEntry?.selected !== undefined &&\n stateEntry.selected.length > 0\n ? selectedToProxySelection(stateEntry.selected)\n : undefined;\n\n return loadConfigFromRaw(applyProfileState(object, userState));\n}\n\nexport function resolveProfilePath(\n profile: string,\n profileDir: string = getDefaultProfileDir(),\n): string {\n validateProfileName(profile);\n\n const ext = extname(profile);\n if (ext.length > 0) {\n if (!isSupportedProfileExtension(ext)) {\n throw new ConfigError(`Unsupported profile file extension: ${ext}`);\n }\n const profilePath = join(profileDir, profile);\n if (!existsSync(profilePath)) {\n throw new ConfigError(\n `Profile \"${profile}\" was not found: ${profilePath}`,\n );\n }\n return profilePath;\n }\n\n const candidates = PROFILE_EXTENSIONS.map((extension: string): string =>\n join(profileDir, `${profile}${extension}`),\n );\n const existing = candidates.filter((candidate: string): boolean =>\n existsSync(candidate),\n );\n if (existing.length === 1) {\n const [profilePath] = existing;\n if (profilePath === undefined) {\n throw new ConfigError(`Profile \"${profile}\" was not found`);\n }\n return profilePath;\n }\n if (existing.length > 1) {\n throw new ConfigError(\n `Profile \"${profile}\" is ambiguous. Multiple files exist: ${existing.join(\", \")}. Specify the extension in user.json.`,\n );\n }\n\n throw new ConfigError(\n `Profile \"${profile}\" was not found in ${profileDir}. Searched: ${candidates.join(\", \")}`,\n );\n}\n\nexport function loadConfigFromUserProfile(\n userConfigPath: string = getDefaultUserConfigPath(),\n): { config: AppConfig; profilePath: string } {\n const userConfig = loadLynxUserConfig(userConfigPath);\n const profilePath = resolveProfilePath(\n userConfig.profile,\n getDefaultProfileDir(),\n );\n const config = loadEffectiveProfileConfig(profilePath);\n return { config, profilePath };\n}\n\nexport function loadDefaultConfig(): AppConfig {\n const userConfigPath = getDefaultUserConfigPath();\n if (existsSync(userConfigPath)) {\n return loadConfigFromUserProfile(userConfigPath).config;\n }\n if (existsSync(LEGACY_CONFIG_PATH)) {\n return loadConfig(LEGACY_CONFIG_PATH);\n }\n ensureDefaultUserConfig(userConfigPath);\n throw new ConfigError(\n `Created default user config: ${userConfigPath}. Add a Clash-style profile with 'lynx config add <name> --file <path>' (or --url / --template), then select it with 'lynx config use <profile>'. Expected profile file: ${getDefaultProfileDir()}/${DEFAULT_USER_CONFIG.profile}.toml (or .yaml/.json).`,\n );\n}\n\nexport function loadDefaultConfigWithPath(): { config: AppConfig; profilePath?: string } {\n const userConfigPath = getDefaultUserConfigPath();\n if (existsSync(userConfigPath)) {\n return loadConfigFromUserProfile(userConfigPath);\n }\n if (existsSync(LEGACY_CONFIG_PATH)) {\n return { config: loadConfig(LEGACY_CONFIG_PATH) };\n }\n ensureDefaultUserConfig(userConfigPath);\n throw new ConfigError(\n `Created default user config: ${userConfigPath}. Add a Clash-style profile with 'lynx config add <name> --file <path>' (or --url / --template), then select it with 'lynx config use <profile>'. Expected profile file: ${getDefaultProfileDir()}/${DEFAULT_USER_CONFIG.profile}.toml (or .yaml/.json).`,\n );\n}\n\nfunction asOptionalRecord(\n raw: unknown,\n field: string,\n): Record<string, unknown> | undefined {\n if (raw === undefined) {\n return undefined;\n }\n return asRecord(raw, field);\n}\n\nfunction asRecord(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigError(`${field} must be a table`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction validateProfileName(profile: string): void {\n if (profile.length === 0) {\n throw new ConfigError(\"profile must be a non-empty string\");\n }\n if (\n isAbsolute(profile) ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\") ||\n profile === \".\" ||\n profile === \"..\" ||\n basename(profile) !== profile\n ) {\n throw new ConfigError(\n `profile must be a file name under ${getDefaultProfileDir()}, not a path: ${profile}`,\n );\n }\n}\n\nexport function isSupportedProfileExtension(ext: string): boolean {\n return PROFILE_EXTENSIONS.includes(\n ext as (typeof PROFILE_EXTENSIONS)[number],\n );\n}\n","import { dump as dumpYaml } from \"js-yaml\";\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, extname, join } from \"node:path\";\nimport { stringify as stringifyToml } from \"smol-toml\";\nimport { loadConfig, loadConfigFromRaw, parseConfigFile } from \"../config/loader.js\";\nimport type { UserProfileConfig } from \"../config/models.js\";\nimport { ConfigError } from \"../config/models.js\";\nimport { fetchSubscription } from \"../config/subscription.js\";\nimport {\n ensureDefaultUserConfig,\n findProfileStateEntry,\n getDefaultProfileDir,\n getDefaultStateConfigPath,\n getDefaultUserConfigPath,\n getLynxConfigHome,\n getProfileStateKey,\n loadEffectiveProfileConfig,\n loadLynxStateConfig,\n loadLynxUserConfig,\n resolveProfilePath,\n updateProfileState,\n writeLynxUserConfig,\n} from \"../config/user-config.js\";\n\nconst PROFILE_EXTENSIONS = new Set([\".toml\", \".yaml\", \".yml\", \".json\"]);\nconst DEFAULT_TEMPLATE: UserProfileConfig = {\n port: 8080,\n \"allow-lan\": false,\n mode: \"rule\",\n \"log-level\": \"debug\",\n \"access-log\": true,\n proxies: [],\n \"proxy-groups\": [\n {\n name: \"default\",\n type: \"select\",\n proxies: [\"DIRECT\"],\n },\n ],\n rules: [\"MATCH,DIRECT\"]\n};\n\nexport async function runConfigCommand(args: readonly string[]): Promise<void> {\n const [command, ...rest] = args;\n if (command === undefined || command === \"--help\" || command === \"-h\") {\n console.log(createConfigHelpText());\n return;\n }\n\n if (command === \"list\") {\n listProfiles();\n return;\n }\n if (command === \"current\") {\n showCurrentConfig();\n return;\n }\n if (command === \"use\") {\n useProfile(requireArg(rest[0], \"profile\"));\n return;\n }\n if (command === \"add\") {\n await addProfile(rest);\n return;\n }\n if (command === \"update\") {\n await updateProfile(rest);\n return;\n }\n if (command === \"info\") {\n showSubscriptionInfo(rest);\n return;\n }\n if (command === \"show\") {\n showProfile(rest);\n return;\n }\n if (command === \"remove\") {\n removeProfile(requireArg(rest[0], \"profile\"));\n return;\n }\n if (command === \"path\") {\n showConfigPaths();\n return;\n }\n\n throw new Error(`Unknown config command: ${command}`);\n}\n\nfunction listProfiles(): void {\n ensureDefaultUserConfig();\n const profileDir = getDefaultProfileDir();\n const current = loadLynxUserConfig().profile;\n const entries = readdirSync(profileDir, { withFileTypes: true })\n .filter((entry): boolean => entry.isFile())\n .map((entry): string => entry.name)\n .filter((name): boolean => PROFILE_EXTENSIONS.has(extname(name)))\n .sort();\n\n if (entries.length === 0) {\n console.log(`No profiles found in ${profileDir}`);\n return;\n }\n\n for (const entry of entries) {\n const stem = stripSupportedExtension(entry);\n const marker = current === entry || current === stem ? \"*\" : \" \";\n console.log(`${marker} ${entry}`);\n }\n}\n\nfunction showCurrentConfig(): void {\n ensureDefaultUserConfig();\n const userConfig = loadLynxUserConfig();\n console.log(`user config: ${getDefaultUserConfigPath()}`);\n console.log(`state config: ${getDefaultStateConfigPath()}`);\n console.log(`profile: ${userConfig.profile}`);\n console.log(`profile dir: ${getDefaultProfileDir()}`);\n try {\n const profilePath = resolveProfilePath(userConfig.profile);\n const config = loadEffectiveProfileConfig(profilePath);\n console.log(`profile path: ${profilePath}`);\n console.log(`state key: ${getProfileStateKey(profilePath)}`);\n console.log(`effective listen: ${config.server.host}:${config.server.port}`);\n const globalSelection = config.user.proxyGroupSelections[\"GLOBAL\"];\n console.log(\n `global proxy: ${globalSelection ?? \"(not set)\"}`,\n );\n const entries = Object.entries(config.user.proxyGroupSelections).filter(\n ([group]) => group !== \"GLOBAL\",\n );\n if (entries.length === 0) {\n console.log(\"selections: (none)\");\n } else {\n console.log(\"selections:\");\n for (const [group, proxy] of entries) {\n console.log(` ${group}: ${proxy}`);\n }\n }\n } catch (error) {\n console.log(\n `profile path: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction useProfile(profile: string): void {\n const profilePath = resolveProfilePath(profile);\n loadConfig(profilePath);\n writeLynxUserConfig({ profile });\n console.log(`Using profile: ${profile}`);\n}\n\nasync function addProfile(args: readonly string[]): Promise<void> {\n const name = requireArg(args[0], \"name\");\n const fileIndex = args.indexOf(\"--file\");\n const urlIndex = args.indexOf(\"--url\");\n const useTemplate = args.includes(\"--template\");\n const userAgentIndex = args.indexOf(\"--user-agent\");\n const userAgent =\n userAgentIndex === -1\n ? undefined\n : requireArg(args[userAgentIndex + 1], \"user-agent\");\n\n const sourceCount =\n (fileIndex === -1 ? 0 : 1) + (urlIndex === -1 ? 0 : 1) + (useTemplate ? 1 : 0);\n if (sourceCount === 0) {\n throw new Error(\"config add requires --file <path>, --url <url>, or --template\");\n }\n if (sourceCount > 1) {\n throw new Error(\n \"config add accepts only one of --file, --url, or --template\",\n );\n }\n\n if (urlIndex !== -1) {\n const url = requireArg(args[urlIndex + 1], \"url\");\n await addProfileFromUrl(name, url, userAgent);\n return;\n }\n\n const source = fileIndex === -1 ? undefined : requireArg(args[fileIndex + 1], \"file\");\n const ext = extname(name) || (source === undefined ? \".toml\" : extname(source));\n if (!PROFILE_EXTENSIONS.has(ext)) {\n throw new ConfigError(`Unsupported profile file extension: ${ext}`);\n }\n\n const fileName = extname(name) ? name : `${name}${ext}`;\n ensureProfileFileName(fileName);\n mkdirSync(getDefaultProfileDir(), { recursive: true });\n const targetPath = join(getDefaultProfileDir(), fileName);\n if (existsSync(targetPath)) {\n throw new ConfigError(`Profile already exists: ${targetPath}`);\n }\n\n if (source === undefined) {\n writeFileSync(targetPath, serializeTemplate(targetPath), \"utf8\");\n } else {\n loadConfig(source);\n copyFileSync(source, targetPath);\n }\n loadConfig(targetPath);\n console.log(`Added profile: ${targetPath}`);\n}\n\n// 从订阅 URL 抓取配置并存为新 profile。订阅默认存成 .yaml(除非 name 已带扩展名)。\n// 抓取或校验失败时不留下文件、不写 state。\nasync function addProfileFromUrl(\n name: string,\n url: string,\n userAgent: string | undefined,\n): Promise<void> {\n const ext = extname(name) || \".yaml\";\n if (!PROFILE_EXTENSIONS.has(ext)) {\n throw new ConfigError(`Unsupported profile file extension: ${ext}`);\n }\n const fileName = extname(name) ? name : `${name}${ext}`;\n ensureProfileFileName(fileName);\n mkdirSync(getDefaultProfileDir(), { recursive: true });\n const targetPath = join(getDefaultProfileDir(), fileName);\n if (existsSync(targetPath)) {\n throw new ConfigError(`Profile already exists: ${targetPath}`);\n }\n\n // 先抓取并校验,通过后才落盘,避免留下半成品文件。\n const result = await fetchSubscription(url, { userAgent });\n validateSubscriptionContent(result.content, ext);\n\n writeFileSync(targetPath, result.content, \"utf8\");\n updateProfileState(targetPath, (state) => ({\n ...state,\n url,\n time: nowIsoString(),\n subInfo: result.subInfo ?? state.subInfo,\n }));\n console.log(`Added subscription profile: ${targetPath}`);\n console.log(` url: ${url}`);\n}\n\n// 用 state.json 中记录的 url 重新抓取订阅,校验通过后整份覆盖 profile 文件。\n// 省略 name 时更新当前 profile;非订阅 profile(无 url)报错。校验失败保留旧文件。\nasync function updateProfile(args: readonly string[]): Promise<void> {\n const userAgentIndex = args.indexOf(\"--user-agent\");\n const cliUserAgent =\n userAgentIndex === -1\n ? undefined\n : requireArg(args[userAgentIndex + 1], \"user-agent\");\n const positional = args.filter(\n (arg, index): boolean =>\n arg !== \"--user-agent\" && index !== userAgentIndex + 1,\n );\n const name = positional[0] ?? loadLynxUserConfig().profile;\n\n const profilePath = resolveProfilePath(name);\n const stateKey = getProfileStateKey(profilePath);\n const entry = findProfileStateEntry(loadLynxStateConfig(), stateKey);\n const url = entry?.url;\n if (url === undefined || url.length === 0) {\n throw new ConfigError(\n `Profile \"${name}\" is not a subscription (no url recorded in state.json). Use \"config add ${name} --url <url>\" first.`,\n );\n }\n\n const ext = extname(profilePath);\n // 先抓取并校验,校验失败抛错并保留原有 profile 文件。\n const result = await fetchSubscription(url, {\n userAgent: cliUserAgent ?? entry?.headers,\n });\n validateSubscriptionContent(result.content, ext);\n\n writeFileSync(profilePath, result.content, \"utf8\");\n updateProfileState(profilePath, (state) => ({\n ...state,\n time: nowIsoString(),\n subInfo: result.subInfo ?? state.subInfo,\n }));\n console.log(`Updated subscription profile: ${profilePath}`);\n console.log(\"Run 'lynx proxy restart' to apply the new config.\");\n}\n\nfunction showSubscriptionInfo(args: readonly string[]): void {\n if (args.length > 1) {\n throw new Error(`Unknown config info argument: ${args[1]}`);\n }\n const name = args[0] ?? loadLynxUserConfig().profile;\n const profilePath = resolveProfilePath(name);\n const stateKey = getProfileStateKey(profilePath);\n const entry = findProfileStateEntry(loadLynxStateConfig(), stateKey);\n\n if (entry?.url === undefined || entry.url.length === 0) {\n console.log(`Profile \"${name}\" is not a subscription (no url recorded).`);\n return;\n }\n\n console.log(`profile: ${stateKey}`);\n console.log(`url: ${entry.url}`);\n console.log(`updated: ${entry.time ?? \"(never)\"}`);\n const subInfo = entry.subInfo;\n if (subInfo === undefined) {\n console.log(\"traffic: (unknown)\");\n console.log(\"expire: (unknown)\");\n return;\n }\n const used = subInfo.upload + subInfo.download;\n console.log(`traffic: ${formatBytes(used)} / ${formatBytes(subInfo.total)}`);\n console.log(`expire: ${formatExpire(subInfo.expire)}`);\n}\n\n\nfunction showProfile(args: readonly string[]): void {\n const effective = args.includes(\"--effective\");\n const rest = args.filter((arg): boolean => arg !== \"--effective\");\n if (rest.length > 1) {\n throw new Error(`Unknown config show argument: ${rest[1]}`);\n }\n const selected = rest[0] ?? loadLynxUserConfig().profile;\n const profilePath = resolveProfilePath(selected);\n if (!effective) {\n console.log(readFileSync(profilePath, \"utf8\"));\n return;\n }\n console.log(`${JSON.stringify(loadEffectiveProfileConfig(profilePath), null, 2)}\\n`);\n}\n\nfunction removeProfile(profile: string): void {\n const userConfig = loadLynxUserConfig();\n const profilePath = resolveProfilePath(profile);\n const fileName = basename(profilePath);\n if (userConfig.profile === profile || userConfig.profile === fileName) {\n throw new ConfigError(\"Cannot remove the active profile. Switch profiles first.\");\n }\n rmSync(profilePath);\n console.log(`Removed profile: ${profilePath}`);\n}\n\nfunction showConfigPaths(): void {\n ensureDefaultUserConfig();\n console.log(`config home: ${getLynxConfigHome()}`);\n console.log(`user config: ${getDefaultUserConfigPath()}`);\n console.log(`state config: ${getDefaultStateConfigPath()}`);\n console.log(`profile dir: ${getDefaultProfileDir()}`);\n}\n\nfunction serializeTemplate(path: string): string {\n const ext = extname(path);\n if (ext === \".json\") {\n return `${JSON.stringify(DEFAULT_TEMPLATE, null, 2)}\\n`;\n }\n if (ext === \".toml\") {\n return stringifyToml(DEFAULT_TEMPLATE);\n }\n if (ext === \".yaml\" || ext === \".yml\") {\n return dumpYaml(DEFAULT_TEMPLATE);\n }\n throw new ConfigError(`Unsupported profile file extension: ${ext}`);\n}\n\n// 用对应扩展名解析订阅内容并走完整校验;失败抛 ConfigError。\nfunction validateSubscriptionContent(content: string, ext: string): void {\n const raw = parseConfigFile(`subscription${ext}`, content);\n loadConfigFromRaw(raw);\n}\n\nfunction nowIsoString(): string {\n return new Date().toISOString();\n}\n\nfunction formatBytes(bytes: number): string {\n if (!Number.isFinite(bytes) || bytes <= 0) {\n return \"0 B\";\n }\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\"];\n let value = bytes;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit += 1;\n }\n const rounded = unit === 0 ? value : Math.round(value * 100) / 100;\n return `${rounded} ${units[unit]}`;\n}\n\nfunction formatExpire(expire: number): string {\n if (!Number.isFinite(expire) || expire <= 0) {\n return \"(no expiry)\";\n }\n // 机场的 expire 是 Unix 秒级时间戳。\n const date = new Date(expire * 1000);\n return date.toISOString().slice(0, 10);\n}\n\nfunction stripSupportedExtension(fileName: string): string {\n const ext = extname(fileName);\n return PROFILE_EXTENSIONS.has(ext) ? fileName.slice(0, -ext.length) : fileName;\n}\n\nfunction ensureProfileFileName(fileName: string): void {\n if (\n fileName.length === 0 ||\n fileName.includes(\"/\") ||\n fileName.includes(\"\\\\\") ||\n fileName.includes(\"\\0\") ||\n basename(fileName) !== fileName\n ) {\n throw new ConfigError(`profile must be a file name, not a path: ${fileName}`);\n }\n}\n\nfunction requireArg(value: string | undefined, name: string): string {\n if (value === undefined || value.length === 0) {\n throw new Error(`Missing ${name}`);\n }\n return value;\n}\n\nfunction createConfigHelpText(): string {\n return `Usage: lynx config <command> [options]\n\nCommands:\n list List profile config files\n current Show active user config and resolved profile\n use <profile> Select active profile in user.json\n add <name> --file <path> Copy a profile config into the profile dir\n add <name> --template Create a Clash-style profile from the default template; extension controls TOML/YAML/JSON format\n add <name> --url <url> Fetch a subscription and save it as a profile (default .yaml); optional --user-agent <ua>\n update [profile] Re-fetch a subscription profile by its recorded url and overwrite it (defaults to active profile)\n info [profile] Show subscription url, last update time, traffic, and expiry\n show [profile] Print raw profile config\n show [profile] --effective Print resolved profile + state.json as JSON\n remove <profile> Remove an inactive profile\n path Show config paths`;\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { getLynxConfigHome } from \"../config/user-config.js\";\n\nexport interface ProxyDaemonState {\n version: 1;\n pid: number;\n profile?: string;\n profilePath?: string;\n host: string;\n port: number;\n startedAt: string;\n logFile: string;\n}\n\nexport function getProxyDaemonStatePath(): string {\n return join(getLynxConfigHome(), \"runtime\", \"proxy-daemon.json\");\n}\n\nexport function getProxyDaemonLogPath(): string {\n return join(getLynxConfigHome(), \"runtime\", \"proxy-daemon.log\");\n}\n\nexport function getControlSocketPath(): string {\n return join(getLynxConfigHome(), \"runtime\", \"control.sock\");\n}\n\nexport function loadProxyDaemonState(\n path: string = getProxyDaemonStatePath(),\n): ProxyDaemonState | undefined {\n if (!existsSync(path)) {\n return undefined;\n }\n const raw = JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new Error(\"proxy daemon state must be an object\");\n }\n const object = raw as Record<string, unknown>;\n if (object[\"version\"] !== 1) {\n throw new Error(\"proxy daemon state version must be 1\");\n }\n const pid = object[\"pid\"];\n const host = object[\"host\"];\n const port = object[\"port\"];\n const startedAt = object[\"startedAt\"];\n const logFile = object[\"logFile\"];\n if (typeof pid !== \"number\" || !Number.isInteger(pid) || pid <= 0) {\n throw new Error(\"proxy daemon state pid must be a positive integer\");\n }\n if (typeof host !== \"string\" || host.length === 0) {\n throw new Error(\"proxy daemon state host must be a non-empty string\");\n }\n if (typeof port !== \"number\" || !Number.isInteger(port) || port <= 0) {\n throw new Error(\"proxy daemon state port must be a positive integer\");\n }\n if (typeof startedAt !== \"string\" || startedAt.length === 0) {\n throw new Error(\"proxy daemon state startedAt must be a non-empty string\");\n }\n if (typeof logFile !== \"string\" || logFile.length === 0) {\n throw new Error(\"proxy daemon state logFile must be a non-empty string\");\n }\n\n const state: ProxyDaemonState = {\n version: 1,\n pid,\n host,\n port,\n startedAt,\n logFile,\n };\n if (typeof object[\"profile\"] === \"string\") {\n state.profile = object[\"profile\"];\n }\n if (typeof object[\"profilePath\"] === \"string\") {\n state.profilePath = object[\"profilePath\"];\n }\n return state;\n}\n\nexport function writeProxyDaemonState(\n state: ProxyDaemonState,\n path: string = getProxyDaemonStatePath(),\n): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(state, null, 2)}\\n`, \"utf8\");\n}\n\nexport function removeProxyDaemonState(\n path: string = getProxyDaemonStatePath(),\n): void {\n rmSync(path, { force: true });\n}\n\nexport function isProcessRunning(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n const code = typeof error === \"object\" && error !== null\n ? (error as { code?: unknown }).code\n : undefined;\n return code === \"EPERM\";\n }\n}\n","import { createConnection, createServer } from \"node:net\";\nimport type { Server, Socket } from \"node:net\";\nimport { existsSync, mkdirSync, rmSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { AppConfig, ProfileMode } from \"../config/models.js\";\nimport type { ProxyServer, RuntimeSnapshot } from \"../server/http-server.js\";\nimport { getControlSocketPath } from \"./daemon-state.js\";\n\nconst SUPPORTED_MODES: readonly ProfileMode[] = [\n \"rule\",\n \"global\",\n \"direct\",\n \"script\",\n];\n\nexport interface ControlCommand {\n cmd: \"selectGroup\" | \"useGroup\" | \"setMode\" | \"unsetGroup\" | \"query\";\n group?: string;\n proxy?: string;\n mode?: string;\n}\n\nexport interface ControlResponse {\n ok: boolean;\n error?: string;\n state?: RuntimeSnapshot;\n}\n\nexport interface ControlServer {\n close(): Promise<void>;\n}\n\n/**\n * 在 Unix domain socket 上监听控制命令,按逐行 JSON 解析并应用到运行中的 ProxyServer。\n * 非 Unix 平台(不支持 Unix domain socket)下返回 undefined,由调用方降级。\n */\nexport async function startControlServer(\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n socketPath: string = getControlSocketPath(),\n): Promise<ControlServer | undefined> {\n if (process.platform === \"win32\") {\n return undefined;\n }\n\n await prepareSocketPath(socketPath);\n\n const server = createServer((socket: Socket): void => {\n handleConnection(socket, proxy, config);\n });\n\n return new Promise<ControlServer | undefined>(\n (\n resolve: (value: ControlServer | undefined) => void,\n reject: (error: Error) => void,\n ): void => {\n const onError = (error: Error): void => {\n server.removeListener(\"listening\", onListening);\n reject(error);\n };\n const onListening = (): void => {\n server.removeListener(\"error\", onError);\n resolve(new NodeControlServer(server, socketPath));\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n mkdirSync(dirname(socketPath), { recursive: true });\n server.listen(socketPath);\n },\n );\n}\n\nclass NodeControlServer implements ControlServer {\n public constructor(\n private readonly server: Server,\n private readonly socketPath: string,\n ) {}\n\n public close(): Promise<void> {\n return new Promise<void>((resolve): void => {\n this.server.close((): void => {\n rmSync(this.socketPath, { force: true });\n resolve();\n });\n });\n }\n}\n\n/**\n * 启动监听前处理残留 socket 文件:先尝试连接,连得上说明已有 daemon 在跑(抛错),\n * 连不上则删除残留文件后允许重新监听。\n */\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n if (!existsSync(socketPath)) {\n return;\n }\n const alive = await isSocketAlive(socketPath);\n if (alive) {\n throw new Error(\n `Control socket already in use by a running daemon: ${socketPath}`,\n );\n }\n rmSync(socketPath, { force: true });\n}\n\nfunction isSocketAlive(socketPath: string): Promise<boolean> {\n return new Promise<boolean>((resolve): void => {\n const probe = createConnection(socketPath);\n const done = (alive: boolean): void => {\n probe.destroy();\n resolve(alive);\n };\n probe.once(\"connect\", (): void => done(true));\n probe.once(\"error\", (): void => done(false));\n });\n}\n\nfunction handleConnection(\n socket: Socket,\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n): void {\n let buffer = \"\";\n socket.setEncoding(\"utf8\");\n socket.on(\"data\", (chunk: string): void => {\n buffer += chunk;\n let newlineIndex = buffer.indexOf(\"\\n\");\n while (newlineIndex !== -1) {\n const line = buffer.slice(0, newlineIndex);\n buffer = buffer.slice(newlineIndex + 1);\n const response = processLine(line, proxy, config);\n socket.write(`${JSON.stringify(response)}\\n`);\n newlineIndex = buffer.indexOf(\"\\n\");\n }\n });\n socket.on(\"error\", (): void => {\n socket.destroy();\n });\n}\n\nfunction processLine(\n line: string,\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n): ControlResponse {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n return { ok: false, error: \"empty command\" };\n }\n let command: ControlCommand;\n try {\n command = JSON.parse(trimmed) as ControlCommand;\n } catch {\n return { ok: false, error: \"invalid JSON command\" };\n }\n return applyCommand(command, proxy, config);\n}\n\nexport function applyCommand(\n command: ControlCommand,\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n): ControlResponse {\n switch (command.cmd) {\n case \"query\":\n return { ok: true, state: proxy.getSnapshot() };\n case \"setMode\":\n return applySetMode(command.mode, proxy);\n case \"useGroup\":\n return applyUseGroup(command.group, proxy, config);\n case \"selectGroup\":\n return applySelectGroup(command.group, command.proxy, proxy, config);\n case \"unsetGroup\":\n return applyUnsetGroup(command.group, proxy, config);\n default:\n return { ok: false, error: `unknown command: ${String(command.cmd)}` };\n }\n}\n\nfunction applySetMode(\n mode: string | undefined,\n proxy: ProxyServer,\n): ControlResponse {\n if (mode === undefined || !SUPPORTED_MODES.includes(mode as ProfileMode)) {\n return { ok: false, error: `unsupported mode: ${String(mode)}` };\n }\n proxy.setMode(mode as ProfileMode);\n return { ok: true, state: proxy.getSnapshot() };\n}\n\nfunction applyUseGroup(\n group: string | undefined,\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n): ControlResponse {\n if (group === undefined) {\n return { ok: false, error: \"missing group\" };\n }\n if (!groupExists(config, group)) {\n return { ok: false, error: `unknown proxy-group: ${group}` };\n }\n proxy.setGlobalProxy(group);\n return { ok: true, state: proxy.getSnapshot() };\n}\n\nfunction applySelectGroup(\n group: string | undefined,\n selected: string | undefined,\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n): ControlResponse {\n if (group === undefined || selected === undefined) {\n return { ok: false, error: \"missing group or proxy\" };\n }\n const members = groupMembers(config, group);\n if (members === undefined) {\n return { ok: false, error: `unknown proxy-group: ${group}` };\n }\n if (!members.includes(selected)) {\n return {\n ok: false,\n error: `proxy-group ${group} does not contain selectable proxy: ${selected}`,\n };\n }\n proxy.selectGroup(group, selected);\n return { ok: true, state: proxy.getSnapshot() };\n}\n\nfunction applyUnsetGroup(\n group: string | undefined,\n proxy: ProxyServer,\n config: Pick<AppConfig, \"proxies\" | \"proxyGroups\">,\n): ControlResponse {\n if (group === undefined) {\n return { ok: false, error: \"missing group\" };\n }\n if (!groupExists(config, group)) {\n return { ok: false, error: `unknown proxy-group: ${group}` };\n }\n proxy.unsetGroup(group);\n return { ok: true, state: proxy.getSnapshot() };\n}\n\nfunction groupExists(\n config: Pick<AppConfig, \"proxyGroups\">,\n group: string,\n): boolean {\n return config.proxyGroups.some((g): boolean => g.name === group);\n}\n\nfunction groupMembers(\n config: Pick<AppConfig, \"proxyGroups\">,\n group: string,\n): string[] | undefined {\n return config.proxyGroups.find((g): boolean => g.name === group)?.proxies;\n}\n\n/**\n * CLI 端:连接控制 socket 发送一条命令并返回响应。\n * daemon 未运行(socket 不存在或拒绝连接)时返回 undefined,由调用方降级为\"仅写盘\"。\n */\nexport function sendControlCommand(\n command: ControlCommand,\n socketPath: string = getControlSocketPath(),\n): Promise<ControlResponse | undefined> {\n if (!existsSync(socketPath)) {\n return Promise.resolve(undefined);\n }\n return new Promise<ControlResponse | undefined>((resolve, reject): void => {\n const socket = createConnection(socketPath);\n let buffer = \"\";\n socket.setEncoding(\"utf8\");\n socket.on(\"connect\", (): void => {\n socket.write(`${JSON.stringify(command)}\\n`);\n });\n socket.on(\"data\", (chunk: string): void => {\n buffer += chunk;\n const newlineIndex = buffer.indexOf(\"\\n\");\n if (newlineIndex !== -1) {\n const line = buffer.slice(0, newlineIndex);\n socket.end();\n try {\n resolve(JSON.parse(line) as ControlResponse);\n } catch {\n resolve(undefined);\n }\n }\n });\n socket.on(\"error\", (error: NodeJS.ErrnoException): void => {\n // daemon 未运行:socket 文件残留但无监听者\n if (error.code === \"ECONNREFUSED\" || error.code === \"ENOENT\") {\n resolve(undefined);\n return;\n }\n reject(error);\n });\n });\n}\n\n/**\n * 检测控制 socket 是否有 daemon 在监听(供 proxy status 报告)。\n */\nexport function isControlSocketReady(\n socketPath: string = getControlSocketPath(),\n): Promise<boolean> {\n if (!existsSync(socketPath)) {\n return Promise.resolve(false);\n }\n return new Promise<boolean>((resolve): void => {\n const probe = createConnection(socketPath);\n const done = (ready: boolean): void => {\n probe.destroy();\n resolve(ready);\n };\n probe.once(\"connect\", (): void => done(true));\n probe.once(\"error\", (): void => done(false));\n });\n}\n","import { readFileSync, writeFileSync } from \"node:fs\";\nimport { extname } from \"node:path\";\nimport { dump as dumpYaml } from \"js-yaml\";\nimport { stringify as stringifyToml } from \"smol-toml\";\nimport { loadConfigFromRaw, parseConfigFile } from \"../config/loader.js\";\nimport type {\n AppConfig,\n ProfileMode,\n ProfileStateEntry,\n ProxyGroupSelection,\n} from \"../config/models.js\";\nimport { ConfigError } from \"../config/models.js\";\nimport {\n findProfileStateEntry,\n getDefaultStateConfigPath,\n getProfileStateKey,\n loadEffectiveProfileConfig,\n loadLynxStateConfig,\n loadLynxUserConfig,\n resolveProfilePath,\n updateProfileState,\n} from \"../config/user-config.js\";\nimport { sendControlCommand } from \"../runtime/control.js\";\nimport type { ControlCommand } from \"../runtime/control.js\";\n\ninterface ProfileContext {\n path: string;\n stateKey: string;\n statePath: string;\n raw: Record<string, unknown>;\n config: AppConfig;\n state: ProfileStateEntry;\n}\n\ninterface ParsedOptions {\n profile?: string;\n rest: string[];\n}\n\nexport async function runGroupsCommand(args: readonly string[]): Promise<void> {\n const [command, ...rest] = args;\n if (command === undefined || command === \"--help\" || command === \"-h\") {\n console.log(createGroupsHelpText());\n return;\n }\n\n if (command === \"list\") {\n listGroups(parseOptions(rest).profile);\n return;\n }\n if (command === \"current\") {\n await showCurrentGroups(parseOptions(rest).profile);\n return;\n }\n if (command === \"use\") {\n const options = parseOptions(rest);\n await useGroup(requireArg(options.rest[0], \"group\"), options.profile);\n return;\n }\n if (command === \"select\") {\n const options = parseOptions(rest);\n await selectGroupProxy(\n requireArg(options.rest[0], \"group\"),\n requireArg(options.rest[1], \"proxy\"),\n options.profile,\n );\n return;\n }\n if (command === \"mode\") {\n const options = parseOptions(rest);\n await setRuntimeMode(requireArg(options.rest[0], \"mode\"), options.profile);\n return;\n }\n if (command === \"unset\") {\n const options = parseOptions(rest);\n await unsetGroupSelection(requireArg(options.rest[0], \"group\"), options.profile);\n return;\n }\n if (command === \"rule\") {\n runRuleCommand(rest);\n return;\n }\n\n throw new Error(`Unknown groups command: ${command}`);\n}\n\nfunction listGroups(profile: string | undefined): void {\n const context = loadProfileContext(profile);\n const groups = getProxyGroups(context.raw);\n if (groups.length === 0) {\n console.log(`No proxy groups found in ${context.path}`);\n return;\n }\n\n const selections = context.config.user.proxyGroupSelections;\n for (const group of groups) {\n const selected = selections[group.name] ?? group.proxies[0] ?? \"\";\n console.log(` ${group.name}`);\n console.log(` selected: ${selected || \"(none)\"}`);\n console.log(` proxies: ${group.proxies.join(\", \")}`);\n }\n}\n\nasync function showCurrentGroups(profile: string | undefined): Promise<void> {\n const context = loadProfileContext(profile);\n console.log(`profile path: ${context.path}`);\n console.log(`state config: ${context.statePath}`);\n console.log(`state key: ${context.stateKey}`);\n\n // 当 daemon 正在跑当前 profile 时,优先显示其内存中实际生效的值\n const activeProfile = loadLynxUserConfig().profile;\n const live =\n profile === undefined || profile === activeProfile\n ? await sendControlCommand({ cmd: \"query\" })\n : undefined;\n if (live?.ok && live.state !== undefined) {\n console.log(\"source: running daemon (live)\");\n console.log(`mode: ${live.state.mode ?? \"(default)\"}`);\n console.log(`global proxy: ${live.state.globalProxy ?? \"(not set)\"}`);\n const entries = Object.entries(live.state.groupSelections);\n if (entries.length === 0) {\n console.log(\"group selections: (none)\");\n return;\n }\n console.log(\"group selections:\");\n for (const [group, proxy] of entries) {\n console.log(` ${group}: ${proxy}`);\n }\n return;\n }\n\n console.log(\"source: state.json\");\n const globalSelection = context.config.user.proxyGroupSelections[\"GLOBAL\"];\n console.log(\n `global proxy: ${globalSelection ?? \"(not set)\"}`,\n );\n const entries = Object.entries(context.config.user.proxyGroupSelections).filter(\n ([group]) => group !== \"GLOBAL\",\n );\n if (entries.length === 0) {\n console.log(\"group selections: (none)\");\n return;\n }\n console.log(\"group selections:\");\n for (const [group, proxy] of entries) {\n console.log(` ${group}: ${proxy}`);\n }\n}\n\nfunction useGroup(groupName: string, profile: string | undefined): Promise<void> {\n const context = loadProfileContext(profile);\n ensureGroupExists(context.raw, groupName);\n updateProfileState(context.path, (state): ProfileStateEntry => {\n const selected = [...(state.selected ?? [])];\n const existingIndex = selected.findIndex(\n (s: ProxyGroupSelection): boolean => s.name === \"GLOBAL\",\n );\n if (existingIndex >= 0) {\n selected[existingIndex] = { name: \"GLOBAL\", now: groupName };\n } else {\n selected.push({ name: \"GLOBAL\", now: groupName });\n }\n return { ...state, selected };\n });\n loadEffectiveProfileConfig(context.path);\n console.log(`Active proxy group: ${groupName}`);\n return dispatchLive(profile, { cmd: \"useGroup\", group: groupName });\n}\n\nfunction selectGroupProxy(\n groupName: string,\n proxyName: string,\n profile: string | undefined,\n): Promise<void> {\n const context = loadProfileContext(profile);\n const group = ensureGroupExists(context.raw, groupName);\n if (!group.proxies.includes(proxyName)) {\n throw new ConfigError(\n `proxy-group ${groupName} does not contain selectable proxy: ${proxyName}`,\n );\n }\n updateProfileState(context.path, (state): ProfileStateEntry => {\n const selected = [...(state.selected ?? [])];\n const existingIndex = selected.findIndex(\n (s: ProxyGroupSelection): boolean => s.name === groupName,\n );\n if (existingIndex >= 0) {\n selected[existingIndex] = { name: groupName, now: proxyName };\n } else {\n selected.push({ name: groupName, now: proxyName });\n }\n return { ...state, selected };\n });\n loadEffectiveProfileConfig(context.path);\n console.log(`Selected ${proxyName} for group ${groupName}`);\n return dispatchLive(profile, {\n cmd: \"selectGroup\",\n group: groupName,\n proxy: proxyName,\n });\n}\n\nfunction setRuntimeMode(mode: string, profile: string | undefined): Promise<void> {\n if (![\"rule\", \"global\", \"direct\", \"script\"].includes(mode)) {\n throw new ConfigError(`Unsupported mode: ${mode}`);\n }\n const context = loadProfileContext(profile);\n updateProfileState(context.path, (state): ProfileStateEntry => ({\n ...state,\n mode: mode as ProfileMode,\n }));\n loadEffectiveProfileConfig(context.path);\n console.log(`Mode set to ${mode}`);\n return dispatchLive(profile, { cmd: \"setMode\", mode });\n}\n\nfunction unsetGroupSelection(\n groupName: string,\n profile: string | undefined,\n): Promise<void> {\n const context = loadProfileContext(profile);\n ensureGroupExists(context.raw, groupName);\n updateProfileState(context.path, (state): ProfileStateEntry => {\n const selected = (state.selected ?? []).filter(\n (s: ProxyGroupSelection): boolean => s.name !== groupName,\n );\n return { ...state, selected };\n });\n loadEffectiveProfileConfig(context.path);\n console.log(`Removed explicit selection for group ${groupName}`);\n return dispatchLive(profile, { cmd: \"unsetGroup\", group: groupName });\n}\n\n/**\n * 写盘后把变更下发给运行中的 daemon。仅当操作的是当前活动 profile 时下发;\n * daemon 未运行时静默跳过,提示下次启动生效。\n */\nasync function dispatchLive(\n profile: string | undefined,\n command: ControlCommand,\n): Promise<void> {\n const activeProfile = loadLynxUserConfig().profile;\n if (profile !== undefined && profile !== activeProfile) {\n // 操作的是非活动 profile,daemon 跑的不是它,不下发\n return;\n }\n const response = await sendControlCommand(command);\n if (response === undefined) {\n console.log(\"Daemon not running; change will apply on next start.\");\n return;\n }\n if (response.ok) {\n console.log(\"Applied to running daemon.\");\n } else {\n console.log(`Daemon rejected live update: ${response.error ?? \"unknown error\"}`);\n }\n}\n\nfunction runRuleCommand(args: readonly string[]): void {\n const [command, ...rest] = args;\n if (command === \"list\") {\n listRules(parseOptions(rest).profile);\n return;\n }\n if (command === \"set\") {\n const options = parseOptions(rest);\n setRuleTarget(\n requireArg(options.rest[0], \"rule\"),\n requireArg(options.rest[1], \"target\"),\n options.profile,\n );\n return;\n }\n throw new Error(`Unknown groups rule command: ${String(command)}`);\n}\n\nfunction listRules(profile: string | undefined): void {\n const context = loadProfileContext(profile);\n const rules = getRules(context.raw);\n if (rules.length === 0) {\n console.log(`No rules found in ${context.path}`);\n return;\n }\n\n rules.forEach((rule: string, index: number): void => {\n const parts = splitRule(rule);\n const type = parts[0] ?? \"\";\n const target = type.toUpperCase() === \"MATCH\" ? parts[1] : parts[2];\n console.log(`${index}: ${rule}`);\n if (target !== undefined) {\n console.log(` target: ${target}`);\n }\n });\n console.log(`default: ${formatRoute(context.config)}`);\n}\n\nfunction setRuleTarget(\n ruleRef: string,\n target: string,\n profile: string | undefined,\n): void {\n const context = loadProfileContext(profile);\n ensureTargetExists(context.raw, target);\n const rules = getRules(context.raw);\n const index = resolveRuleIndex(rules, ruleRef);\n const rule = rules[index];\n if (rule === undefined) {\n throw new ConfigError(`Rule not found: ${ruleRef}`);\n }\n const parts = splitRule(rule);\n const type = parts[0]?.toUpperCase();\n if (type === \"MATCH\") {\n rules[index] = `MATCH,${target}`;\n } else if (parts.length >= 3) {\n parts[2] = target;\n rules[index] = parts.join(\",\");\n } else {\n throw new ConfigError(`Cannot update malformed rule: ${rule}`);\n }\n writeProfileContext(context);\n console.log(`Updated rule ${index} target to ${target}`);\n}\n\nfunction loadProfileContext(profile: string | undefined): ProfileContext {\n const selected = profile ?? loadLynxUserConfig().profile;\n const path = resolveProfilePath(selected);\n const content = readFileSync(path, \"utf8\");\n const raw = parseConfigFile(path, content);\n const object = asRecord(raw, \"profile config\");\n const stateKey = getProfileStateKey(path);\n const state =\n findProfileStateEntry(loadLynxStateConfig(), stateKey) ??\n ({ name: stateKey, selected: [] } as ProfileStateEntry);\n return {\n path,\n stateKey,\n statePath: getDefaultStateConfigPath(),\n raw: object,\n config: loadEffectiveProfileConfig(path),\n state,\n };\n}\n\nfunction writeProfileContext(context: ProfileContext): void {\n writeFileSync(context.path, serializeConfig(context.path, context.raw), \"utf8\");\n const raw = parseConfigFile(\n context.path,\n readFileSync(context.path, \"utf8\"),\n );\n loadConfigFromRaw(asRecord(raw, \"profile config\"));\n loadEffectiveProfileConfig(context.path);\n}\n\nfunction serializeConfig(path: string, raw: Record<string, unknown>): string {\n const ext = extname(path);\n if (ext === \".json\") {\n return `${JSON.stringify(raw, null, 2)}\\n`;\n }\n if (ext === \".toml\") {\n return stringifyToml(raw);\n }\n if (ext === \".yaml\" || ext === \".yml\") {\n return dumpYaml(raw);\n }\n throw new ConfigError(`Unsupported profile file extension: ${ext}`);\n}\n\nfunction getProxyGroups(raw: Record<string, unknown>): Array<{\n name: string;\n proxies: string[];\n}> {\n const value = raw[\"proxy-groups\"];\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new ConfigError(\"proxy-groups must be an array\");\n }\n return value.map((item: unknown, index: number) => {\n const object = asRecord(item, `proxy-groups[${index}]`);\n const name = requireString(object[\"name\"], `proxy-groups[${index}].name`);\n const proxies = requireStringArray(\n object[\"proxies\"],\n `proxy-groups[${index}].proxies`,\n );\n return { name, proxies };\n });\n}\n\nfunction ensureGroupExists(\n raw: Record<string, unknown>,\n groupName: string,\n): { name: string; proxies: string[] } {\n const group = getProxyGroups(raw).find(\n (candidate): boolean => candidate.name === groupName,\n );\n if (group === undefined) {\n throw new ConfigError(`Unknown proxy-group: ${groupName}`);\n }\n return group;\n}\n\nfunction ensureTargetExists(raw: Record<string, unknown>, target: string): void {\n if (target === \"DIRECT\") {\n return;\n }\n const proxyNames = new Set(\n getNamedItems(raw[\"proxies\"], \"proxies\").map((proxy) => proxy.name),\n );\n const groupNames = new Set(\n getProxyGroups(raw).map((group): string => group.name),\n );\n if (!proxyNames.has(target) && !groupNames.has(target)) {\n throw new ConfigError(`Unknown rule target: ${target}`);\n }\n}\n\nfunction getNamedItems(\n value: unknown,\n field: string,\n): Array<{ name: string }> {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new ConfigError(`${field} must be an array`);\n }\n return value.map((item: unknown, index: number): { name: string } => {\n const object = asRecord(item, `${field}[${index}]`);\n return { name: requireString(object[\"name\"], `${field}[${index}].name`) };\n });\n}\n\nfunction getRules(raw: Record<string, unknown>): string[] {\n const value = raw[\"rules\"];\n if (value === undefined) {\n const rules: string[] = [];\n raw[\"rules\"] = rules;\n return rules;\n }\n if (!Array.isArray(value)) {\n throw new ConfigError(\"rules must be an array\");\n }\n value.forEach((item: unknown, index: number): void => {\n requireString(item, `rules[${index}]`);\n });\n return value as string[];\n}\n\nfunction resolveRuleIndex(rules: readonly string[], ruleRef: string): number {\n if (/^\\d+$/.test(ruleRef)) {\n const index = Number(ruleRef);\n if (index < rules.length) {\n return index;\n }\n }\n if (ruleRef.toUpperCase() === \"MATCH\") {\n const index = rules.findIndex(\n (rule: string): boolean => splitRule(rule)[0]?.toUpperCase() === \"MATCH\",\n );\n if (index !== -1) {\n return index;\n }\n }\n const index = rules.findIndex((rule: string): boolean => rule === ruleRef);\n if (index !== -1) {\n return index;\n }\n throw new ConfigError(`Rule not found: ${ruleRef}`);\n}\n\nfunction parseOptions(args: readonly string[]): ParsedOptions {\n const rest: string[] = [];\n let profile: string | undefined;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === \"--profile\") {\n profile = requireArg(args[index + 1], \"profile\");\n index += 1;\n } else if (arg !== undefined) {\n rest.push(arg);\n }\n }\n if (profile === undefined) {\n return { rest };\n }\n return { profile, rest };\n}\n\nfunction splitRule(rule: string): string[] {\n return rule.split(\",\").map((part: string): string => part.trim());\n}\n\nfunction formatRoute(config: AppConfig): string {\n if (config.route.default === \"DIRECT\") {\n return \"DIRECT\";\n }\n return `PROXY ${config.route.defaultProxy ?? \"(missing proxy)\"}`;\n}\n\nfunction requireString(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ConfigError(`${field} must be a non-empty string`);\n }\n return value;\n}\n\nfunction requireStringArray(value: unknown, field: string): string[] {\n if (!Array.isArray(value)) {\n throw new ConfigError(`${field} must be an array`);\n }\n return value.map((item: unknown, index: number): string =>\n requireString(item, `${field}[${index}]`),\n );\n}\n\nfunction asRecord(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigError(`${field} must be a table`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requireArg(value: string | undefined, name: string): string {\n if (value === undefined || value.length === 0) {\n throw new Error(`Missing ${name}`);\n }\n return value;\n}\n\nfunction createGroupsHelpText(): string {\n return `Usage: lynx groups <command> [options]\n\nCommands:\n list [--profile <profile>] List proxy groups and selections\n current [--profile <profile>] Show active group and all selections\n use <group> [--profile <profile>] Set active proxy group in state.json\n select <group> <proxy> [--profile <profile>] Select a proxy for a group in state.json\n mode <rule|global|direct|script> [--profile p] Set runtime mode in state.json\n unset <group> [--profile <profile>] Remove explicit state selection\n rule list [--profile <profile>] List rules and targets\n rule set <rule|index|MATCH> <target> [--profile p] Update a rule target\n\nSelection, group and mode changes are written to state.json and, when the daemon\nis running the active profile, applied live over the control socket.`;\n}\n","import { appendFileSync } from \"node:fs\";\nimport type { LogConfig, LogLevel } from \"../config/models.js\";\n\nexport interface Logger {\n debug(message: string): void;\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n access(message: string): void;\n isAccessEnabled(): boolean;\n}\n\nconst LEVEL_PRIORITY: Readonly<Record<LogLevel, number>> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\nexport function createLogger(config: LogConfig): Logger {\n return new ConsoleLogger(config);\n}\n\nexport function createDefaultLogger(): Logger {\n return createLogger({ level: \"debug\", access: true });\n}\n\nclass ConsoleLogger implements Logger {\n public constructor(private readonly config: LogConfig) {}\n\n public debug(message: string): void {\n this.write(\"debug\", message);\n }\n\n public info(message: string): void {\n this.write(\"info\", message);\n }\n\n public warn(message: string): void {\n this.write(\"warn\", message);\n }\n\n public error(message: string): void {\n this.write(\"error\", message);\n }\n\n public access(message: string): void {\n if (!this.config.access) {\n return;\n }\n this.writeLine(`${message}\\n`, \"stdout\");\n }\n\n public isAccessEnabled(): boolean {\n return this.config.access;\n }\n\n private write(level: LogLevel, message: string): void {\n if (!this.shouldWrite(level)) {\n return;\n }\n\n const line = `${new Date().toISOString()} ${level.toUpperCase()} ${message}\\n`;\n this.writeLine(line, level === \"error\" ? \"stderr\" : \"stdout\");\n }\n\n private writeLine(line: string, stream: \"stdout\" | \"stderr\"): void {\n if (stream === \"stderr\") {\n process.stderr.write(line);\n } else {\n process.stdout.write(line);\n }\n\n if (this.config.file !== undefined) {\n appendFileSync(this.config.file, line, \"utf8\");\n }\n }\n\n private shouldWrite(level: LogLevel): boolean {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[this.config.level];\n }\n}\n","import { createConnection } from \"node:net\";\nimport type { Socket } from \"node:net\";\n\nexport interface TcpConnectOptions {\n host: string;\n port: number;\n timeoutMs: number;\n}\n\nexport function connectTcp(options: TcpConnectOptions): Promise<Socket> {\n return new Promise<Socket>(\n (\n resolve: (socket: Socket) => void,\n reject: (error: Error) => void,\n ): void => {\n const socket = createConnection({\n host: options.host,\n port: options.port,\n });\n\n const cleanup = (): void => {\n socket.removeListener(\"connect\", onConnect);\n socket.removeListener(\"error\", onError);\n socket.removeListener(\"timeout\", onTimeout);\n };\n\n const onConnect = (): void => {\n cleanup();\n socket.setTimeout(0);\n resolve(socket);\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onTimeout = (): void => {\n cleanup();\n socket.destroy();\n reject(\n new Error(\n `TCP connect timeout: ${options.host}:${options.port}`,\n ),\n );\n };\n\n socket.setTimeout(options.timeoutMs);\n socket.once(\"connect\", onConnect);\n socket.once(\"error\", onError);\n socket.once(\"timeout\", onTimeout);\n },\n );\n}\n","import type { Socket } from \"node:net\";\nimport type { UpstreamProxy } from \"./base.js\";\nimport { connectTcp } from \"../transport/tcp.js\";\n\nexport class DirectProxy implements UpstreamProxy {\n public constructor(private readonly connectTimeoutMs: number) {}\n\n public connect(targetHost: string, targetPort: number): Promise<Socket> {\n return connectTcp({\n host: targetHost,\n port: targetPort,\n timeoutMs: this.connectTimeoutMs,\n });\n }\n}\n","import { isIP } from \"node:net\";\nimport type { Socket } from \"node:net\";\nimport type { Socks5ProxyConfig } from \"../config/models.js\";\nimport type { UpstreamProxy } from \"./base.js\";\nimport { connectTcp } from \"../transport/tcp.js\";\n\nconst SOCKS_VERSION = 0x05;\nconst USERPASS_VERSION = 0x01;\n\nexport class Socks5Proxy implements UpstreamProxy {\n public constructor(\n private readonly config: Socks5ProxyConfig,\n private readonly connectTimeoutMs: number,\n ) {}\n\n public async connect(\n targetHost: string,\n targetPort: number,\n ): Promise<Socket> {\n const socket = await connectTcp({\n host: this.config.host,\n port: this.config.port,\n timeoutMs: this.connectTimeoutMs,\n });\n\n try {\n await this.negotiate(socket);\n await this.sendConnect(socket, targetHost, targetPort);\n return socket;\n } catch (error) {\n socket.destroy();\n throw error;\n }\n }\n\n private async negotiate(socket: Socket): Promise<void> {\n const methods =\n this.config.username === undefined\n ? Buffer.from([SOCKS_VERSION, 0x01, 0x00])\n : Buffer.from([SOCKS_VERSION, 0x02, 0x00, 0x02]);\n socket.write(methods);\n\n const response = await readExact(socket, 2);\n if (response[0] !== SOCKS_VERSION) {\n throw new Error(\"Invalid SOCKS5 negotiation response\");\n }\n\n const method = response[1];\n if (method === 0x00) {\n return;\n }\n\n if (method === 0x02) {\n await this.authenticate(socket);\n return;\n }\n\n throw new Error(\n \"SOCKS5 server does not accept supported authentication methods\",\n );\n }\n\n private async authenticate(socket: Socket): Promise<void> {\n const username = this.config.username;\n const password = this.config.password;\n if (username === undefined || password === undefined) {\n throw new Error(\n \"SOCKS5 username/password authentication requested but credentials are missing\",\n );\n }\n\n const usernameBytes = Buffer.from(username, \"utf8\");\n const passwordBytes = Buffer.from(password, \"utf8\");\n if (usernameBytes.length > 255 || passwordBytes.length > 255) {\n throw new Error(\n \"SOCKS5 username and password must be at most 255 bytes\",\n );\n }\n\n socket.write(\n Buffer.concat([\n Buffer.from([USERPASS_VERSION, usernameBytes.length]),\n usernameBytes,\n Buffer.from([passwordBytes.length]),\n passwordBytes,\n ]),\n );\n\n const response = await readExact(socket, 2);\n if (response[0] !== USERPASS_VERSION || response[1] !== 0x00) {\n throw new Error(\"SOCKS5 username/password authentication failed\");\n }\n }\n\n private async sendConnect(\n socket: Socket,\n targetHost: string,\n targetPort: number,\n ): Promise<void> {\n socket.write(buildSocksConnectRequest(targetHost, targetPort));\n const header = await readExact(socket, 4);\n if (header[0] !== SOCKS_VERSION) {\n throw new Error(\"Invalid SOCKS5 CONNECT response\");\n }\n if (header[1] !== 0x00) {\n throw new Error(`SOCKS5 CONNECT failed with code ${header[1]}`);\n }\n\n const atyp = header[3];\n if (atyp === 0x01) {\n await readExact(socket, 4 + 2);\n } else if (atyp === 0x03) {\n const length = await readExact(socket, 1);\n await readExact(socket, Number(length[0]) + 2);\n } else if (atyp === 0x04) {\n await readExact(socket, 16 + 2);\n } else {\n throw new Error(\n \"SOCKS5 CONNECT response has unsupported address type\",\n );\n }\n }\n}\n\nfunction buildSocksConnectRequest(\n targetHost: string,\n targetPort: number,\n): Buffer {\n const port = Buffer.allocUnsafe(2);\n port.writeUInt16BE(targetPort, 0);\n\n const ipType = isIP(targetHost);\n if (ipType === 4) {\n const octets = targetHost\n .split(\".\")\n .map((part: string): number => Number(part));\n return Buffer.concat([\n Buffer.from([SOCKS_VERSION, 0x01, 0x00, 0x01, ...octets]),\n port,\n ]);\n }\n\n if (ipType === 6) {\n const address = ipv6ToBuffer(targetHost);\n return Buffer.concat([\n Buffer.from([SOCKS_VERSION, 0x01, 0x00, 0x04]),\n address,\n port,\n ]);\n }\n\n const domain = Buffer.from(targetHost, \"utf8\");\n if (domain.length > 255) {\n throw new Error(\"SOCKS5 target domain is too long\");\n }\n return Buffer.concat([\n Buffer.from([SOCKS_VERSION, 0x01, 0x00, 0x03, domain.length]),\n domain,\n port,\n ]);\n}\n\nfunction readExact(socket: Socket, length: number): Promise<Buffer> {\n return new Promise<Buffer>(\n (\n resolve: (buffer: Buffer) => void,\n reject: (error: Error) => void,\n ): void => {\n let buffered = Buffer.alloc(0);\n\n const cleanup = (): void => {\n socket.removeListener(\"data\", onData);\n socket.removeListener(\"error\", onError);\n socket.removeListener(\"close\", onClose);\n };\n\n const onData = (chunk: Buffer): void => {\n buffered = Buffer.concat([buffered, chunk]);\n if (buffered.length >= length) {\n cleanup();\n const needed = buffered.subarray(0, length);\n const rest = buffered.subarray(length);\n if (rest.length > 0) {\n socket.unshift(rest);\n }\n resolve(needed);\n }\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onClose = (): void => {\n cleanup();\n reject(\n new Error(\"Socket closed while reading SOCKS5 response\"),\n );\n };\n\n socket.on(\"data\", onData);\n socket.once(\"error\", onError);\n socket.once(\"close\", onClose);\n },\n );\n}\n\nfunction ipv6ToBuffer(address: string): Buffer {\n const normalized = expandIpv6(address);\n const buffer = Buffer.allocUnsafe(16);\n normalized.forEach((part: number, index: number): void => {\n buffer.writeUInt16BE(part, index * 2);\n });\n return buffer;\n}\n\nfunction expandIpv6(address: string): number[] {\n const halves = address.split(\"::\");\n const left =\n halves[0] === undefined || halves[0].length === 0\n ? []\n : halves[0].split(\":\");\n const right =\n halves[1] === undefined || halves[1].length === 0\n ? []\n : halves[1].split(\":\");\n const missing = 8 - left.length - right.length;\n const parts = [\n ...left,\n ...Array.from({ length: missing }, (): string => \"0\"),\n ...right,\n ];\n return parts.map((part: string): number => Number.parseInt(part, 16));\n}\n","import { createHash } from \"node:crypto\";\nimport { TextEncoder } from \"node:util\";\n\nexport function hashPassword(str: string): Uint8Array {\n const hash = createHash(\"sha224\");\n let encoder = new TextEncoder();\n\n let hashStr = hash.update(encoder.encode(str)).digest(\"hex\");\n return encoder.encode(hashStr);\n}\n","import { isIP } from \"node:net\";\nimport { connect } from \"node:tls\";\nimport type { TLSSocket } from \"node:tls\";\nimport type { TrojanProxyConfig } from \"../config/models.js\";\nimport type { UpstreamProxy } from \"./base.js\";\nimport { hashPassword } from \"../utils/Crypto.js\";\n\nconst TROJAN_CMD_CONNECT = 0x01;\n\nexport class TrojanProxy implements UpstreamProxy {\n public constructor(\n private readonly config: TrojanProxyConfig,\n private readonly connectTimeoutMs: number,\n ) {}\n\n public async connect(\n targetHost: string,\n targetPort: number,\n ): Promise<TLSSocket> {\n const socket = await this.connectTls();\n try {\n socket.write(\n buildTrojanRequest(\n this.config.password,\n targetHost,\n targetPort,\n ),\n );\n return socket;\n } catch (error) {\n socket.destroy();\n throw error;\n }\n }\n\n private connectTls(): Promise<TLSSocket> {\n return new Promise<TLSSocket>(\n (\n resolve: (socket: TLSSocket) => void,\n reject: (error: Error) => void,\n ): void => {\n const socket = connect({\n host: this.config.host,\n port: this.config.port,\n servername: this.config.serverName,\n rejectUnauthorized: !this.config.allowInvalidCert,\n });\n\n const cleanup = (): void => {\n socket.removeListener(\"secureConnect\", onSecureConnect);\n socket.removeListener(\"error\", onError);\n socket.removeListener(\"timeout\", onTimeout);\n };\n\n const onSecureConnect = (): void => {\n cleanup();\n socket.setTimeout(0);\n resolve(socket);\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onTimeout = (): void => {\n cleanup();\n socket.destroy();\n reject(\n new Error(\n `Trojan TLS connect timeout: ${this.config.host}:${this.config.port}`,\n ),\n );\n };\n\n socket.setTimeout(this.connectTimeoutMs);\n socket.once(\"secureConnect\", onSecureConnect);\n socket.once(\"error\", onError);\n socket.once(\"timeout\", onTimeout);\n },\n );\n }\n}\n\nfunction buildTrojanRequest(\n password: string,\n targetHost: string,\n targetPort: number,\n): Buffer {\n const hash = Buffer.from(hashPassword(password));\n const crlf = Buffer.from(\"\\r\\n\", \"ascii\");\n const command = Buffer.from([TROJAN_CMD_CONNECT]);\n const address = encodeAddress(targetHost);\n const port = Buffer.allocUnsafe(2);\n port.writeUInt16BE(targetPort, 0);\n return Buffer.concat([hash, crlf, command, address, port, crlf]);\n}\n\nfunction encodeAddress(host: string): Buffer {\n const ipType = isIP(host);\n if (ipType === 4) {\n return Buffer.from([\n 0x01,\n ...host.split(\".\").map((part: string): number => Number(part)),\n ]);\n }\n\n if (ipType === 6) {\n return Buffer.concat([Buffer.from([0x04]), ipv6ToBuffer(host)]);\n }\n\n const domain = Buffer.from(host, \"utf8\");\n if (domain.length > 255) {\n throw new Error(\"Trojan target domain is too long\");\n }\n return Buffer.concat([Buffer.from([0x03, domain.length]), domain]);\n}\n\nfunction ipv6ToBuffer(address: string): Buffer {\n const halves = address.split(\"::\");\n const left =\n halves[0] === undefined || halves[0].length === 0\n ? []\n : halves[0].split(\":\");\n const right =\n halves[1] === undefined || halves[1].length === 0\n ? []\n : halves[1].split(\":\");\n const missing = 8 - left.length - right.length;\n const parts = [\n ...left,\n ...Array.from({ length: missing }, (): string => \"0\"),\n ...right,\n ];\n const buffer = Buffer.allocUnsafe(16);\n parts.forEach((part: string, index: number): void => {\n buffer.writeUInt16BE(Number.parseInt(part, 16), index * 2);\n });\n return buffer;\n}\n","import type { Socket } from \"node:net\";\nimport type { ProxyConfig } from \"../config/models.js\";\nimport { DirectProxy } from \"./direct.js\";\nimport { Socks5Proxy } from \"./socks5.js\";\nimport { TrojanProxy } from \"./trojan.js\";\n\nexport interface UpstreamProxy {\n connect(targetHost: string, targetPort: number): Promise<Socket>;\n}\n\nexport function createUpstreamProxy(\n config: ProxyConfig,\n connectTimeoutMs: number,\n): UpstreamProxy {\n if (config.type === \"direct\") {\n return new DirectProxy(connectTimeoutMs);\n }\n if (config.type === \"socks5\") {\n return new Socks5Proxy(config, connectTimeoutMs);\n }\n return new TrojanProxy(config, connectTimeoutMs);\n}\n","import type { ParsedHttpRequest, ParsedTarget } from \"./models.js\";\n\nconst HEADER_END = \"\\r\\n\\r\\n\";\n\nexport class HttpParseError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"HttpParseError\";\n }\n}\n\nexport function findHeaderEnd(buffer: Buffer): number {\n return buffer.indexOf(HEADER_END);\n}\n\nexport function parseHttpRequest(buffer: Buffer): ParsedHttpRequest {\n const headerEnd = findHeaderEnd(buffer);\n if (headerEnd < 0) {\n throw new HttpParseError(\"HTTP header is incomplete\");\n }\n\n const headerText = buffer.subarray(0, headerEnd).toString(\"latin1\");\n const lines = headerText.split(\"\\r\\n\");\n const requestLine = lines[0];\n if (requestLine === undefined) {\n throw new HttpParseError(\"Missing request line\");\n }\n\n const requestParts = requestLine\n .split(\" \")\n .filter((part: string): boolean => part.length > 0);\n if (requestParts.length !== 3) {\n throw new HttpParseError(\"Invalid request line\");\n }\n\n const method = requestParts[0];\n const requestTarget = requestParts[1];\n const version = requestParts[2];\n if (\n method === undefined ||\n requestTarget === undefined ||\n version === undefined ||\n !version.startsWith(\"HTTP/\")\n ) {\n throw new HttpParseError(\"Invalid request line\");\n }\n\n const headers: Record<string, string> = {};\n for (const line of lines.slice(1)) {\n if (line.length === 0) {\n continue;\n }\n const colonIndex = line.indexOf(\":\");\n if (colonIndex <= 0) {\n throw new HttpParseError(`Invalid header line: ${line}`);\n }\n const name = line.slice(0, colonIndex).trim().toLowerCase();\n const value = line.slice(colonIndex + 1).trim();\n headers[name] = value;\n }\n\n return {\n method,\n requestTarget,\n version,\n headers,\n headerLength: headerEnd + HEADER_END.length,\n };\n}\n\nexport function parseTarget(request: ParsedHttpRequest): ParsedTarget {\n if (request.method.toUpperCase() === \"CONNECT\") {\n const { host, port } = parseHostPort(request.requestTarget, 443, {\n requirePort: true,\n });\n return { host, port, scheme: \"https\", path: \"\", isConnect: true };\n }\n\n if (\n request.requestTarget.startsWith(\"http://\") ||\n request.requestTarget.startsWith(\"https://\")\n ) {\n let url: URL;\n try {\n url = new URL(request.requestTarget);\n } catch {\n throw new HttpParseError(\"Invalid request target URL\");\n }\n\n const scheme = url.protocol.slice(0, -1);\n const port =\n url.port.length > 0\n ? parsePort(url.port)\n : defaultPortForScheme(scheme);\n if (url.hostname.length === 0) {\n throw new HttpParseError(\"Missing target host\");\n }\n return {\n host: url.hostname,\n port,\n scheme,\n path: `${url.pathname}${url.search}`,\n isConnect: false,\n };\n }\n\n const hostHeader = request.headers[\"host\"];\n if (hostHeader === undefined || hostHeader.trim().length === 0) {\n throw new HttpParseError(\"Missing Host header\");\n }\n const { host, port } = parseHostPort(hostHeader, 80);\n return {\n host,\n port,\n scheme: \"http\",\n path: request.requestTarget,\n isConnect: false,\n };\n}\n\nexport function rewriteAbsoluteFormToOriginForm(\n request: ParsedHttpRequest,\n originalBuffer: Buffer,\n): Buffer {\n if (request.method.toUpperCase() === \"CONNECT\") {\n return originalBuffer;\n }\n\n const target = parseTarget(request);\n const headerEnd = findHeaderEnd(originalBuffer);\n if (headerEnd < 0) {\n throw new HttpParseError(\"HTTP header is incomplete\");\n }\n\n const headerText = originalBuffer.subarray(0, headerEnd).toString(\"latin1\");\n const lines = headerText.split(\"\\r\\n\");\n const rewrittenLines = [\n `${request.method} ${target.path.length > 0 ? target.path : \"/\"} ${request.version}`,\n ];\n\n for (const line of lines.slice(1)) {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex <= 0) {\n continue;\n }\n const headerName = line.slice(0, colonIndex).trim().toLowerCase();\n if (headerName === \"proxy-connection\") {\n continue;\n }\n rewrittenLines.push(line);\n }\n\n const rewrittenHeader = `${rewrittenLines.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n const body = originalBuffer.subarray(headerEnd + HEADER_END.length);\n return Buffer.concat([Buffer.from(rewrittenHeader, \"latin1\"), body]);\n}\n\nexport function createHttpErrorResponse(\n statusCode: number,\n reason: string,\n): Buffer {\n const body = `${statusCode} ${reason}\\n`;\n return Buffer.from(\n `HTTP/1.1 ${statusCode} ${reason}\\r\\nConnection: close\\r\\nContent-Type: text/plain; charset=utf-8\\r\\nContent-Length: ${Buffer.byteLength(body)}\\r\\n\\r\\n${body}`,\n \"utf8\",\n );\n}\n\nfunction parseHostPort(\n value: string,\n defaultPort: number,\n options: { requirePort?: boolean } = {},\n): { host: string; port: number } {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n throw new HttpParseError(\"Missing host\");\n }\n\n if (trimmed.startsWith(\"[\")) {\n const closing = trimmed.indexOf(\"]\");\n if (closing < 0) {\n throw new HttpParseError(`Invalid host:port value: ${value}`);\n }\n const host = trimmed.slice(1, closing);\n if (host.length === 0) {\n throw new HttpParseError(\"Missing host\");\n }\n const rest = trimmed.slice(closing + 1);\n if (rest.length === 0) {\n if (options.requirePort === true) {\n throw new HttpParseError(`Missing port in host:port value: ${value}`);\n }\n return { host, port: defaultPort };\n }\n if (!rest.startsWith(\":\")) {\n throw new HttpParseError(`Invalid host:port value: ${value}`);\n }\n return { host, port: parsePort(rest.slice(1)) };\n }\n\n if (trimmed.includes(\"[\") || trimmed.includes(\"]\")) {\n throw new HttpParseError(`Invalid host:port value: ${value}`);\n }\n\n const firstColon = trimmed.indexOf(\":\");\n const lastColon = trimmed.lastIndexOf(\":\");\n if (firstColon !== lastColon) {\n throw new HttpParseError(`Invalid host:port value: ${value}`);\n }\n\n if (lastColon >= 0) {\n const host = trimmed.slice(0, lastColon);\n if (host.length === 0) {\n throw new HttpParseError(\"Missing host\");\n }\n return { host, port: parsePort(trimmed.slice(lastColon + 1)) };\n }\n\n if (options.requirePort === true) {\n throw new HttpParseError(`Missing port in host:port value: ${value}`);\n }\n return { host: trimmed, port: defaultPort };\n}\n\nfunction parsePort(value: string): number {\n if (!/^\\d+$/.test(value)) {\n throw new HttpParseError(`Invalid port: ${value}`);\n }\n const port = Number(value);\n if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {\n throw new HttpParseError(`Invalid port: ${value}`);\n }\n return port;\n}\n\nfunction defaultPortForScheme(scheme: string): number {\n if (scheme === \"https\") {\n return 443;\n }\n return 80;\n}\n","import type { AppConfig, ProfileMode, RuleConfig } from \"../config/models.js\";\nimport type { RouteResult, RouteTarget } from \"./rules.js\";\n\nexport function matchRoute(\n config: Pick<AppConfig, \"route\" | \"rules\" | \"proxies\" | \"proxyGroups\" | \"user\">,\n target: RouteTarget,\n mode: ProfileMode | undefined,\n globalProxySelection: string | undefined,\n groupSelections?: ReadonlyMap<string, string>,\n): RouteResult {\n if (mode === \"direct\" || mode === \"script\") {\n return { action: \"DIRECT\", ruleName: \"direct-mode\" };\n }\n\n if (mode === \"global\") {\n if (globalProxySelection === undefined || globalProxySelection === \"DIRECT\") {\n return { action: \"DIRECT\", ruleName: \"global-mode\" };\n }\n return {\n action: \"PROXY\",\n proxyName: globalProxySelection,\n ruleName: \"global-mode\",\n };\n }\n\n const proxyNames = new Set(config.proxies.map((p) => p.name));\n const proxyGroups = new Map(config.proxyGroups.map((g) => [g.name, g]));\n // 运行时逐组选择优先;缺省时回落到配置加载阶段的静态选择\n const selections: Record<string, string> =\n groupSelections !== undefined\n ? Object.fromEntries(groupSelections)\n : config.user.proxyGroupSelections;\n\n for (const rule of config.rules) {\n if (matchesRule(rule, target)) {\n if (rule.action === \"DIRECT\") {\n return { action: \"DIRECT\", ruleName: rule.name };\n }\n const proxyName = resolveProxyTarget(\n rule.proxy,\n config.route.defaultProxy,\n selections,\n proxyNames,\n proxyGroups,\n );\n if (proxyName === \"DIRECT\") {\n return { action: \"DIRECT\", ruleName: rule.name };\n }\n return { action: \"PROXY\", proxyName, ruleName: rule.name };\n }\n }\n\n if (config.route.default === \"DIRECT\") {\n return { action: \"DIRECT\", ruleName: \"default\" };\n }\n const defaultProxy = resolveProxyTarget(\n config.route.defaultProxy,\n undefined,\n selections,\n proxyNames,\n proxyGroups,\n );\n if (defaultProxy === \"DIRECT\") {\n return { action: \"DIRECT\", ruleName: \"default\" };\n }\n return { action: \"PROXY\", proxyName: defaultProxy, ruleName: \"default\" };\n}\n\nfunction resolveProxyTarget(\n target: string | undefined,\n fallback: string | undefined,\n selections: Record<string, string>,\n proxyNames: ReadonlySet<string>,\n proxyGroups: ReadonlyMap<string, { name: string; proxies: string[] }>,\n visiting: ReadonlySet<string> = new Set<string>(),\n): string {\n const targetName = target ?? fallback;\n if (targetName === undefined) {\n throw new Error(\"No proxy target specified\");\n }\n if (targetName === \"DIRECT\") {\n return \"DIRECT\";\n }\n if (proxyNames.has(targetName)) {\n return targetName;\n }\n\n const group = proxyGroups.get(targetName);\n if (group !== undefined) {\n if (visiting.has(targetName)) {\n throw new Error(`Cannot resolve cyclic proxy group: ${targetName}`);\n }\n const nextVisiting = new Set(visiting);\n nextVisiting.add(targetName);\n const selected = selections[targetName];\n if (selected !== undefined) {\n try {\n return resolveProxyTarget(\n selected,\n undefined,\n selections,\n proxyNames,\n proxyGroups,\n nextVisiting,\n );\n } catch {\n // 显式选择已失效(例如订阅更新后节点消失):\n // 降级到组内第一个可解析成员,而不是让路由失败。\n }\n }\n for (const candidate of group.proxies) {\n try {\n return resolveProxyTarget(\n candidate,\n undefined,\n selections,\n proxyNames,\n proxyGroups,\n nextVisiting,\n );\n } catch {\n // Try the next group member; config validation guarantees at least\n // one resolvable member for valid profiles.\n }\n }\n }\n throw new Error(`Cannot resolve proxy target: ${targetName}`);\n}\n\nfunction matchesRule(rule: RuleConfig, target: RouteTarget): boolean {\n const host = target.host.toLowerCase();\n const value = rule.value.toLowerCase();\n\n switch (rule.match) {\n case \"domain\":\n return host === value;\n case \"domain_suffix\":\n return matchesDomainSuffix(host, value);\n case \"domain_keyword\":\n return host.includes(value);\n case \"ip\":\n return host === value;\n case \"ip_cidr\":\n return matchesIpv4Cidr(host, value);\n case \"ip_cidr6\":\n return matchesIpv6Cidr(host, value);\n case \"port\":\n return target.port === Number(rule.value);\n case \"scheme\":\n return target.scheme?.toLowerCase() === value;\n case \"geoip\":\n return false;\n }\n}\n\nfunction matchesDomainSuffix(host: string, suffix: string): boolean {\n const normalized = suffix.startsWith(\".\") ? suffix.slice(1) : suffix;\n return host === normalized || host.endsWith(`.${normalized}`);\n}\n\nfunction matchesIpv4Cidr(host: string, cidr: string): boolean {\n const [network, prefixText] = cidr.split(\"/\");\n if (network === undefined || prefixText === undefined) {\n return false;\n }\n\n const ipValue = ipv4ToNumber(host);\n const networkValue = ipv4ToNumber(network);\n const prefix = Number(prefixText);\n if (\n ipValue === null ||\n networkValue === null ||\n !Number.isInteger(prefix) ||\n prefix < 0 ||\n prefix > 32\n ) {\n return false;\n }\n\n const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;\n return (ipValue & mask) === (networkValue & mask);\n}\n\nfunction ipv4ToNumber(value: string): number | null {\n const parts = value.split(\".\");\n if (parts.length !== 4) {\n return null;\n }\n\n let result = 0;\n for (const part of parts) {\n if (!/^\\d+$/.test(part)) {\n return null;\n }\n const byte = Number(part);\n if (!Number.isInteger(byte) || byte < 0 || byte > 255) {\n return null;\n }\n result = ((result << 8) | byte) >>> 0;\n }\n return result;\n}\n\nfunction matchesIpv6Cidr(host: string, cidr: string): boolean {\n const [network, prefixText] = cidr.split(\"/\");\n if (network === undefined || prefixText === undefined) {\n return false;\n }\n\n const ipValue = ipv6ToBigInt(host);\n const networkValue = ipv6ToBigInt(network);\n const prefix = Number(prefixText);\n if (\n ipValue === null ||\n networkValue === null ||\n !Number.isInteger(prefix) ||\n prefix < 0 ||\n prefix > 128\n ) {\n return false;\n }\n\n const hostBits = 128n - BigInt(prefix);\n const mask = prefix === 0 ? 0n : ((1n << BigInt(prefix)) - 1n) << hostBits;\n return (ipValue & mask) === (networkValue & mask);\n}\n\nfunction ipv6ToBigInt(value: string): bigint | null {\n if (value.includes(\".\")) {\n return null;\n }\n\n const separatorIndex = value.indexOf(\"::\");\n const hasCompression = separatorIndex !== -1;\n if (hasCompression && value.indexOf(\"::\", separatorIndex + 2) !== -1) {\n return null;\n }\n\n const left = hasCompression ? value.slice(0, separatorIndex) : value;\n const right = hasCompression ? value.slice(separatorIndex + 2) : \"\";\n const leftParts = splitIpv6Part(left);\n const rightParts = splitIpv6Part(right);\n if (leftParts === null || rightParts === null) {\n return null;\n }\n\n const missing = 8 - leftParts.length - rightParts.length;\n if (hasCompression ? missing < 1 : missing !== 0) {\n return null;\n }\n\n const parts = [\n ...leftParts,\n ...Array<number>(missing).fill(0),\n ...rightParts,\n ];\n if (parts.length !== 8) {\n return null;\n }\n\n let result = 0n;\n for (const part of parts) {\n result = (result << 16n) | BigInt(part);\n }\n return result;\n}\n\nfunction splitIpv6Part(value: string): number[] | null {\n if (value.length === 0) {\n return [];\n }\n\n const fields = value.split(\":\");\n const parts: number[] = [];\n for (const field of fields) {\n if (field.length === 0 || !/^[0-9a-fA-F]{1,4}$/.test(field)) {\n return null;\n }\n parts.push(Number.parseInt(field, 16));\n }\n return parts;\n}\n","import type { Socket } from \"node:net\";\n\nexport function relaySockets(client: Socket, remote: Socket): void {\n const closeBoth = (): void => {\n if (!client.destroyed) {\n client.destroy();\n }\n if (!remote.destroyed) {\n remote.destroy();\n }\n };\n\n client.on(\"error\", closeBoth);\n remote.on(\"error\", closeBoth);\n client.on(\"close\", closeBoth);\n remote.on(\"close\", closeBoth);\n\n client.pipe(remote);\n remote.pipe(client);\n}\n","import type { Socket } from \"node:net\";\nimport type { AppConfig } from \"../config/models.js\";\nimport {\n createHttpErrorResponse,\n findHeaderEnd,\n parseHttpRequest,\n parseTarget,\n rewriteAbsoluteFormToOriginForm,\n} from \"../http/parser.js\";\nimport type { ParsedHttpRequest, ParsedTarget } from \"../http/models.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport type { UpstreamProxy } from \"../protocol/base.js\";\nimport { DirectProxy } from \"../protocol/direct.js\";\nimport { matchRoute } from \"../router/matcher.js\";\nimport type { RouteResult, RouteTarget } from \"../router/rules.js\";\nimport { relaySockets } from \"../transport/relay.js\";\n\nconst MAX_HEADER_SIZE = 64 * 1024;\n\nexport interface HandlerContext {\n config: AppConfig;\n upstreams: ReadonlyMap<string, UpstreamProxy>;\n directProxy: DirectProxy;\n logger: Logger;\n runtimeState: RuntimeState;\n}\n\nexport interface RuntimeState {\n mode: AppConfig[\"mode\"];\n globalProxy: string | undefined;\n groupSelections: Map<string, string>;\n}\n\nexport function handleClientConnection(\n client: Socket,\n context: HandlerContext,\n): void {\n let buffer = Buffer.alloc(0);\n const startedAt = Date.now();\n\n const onData = (chunk: Buffer): void => {\n buffer = Buffer.concat([buffer, chunk]);\n if (buffer.length > MAX_HEADER_SIZE) {\n client.removeListener(\"data\", onData);\n writeErrorAndClose(client, 400, \"Bad Request\");\n return;\n }\n\n if (findHeaderEnd(buffer) < 0) {\n return;\n }\n\n client.removeListener(\"data\", onData);\n client.pause();\n void processClientRequest(client, buffer, context, startedAt);\n };\n\n client.on(\"data\", onData);\n client.on(\"error\", (): void => {\n client.destroy();\n });\n}\n\nasync function processClientRequest(\n client: Socket,\n buffer: Buffer,\n context: HandlerContext,\n startedAt: number,\n): Promise<void> {\n let request: ParsedHttpRequest | undefined;\n let target: ParsedTarget | undefined;\n let route: RouteResult | undefined;\n\n try {\n request = parseHttpRequest(buffer);\n target = parseTarget(request);\n route = matchRoute(\n context.config,\n toRouteTarget(request, target),\n context.runtimeState.mode,\n context.runtimeState.globalProxy,\n context.runtimeState.groupSelections,\n );\n const upstream = selectUpstream(context, route);\n const remote = await upstream.connect(target.host, target.port);\n\n if (target.isConnect) {\n client.write(\n Buffer.from(\n \"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\",\n \"ascii\",\n ),\n );\n const rest = buffer.subarray(request.headerLength);\n if (rest.length > 0) {\n remote.write(rest);\n }\n logAccess(context, request, target, route, startedAt);\n relaySockets(client, remote);\n client.resume();\n return;\n }\n\n remote.write(rewriteAbsoluteFormToOriginForm(request, buffer));\n logAccess(context, request, target, route, startedAt);\n relaySockets(client, remote);\n client.resume();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const statusCode =\n message.includes(\"Bad Request\") ||\n message.includes(\"Invalid\") ||\n message.includes(\"Missing\")\n ? 400\n : 502;\n logAccess(context, request, target, route, startedAt, message);\n writeErrorAndClose(\n client,\n statusCode,\n statusCode === 400 ? \"Bad Request\" : \"Bad Gateway\",\n );\n }\n}\n\nfunction toRouteTarget(\n request: ParsedHttpRequest,\n target: ParsedTarget,\n): RouteTarget {\n return {\n host: target.host,\n port: target.port,\n scheme: target.scheme,\n method: request.method,\n };\n}\n\nfunction selectUpstream(\n context: HandlerContext,\n route: RouteResult,\n): UpstreamProxy {\n if (route.action === \"DIRECT\") {\n return context.directProxy;\n }\n\n const proxyName = route.proxyName;\n if (proxyName === undefined) {\n throw new Error(\"PROXY route has no proxy name\");\n }\n\n const upstream = context.upstreams.get(proxyName);\n if (upstream === undefined) {\n throw new Error(`Unknown upstream proxy: ${proxyName}`);\n }\n return upstream;\n}\n\nfunction writeErrorAndClose(\n client: Socket,\n statusCode: number,\n reason: string,\n): void {\n if (client.destroyed) {\n return;\n }\n client.end(createHttpErrorResponse(statusCode, reason));\n}\n\nfunction logAccess(\n context: HandlerContext,\n request: ParsedHttpRequest | undefined,\n target: ParsedTarget | undefined,\n route: RouteResult | undefined,\n startedAt: number,\n error?: string,\n): void {\n if (!context.logger.isAccessEnabled()) {\n return;\n }\n\n const durationMs = Date.now() - startedAt;\n const method = request?.method ?? \"-\";\n const host = target?.host ?? \"-\";\n const port = target?.port ?? \"-\";\n const action = route?.action ?? \"-\";\n const proxy = route?.proxyName ?? \"-\";\n const rule = route?.ruleName ?? \"-\";\n const suffix = error === undefined ? \"\" : ` error=${JSON.stringify(error)}`;\n context.logger.access(\n `access method=${method} target=${host}:${port} action=${action} proxy=${proxy} rule=${JSON.stringify(rule)} duration_ms=${durationMs}${suffix}`,\n );\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\nimport type { AppConfig, ProxyConfig } from \"../config/models.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport { createLogger } from \"../logging/logger.js\";\nimport { createUpstreamProxy } from \"../protocol/base.js\";\nimport type { UpstreamProxy } from \"../protocol/base.js\";\nimport { DirectProxy } from \"../protocol/direct.js\";\nimport { handleClientConnection, type RuntimeState } from \"./handler.js\";\nimport type { HandlerContext } from \"./handler.js\";\n\nexport interface RuntimeSnapshot {\n mode: AppConfig[\"mode\"];\n globalProxy: string | undefined;\n groupSelections: Record<string, string>;\n}\n\nexport interface ProxyServer {\n close(): Promise<void>;\n setMode(mode: AppConfig[\"mode\"]): void;\n setGlobalProxy(proxy: string | undefined): void;\n selectGroup(group: string, proxy: string): void;\n unsetGroup(group: string): void;\n getSnapshot(): RuntimeSnapshot;\n}\n\nexport function startHttpProxyServer(\n config: AppConfig,\n logger: Logger = createLogger(config.log),\n): Promise<ProxyServer> {\n const directProxy = new DirectProxy(config.server.connectTimeoutMs);\n const runtimeState: RuntimeState = {\n mode: config.mode,\n globalProxy: undefined,\n groupSelections: new Map<string, string>(),\n };\n const context: HandlerContext = {\n config,\n upstreams: createUpstreamMap(config),\n directProxy,\n logger,\n runtimeState,\n };\n\n const server = createServer((socket): void => {\n handleClientConnection(socket, context);\n });\n\n return new Promise<ProxyServer>(\n (\n resolve: (proxyServer: ProxyServer) => void,\n reject: (error: Error) => void,\n ): void => {\n const onError = (error: Error): void => {\n server.removeListener(\"listening\", onListening);\n reject(error);\n };\n\n const onListening = (): void => {\n server.removeListener(\"error\", onError);\n resolve(new NodeProxyServer(server, runtimeState));\n };\n\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(config.server.port, config.server.host);\n },\n );\n}\n\nclass NodeProxyServer implements ProxyServer {\n public constructor(\n private readonly server: Server,\n private readonly runtimeState: RuntimeState,\n ) {}\n\n public close(): Promise<void> {\n return new Promise<void>(\n (resolve: () => void, reject: (error: Error) => void): void => {\n this.server.close((error?: Error): void => {\n if (error !== undefined) {\n reject(error);\n return;\n }\n resolve();\n });\n },\n );\n }\n\n public setMode(mode: AppConfig[\"mode\"]): void {\n this.runtimeState.mode = mode;\n }\n\n public setGlobalProxy(proxy: string | undefined): void {\n this.runtimeState.globalProxy = proxy;\n }\n\n public selectGroup(group: string, proxy: string): void {\n this.runtimeState.groupSelections.set(group, proxy);\n }\n\n public unsetGroup(group: string): void {\n this.runtimeState.groupSelections.delete(group);\n }\n\n public getSnapshot(): RuntimeSnapshot {\n return {\n mode: this.runtimeState.mode,\n globalProxy: this.runtimeState.globalProxy,\n groupSelections: Object.fromEntries(\n this.runtimeState.groupSelections,\n ),\n };\n }\n}\n\nfunction createUpstreamMap(\n config: AppConfig,\n): ReadonlyMap<string, UpstreamProxy> {\n const upstreams = new Map<string, UpstreamProxy>();\n for (const proxy of config.proxies) {\n upstreams.set(\n proxy.name,\n createProxy(proxy, config.server.connectTimeoutMs),\n );\n }\n return upstreams;\n}\n\nfunction createProxy(\n proxy: ProxyConfig,\n connectTimeoutMs: number,\n): UpstreamProxy {\n return createUpstreamProxy(proxy, connectTimeoutMs);\n}\n","import type { AppConfig } from \"../config/models.js\";\nimport type { ProxyDaemonState } from \"./daemon-state.js\";\nimport { writeProxyDaemonState } from \"./daemon-state.js\";\nimport { startControlServer } from \"./control.js\";\nimport type { ControlServer } from \"./control.js\";\nimport {\n findProfileStateEntry,\n getProfileStateKey,\n loadLynxStateConfig,\n} from \"../config/user-config.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport { createLogger } from \"../logging/logger.js\";\nimport type { ProxyServer } from \"../server/http-server.js\";\nimport { startHttpProxyServer } from \"../server/http-server.js\";\n\nexport interface ForegroundProxyOptions {\n daemonState?: ProxyDaemonState;\n}\n\nexport async function startForegroundProxy(\n config: AppConfig,\n profilePath?: string,\n options: ForegroundProxyOptions = {},\n): Promise<void> {\n const logger = createLogger(config.log);\n const server = await startHttpProxyServer(config, logger);\n\n // Initialize runtime state from state.json if profilePath is provided\n if (profilePath !== undefined) {\n const profileName = getProfileStateKey(profilePath);\n const state = loadLynxStateConfig();\n const stateEntry = findProfileStateEntry(state, profileName);\n if (stateEntry?.mode !== undefined) {\n server.setMode(stateEntry.mode);\n }\n for (const selection of stateEntry?.selected ?? []) {\n if (selection.name === \"GLOBAL\") {\n server.setGlobalProxy(selection.now);\n } else {\n server.selectGroup(selection.name, selection.now);\n }\n }\n }\n\n logger.info(\n `LynxProxy listening on http://${config.server.host}:${config.server.port}`,\n );\n\n // 启动本机控制通道;非 Unix 平台或启动失败时降级(实时切换不可用)\n let controlServer: ControlServer | undefined;\n try {\n controlServer = await startControlServer(server, config);\n if (controlServer === undefined) {\n logger.warn(\n \"Control socket unavailable on this platform; live switching disabled.\",\n );\n }\n } catch (error) {\n logger.warn(\n `Failed to start control socket: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n if (options.daemonState !== undefined) {\n writeProxyDaemonState(options.daemonState);\n }\n installShutdownHandler(server, controlServer, logger);\n}\n\nfunction installShutdownHandler(\n server: ProxyServer,\n controlServer: ControlServer | undefined,\n logger: Logger,\n): void {\n let closing = false;\n const close = (signal: NodeJS.Signals): void => {\n if (closing) {\n return;\n }\n closing = true;\n logger.info(`received ${signal}, shutting down`);\n const shutdown = Promise.all([\n server.close(),\n controlServer?.close() ?? Promise.resolve(),\n ]);\n void shutdown.then(\n (): void => {\n process.exitCode = 0;\n },\n (error: unknown): void => {\n logger.error(\n error instanceof Error ? error.message : String(error),\n );\n process.exitCode = 1;\n },\n );\n };\n\n process.once(\"SIGINT\", close);\n process.once(\"SIGTERM\", close);\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, openSync, readFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { loadLynxUserConfig, loadDefaultConfigWithPath } from \"../config/user-config.js\";\nimport { startForegroundProxy } from \"../runtime/proxy-runner.js\";\nimport type { ProxyDaemonState } from \"../runtime/daemon-state.js\";\nimport {\n getProxyDaemonLogPath,\n isProcessRunning,\n loadProxyDaemonState,\n removeProxyDaemonState,\n} from \"../runtime/daemon-state.js\";\nimport { isControlSocketReady } from \"../runtime/control.js\";\n\nconst STOP_TIMEOUT_MS = 5_000;\n\nexport async function runProxyCommand(args: readonly string[]): Promise<void> {\n const [command, ...rest] = args;\n if (command === undefined || command === \"--help\" || command === \"-h\") {\n console.log(createProxyHelpText());\n return;\n }\n\n if (command === \"status\") {\n ensureNoArgs(command, rest);\n await showStatus();\n return;\n }\n\n if (command === \"start\") {\n ensureNoArgs(command, rest);\n startDaemon();\n return;\n }\n\n if (command === \"run-daemon\") {\n ensureNoArgs(command, rest);\n await runDaemonForeground();\n return;\n }\n\n if (command === \"stop\") {\n ensureNoArgs(command, rest);\n await stopDaemon();\n return;\n }\n\n if (command === \"restart\") {\n ensureNoArgs(command, rest);\n await restartDaemon();\n return;\n }\n\n if (command === \"reload\") {\n ensureNoArgs(command, rest);\n console.log(\"lynx proxy reload is not implemented yet. Use `lynx proxy restart` to apply configuration changes.\");\n return;\n }\n\n if (command === \"logs\") {\n ensureNoArgs(command, rest);\n showLogs();\n return;\n }\n\n throw new Error(`Unknown proxy command: ${command}`);\n}\n\nasync function showStatus(): Promise<void> {\n const state = readStateForStatus();\n if (state === undefined) {\n console.log(\"LynxProxy daemon is not running.\");\n return;\n }\n if (!isProcessRunning(state.pid)) {\n removeProxyDaemonState();\n console.log(\"LynxProxy daemon is not running. Removed stale daemon state.\");\n return;\n }\n\n console.log(\"LynxProxy daemon is running.\");\n console.log(`pid: ${state.pid}`);\n console.log(`listen: ${state.host}:${state.port}`);\n console.log(`profile: ${state.profile ?? \"(unknown)\"}`);\n if (state.profilePath !== undefined) {\n console.log(`profile path: ${state.profilePath}`);\n }\n console.log(`started at: ${state.startedAt}`);\n console.log(`log file: ${state.logFile}`);\n const controlReady = await isControlSocketReady();\n console.log(\n `control socket: ${controlReady ? \"ready (live switching available)\" : \"unavailable\"}`,\n );\n}\n\nfunction startDaemon(): void {\n const existing = readStateForStatus();\n if (existing !== undefined) {\n if (isProcessRunning(existing.pid)) {\n console.log(`LynxProxy daemon is already running with PID ${existing.pid}.`);\n return;\n }\n removeProxyDaemonState();\n }\n\n const { config, profilePath } = loadDefaultConfigWithPath();\n const profile = loadLynxUserConfig().profile;\n const logFile = getProxyDaemonLogPath();\n mkdirSync(dirname(logFile), { recursive: true });\n const out = openSync(logFile, \"a\");\n const child = spawn(process.execPath, [process.argv[1]!, \"proxy\", \"run-daemon\"], {\n detached: true,\n stdio: [\"ignore\", out, out],\n env: process.env,\n });\n child.unref();\n\n console.log(`LynxProxy daemon starting with PID ${child.pid}.`);\n console.log(`listen: ${config.server.host}:${config.server.port}`);\n console.log(`profile: ${profile}`);\n if (profilePath !== undefined) {\n console.log(`profile path: ${profilePath}`);\n }\n console.log(`log file: ${logFile}`);\n}\n\nasync function runDaemonForeground(): Promise<void> {\n const { config, profilePath } = loadDefaultConfigWithPath();\n const profile = loadLynxUserConfig().profile;\n const daemonState: ProxyDaemonState = {\n version: 1,\n pid: process.pid,\n profile,\n host: config.server.host,\n port: config.server.port,\n startedAt: new Date().toISOString(),\n logFile: getProxyDaemonLogPath(),\n };\n if (profilePath !== undefined) {\n daemonState.profilePath = profilePath;\n }\n await startForegroundProxy(config, profilePath, { daemonState });\n}\n\nasync function stopDaemon(): Promise<void> {\n const state = readStateForStatus();\n if (state === undefined) {\n console.log(\"LynxProxy daemon is not running.\");\n return;\n }\n if (!isProcessRunning(state.pid)) {\n removeProxyDaemonState();\n console.log(\"LynxProxy daemon is not running. Removed stale daemon state.\");\n return;\n }\n\n process.kill(state.pid, \"SIGTERM\");\n const stopped = await waitForExit(state.pid, STOP_TIMEOUT_MS);\n if (!stopped) {\n throw new Error(`Timed out waiting for LynxProxy daemon PID ${state.pid} to stop`);\n }\n removeProxyDaemonState();\n console.log(`Stopped LynxProxy daemon PID ${state.pid}.`);\n}\n\nasync function restartDaemon(): Promise<void> {\n const state = readStateForStatus();\n if (state !== undefined && isProcessRunning(state.pid)) {\n await stopDaemon();\n } else if (state !== undefined) {\n removeProxyDaemonState();\n }\n startDaemon();\n}\n\nfunction showLogs(): void {\n const state = readStateForStatus();\n const logFile = state?.logFile ?? getProxyDaemonLogPath();\n if (!existsSync(logFile)) {\n console.log(`No proxy daemon log file found: ${logFile}`);\n return;\n }\n console.log(readFileSync(logFile, \"utf8\"));\n}\n\nfunction readStateForStatus(): ProxyDaemonState | undefined {\n try {\n return loadProxyDaemonState();\n } catch (error) {\n removeProxyDaemonState();\n throw new Error(\n `Invalid proxy daemon state removed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n return new Promise((resolve): void => {\n const started = Date.now();\n const timer = setInterval((): void => {\n if (!isProcessRunning(pid)) {\n clearInterval(timer);\n resolve(true);\n return;\n }\n if (Date.now() - started >= timeoutMs) {\n clearInterval(timer);\n resolve(false);\n }\n }, 100);\n });\n}\n\nfunction ensureNoArgs(command: string, args: readonly string[]): void {\n if (args.length > 0) {\n throw new Error(`Unknown proxy ${command} argument: ${String(args[0])}`);\n }\n}\n\nfunction createProxyHelpText(): string {\n return `Usage: lynx proxy <command> [options]\n\nCommands:\n start Start proxy service in background using the active profile\n stop Stop background proxy service\n restart Restart background proxy service\n status Show background proxy status\n reload Ask user to restart; hot reload is not implemented yet\n logs Show proxy daemon logs`;\n}\n","import { runConfigCommand } from \"./config-cli.js\";\nimport { runGroupsCommand } from \"./groups-cli.js\";\nimport { runProxyCommand } from \"./proxy-cli.js\";\n\nexport const CLI_COMMANDS: Set<string> = new Set([\"config\", \"proxy\", \"groups\"]);\n\nexport function isCliCommand(command: string | undefined): boolean {\n return command !== undefined && CLI_COMMANDS.has(command);\n}\n\nexport async function runCliCommand(args: readonly string[]): Promise<void> {\n const [command, ...rest] = args;\n if (command === \"config\") {\n await runConfigCommand(rest);\n return;\n }\n if (command === \"proxy\") {\n await runProxyCommand(rest);\n return;\n }\n if (command === \"groups\") {\n await runGroupsCommand(rest);\n return;\n }\n throw new Error(`Unknown command: ${String(command)}`);\n}\n\nexport function createCliHelpText(): string {\n return `Commands:\n config Manage user config and profile files\n proxy Control proxy service state\n groups Manage proxy-group selections\n\nRun lynx <command> --help for command-specific help.`;\n}\n","#!/usr/bin/env node\n\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { createCliHelpText, isCliCommand, runCliCommand } from \"./cli/index.js\";\nimport { ConfigError } from \"./config/models.js\";\nimport { loadDefaultConfigWithPath } from \"./config/user-config.js\";\nimport { createDefaultLogger } from \"./logging/logger.js\";\nimport { startForegroundProxy } from \"./runtime/proxy-runner.js\";\n\nconst VERSION = \"1.0.0\";\n\nexport interface CliOptions {\n commandArgs?: readonly string[];\n help: boolean;\n version: boolean;\n}\n\nexport function parseCliArgs(argv: readonly string[]): CliOptions {\n const options: CliOptions = {\n help: false,\n version: false,\n };\n const args = argv.slice(2);\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === undefined) {\n continue;\n }\n\n if (index === 0 && isCliCommand(arg)) {\n options.commandArgs = args.slice(index);\n break;\n }\n\n if (arg === \"--help\" || arg === \"-h\") {\n options.help = true;\n } else if (arg === \"--version\" || arg === \"-v\") {\n options.version = true;\n } else {\n throw new Error(`Unknown argument: ${arg}`);\n }\n }\n\n return options;\n}\n\nexport async function main(\n argv: readonly string[] = process.argv,\n): Promise<void> {\n const options = parseCliArgs(argv);\n if (options.commandArgs !== undefined) {\n await runCliCommand(options.commandArgs);\n return;\n }\n\n if (options.help) {\n console.log(createHelpText());\n return;\n }\n\n if (options.version) {\n console.log(VERSION);\n return;\n }\n\n const { config, profilePath } = loadDefaultConfigWithPath();\n await startForegroundProxy(config, profilePath);\n}\n\nfunction createHelpText(): string {\n return `Usage: lynx [options]\n lynx <command> [options]\n\nOptions:\n -h, --help Show help\n -v, --version Show version\n\n${createCliHelpText()}\n\nLynxProxy reads ~/.config/lynx-proxy/user.json and loads the selected profile\nfrom ~/.config/lynx-proxy/profile/. Add a profile with 'lynx config add <name>\n--file <path>' (or --url / --template), then select it with 'lynx config use\n<profile>'. If user.json does not exist and ./config.toml is not present,\nLynxProxy creates a default user.json with profile \"default\".`;\n}\n\nif (\n process.argv[1] !== undefined &&\n realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)\n) {\n void main(process.argv).catch((error: unknown): void => {\n const logger = createDefaultLogger();\n if (error instanceof ConfigError) {\n logger.error(`Config error: ${error.message}`);\n } else {\n logger.error(error instanceof Error ? error.message : String(error));\n }\n process.exitCode = 1;\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAa,cAAb,cAAiC,MAAM;CACnC,YAAmB,SAAiB;EAChC,MAAM,OA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