config.ts 8.2 KB

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