config.ts 7.5 KB

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