config.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { isIP } from 'node:net'
  2. import { homedir } from 'node:os'
  3. import { basename, resolve } from 'node:path'
  4. import { readFileSync } from 'node:fs'
  5. import type { APNsEnvironment } from './apns.js'
  6. import { loadAPNsConfiguration, type APNsConfigurationSnapshot } from './apnsConfiguration.js'
  7. import { loadFCMConfiguration, type FCMConfigurationSnapshot } from './fcmConfiguration.js'
  8. import {
  9. loadAllowedHostsConfiguration,
  10. type AllowedHostsConfigurationSnapshot,
  11. } from './allowedHostsConfiguration.js'
  12. export { DEFAULT_APNS_TOPIC } from './apnsConfiguration.js'
  13. export interface APNsProviderConfig {
  14. keyFile: string
  15. keyId: string
  16. teamId: string
  17. topic: string
  18. environments?: APNsEnvironment[]
  19. }
  20. export interface FCMProviderConfig {
  21. serviceAccountFile: string
  22. projectId: string
  23. packageName: string
  24. }
  25. export interface ServerConfig {
  26. host: string
  27. port: number
  28. upstream: URL
  29. allowedHosts: ReadonlySet<string>
  30. home: string
  31. mediaRoot: string
  32. attachmentsRoot: string
  33. imagesRoot: string
  34. mediaOwner: string
  35. tlsCert?: string
  36. tlsKey?: string
  37. allowInsecureLan: boolean
  38. insecureLan: boolean
  39. production: boolean
  40. superviseDashboard?: boolean
  41. yaoyaoPluginSource?: string
  42. releaseSource?: string
  43. releaseRoot?: string
  44. allowRemoteUpdate?: boolean
  45. upstreamUsername?: string
  46. upstreamPassword?: string
  47. apns?: APNsProviderConfig
  48. apnsConfigurationError?: string
  49. apnsSettings?: APNsConfigurationSnapshot
  50. fcm?: FCMProviderConfig
  51. fcmConfigurationError?: string
  52. fcmSettings?: FCMConfigurationSnapshot
  53. allowedHostsSettings?: AllowedHostsConfigurationSnapshot
  54. }
  55. export const DEFAULT_YAOYAO_PLUGIN_SOURCE = 'https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao'
  56. export const DEFAULT_YAOYAO_RELEASE_SOURCE = 'https://git.samien.cn/samien/hermes-yaoyao.git'
  57. function flag(value: string | undefined): boolean {
  58. return value === '1' || value?.toLowerCase() === 'true'
  59. }
  60. function parsePort(value: string | undefined): number {
  61. const port = Number(value ?? '8800')
  62. if (!Number.isInteger(port) || port < 1 || port > 65_535) {
  63. throw new Error('HERMES_YAOYAO_PORT must be an integer between 1 and 65535')
  64. }
  65. return port
  66. }
  67. function parseUpstream(value: string | undefined): URL {
  68. const upstream = new URL(value ?? 'http://127.0.0.1:9119')
  69. if (!['http:', 'https:'].includes(upstream.protocol)) {
  70. throw new Error('HERMES_YAOYAO_UPSTREAM must use http or https')
  71. }
  72. if (upstream.username || upstream.password || upstream.search || upstream.hash) {
  73. throw new Error('HERMES_YAOYAO_UPSTREAM must not contain credentials, query, or fragment')
  74. }
  75. upstream.pathname = upstream.pathname.replace(/\/+$/, '') || '/'
  76. return upstream
  77. }
  78. function parsePluginSource(value: string | undefined): string {
  79. const source = value?.trim() || DEFAULT_YAOYAO_PLUGIN_SOURCE
  80. if (source.length > 2_048 || /[\u0000-\u001f\u007f]/.test(source)) {
  81. throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE is invalid')
  82. }
  83. if (source.startsWith('https://') || source.startsWith('http://')) {
  84. const url = new URL(source)
  85. if (url.username || url.password) {
  86. throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE must not contain credentials')
  87. }
  88. } else if (!source.startsWith('git@') && !source.startsWith('ssh://')) {
  89. throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE must be an HTTPS or SSH Git source')
  90. }
  91. return source
  92. }
  93. function parseReleaseSource(value: string | undefined): string {
  94. const source = value?.trim() || DEFAULT_YAOYAO_RELEASE_SOURCE
  95. if (source.length > 2_048 || /[\u0000-\u001f\u007f]/.test(source)) {
  96. throw new Error('HERMES_YAOYAO_RELEASE_SOURCE is invalid')
  97. }
  98. if (source.startsWith('https://')) {
  99. const url = new URL(source)
  100. if (url.username || url.password || url.search || url.hash) {
  101. throw new Error('HERMES_YAOYAO_RELEASE_SOURCE must not contain credentials, query, or fragment')
  102. }
  103. } else if (!source.startsWith('git@') && !source.startsWith('ssh://')) {
  104. throw new Error('HERMES_YAOYAO_RELEASE_SOURCE must be an HTTPS or SSH Git source')
  105. }
  106. return source
  107. }
  108. function normalizeConfiguredHost(raw: string): string {
  109. const value = raw.trim().toLowerCase()
  110. if (!value) return ''
  111. if (value.startsWith('[') && value.endsWith(']')) return value.slice(1, -1)
  112. return value.replace(/\.$/, '')
  113. }
  114. export function isLoopbackHost(host: string): boolean {
  115. const normalized = normalizeConfiguredHost(host)
  116. if (normalized === 'localhost' || normalized === '::1') return true
  117. if (isIP(normalized) === 4) return normalized.split('.')[0] === '127'
  118. return false
  119. }
  120. export function isPrivateHost(host: string): boolean {
  121. const normalized = normalizeConfiguredHost(host)
  122. if (isLoopbackHost(normalized)) return true
  123. if (isIP(normalized) === 4) {
  124. const parts = normalized.split('.').map(Number)
  125. return parts[0] === 10
  126. || (parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127)
  127. || (parts[0] === 169 && parts[1] === 254)
  128. || (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31)
  129. || (parts[0] === 192 && parts[1] === 168)
  130. }
  131. if (isIP(normalized) === 6) {
  132. return normalized.startsWith('fc')
  133. || normalized.startsWith('fd')
  134. || /^fe[89ab]/.test(normalized)
  135. }
  136. return false
  137. }
  138. export function isLoopbackUpstream(upstream: URL): boolean {
  139. return isLoopbackHost(upstream.hostname)
  140. }
  141. export function loadServerConfig(
  142. env: NodeJS.ProcessEnv = process.env,
  143. ): ServerConfig {
  144. const host = env.HERMES_YAOYAO_HOST?.trim() || '127.0.0.1'
  145. const port = parsePort(env.HERMES_YAOYAO_PORT)
  146. const upstream = parseUpstream(env.HERMES_YAOYAO_UPSTREAM)
  147. const home = resolve(env.HERMES_YAOYAO_HOME?.trim() || `${homedir()}/.hermes-yaoyao`)
  148. const mediaRoot = resolve(env.HERMES_YAOYAO_MEDIA_ROOT?.trim() || `${homedir()}/Agents`)
  149. const attachmentsRoot = resolve(`${homedir()}/.hermes/attachments`)
  150. const imagesRoot = resolve(`${homedir()}/.hermes/images`)
  151. const tlsCert = env.HERMES_YAOYAO_TLS_CERT?.trim() || undefined
  152. const tlsKey = env.HERMES_YAOYAO_TLS_KEY?.trim() || undefined
  153. if (Boolean(tlsCert) !== Boolean(tlsKey)) {
  154. throw new Error('HERMES_YAOYAO_TLS_CERT and HERMES_YAOYAO_TLS_KEY must be set together')
  155. }
  156. const allowInsecureLan = flag(env.HERMES_YAOYAO_ALLOW_INSECURE_LAN)
  157. const production = env.NODE_ENV === 'production'
  158. const superviseDashboard = flag(env.HERMES_YAOYAO_SUPERVISE_DASHBOARD)
  159. const yaoyaoPluginSource = parsePluginSource(env.HERMES_YAOYAO_PLUGIN_SOURCE)
  160. const releaseSource = parseReleaseSource(env.HERMES_YAOYAO_RELEASE_SOURCE)
  161. const releaseRoot = resolve(env.HERMES_YAOYAO_RELEASE_ROOT?.trim() || `${homedir()}/.local/share/hermes-yaoyao`)
  162. const allowRemoteUpdate = flag(env.HERMES_YAOYAO_ALLOW_REMOTE_UPDATE)
  163. const upstreamUsername = env.HERMES_YAOYAO_UPSTREAM_USERNAME?.trim() || undefined
  164. const upstreamPasswordFile = env.HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE?.trim()
  165. if (env.HERMES_YAOYAO_UPSTREAM_PASSWORD && upstreamPasswordFile) {
  166. throw new Error('Set only one of HERMES_YAOYAO_UPSTREAM_PASSWORD or HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE')
  167. }
  168. const upstreamPassword = env.HERMES_YAOYAO_UPSTREAM_PASSWORD
  169. || (upstreamPasswordFile ? readFileSync(resolve(upstreamPasswordFile), 'utf8').replace(/[\r\n]+$/, '') : undefined)
  170. const apnsSettings = loadAPNsConfiguration(home, env)
  171. const fcmSettings = loadFCMConfiguration(home, env)
  172. const insecureLan = !tlsCert && !isLoopbackHost(host)
  173. if (production && insecureLan && !allowInsecureLan) {
  174. throw new Error(
  175. 'Plain HTTP on a non-loopback host requires HERMES_YAOYAO_ALLOW_INSECURE_LAN=1',
  176. )
  177. }
  178. const allowedHostsSettings = loadAllowedHostsConfiguration(home, env)
  179. const allowedHosts = new Set(allowedHostsSettings.hosts)
  180. return {
  181. host,
  182. port,
  183. upstream,
  184. allowedHosts,
  185. allowedHostsSettings,
  186. home,
  187. mediaRoot,
  188. attachmentsRoot,
  189. imagesRoot,
  190. mediaOwner: basename(homedir()),
  191. tlsCert,
  192. tlsKey,
  193. allowInsecureLan,
  194. insecureLan,
  195. production,
  196. superviseDashboard,
  197. yaoyaoPluginSource,
  198. releaseSource,
  199. releaseRoot,
  200. allowRemoteUpdate,
  201. upstreamUsername,
  202. upstreamPassword,
  203. ...(apnsSettings.config ? { apns: apnsSettings.config } : {}),
  204. ...(apnsSettings.configurationError ? { apnsConfigurationError: apnsSettings.configurationError } : {}),
  205. apnsSettings,
  206. ...(fcmSettings.config ? { fcm: fcmSettings.config } : {}),
  207. ...(fcmSettings.configurationError ? { fcmConfigurationError: fcmSettings.configurationError } : {}),
  208. fcmSettings,
  209. }
  210. }