hermes-yaoyao.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/env node
  2. import { execFileSync } from 'node:child_process'
  3. import { existsSync, realpathSync } from 'node:fs'
  4. import { chmod, mkdir, readdir, stat, unlink, writeFile } from 'node:fs/promises'
  5. import { homedir } from 'node:os'
  6. import { dirname, join, resolve } from 'node:path'
  7. import { setTimeout as delay } from 'node:timers/promises'
  8. import { fileURLToPath } from 'node:url'
  9. import { normalizeReleaseSource } from './lib/release-source.mjs'
  10. const label = 'com.samien.hermes-yaoyao'
  11. const sourceProjectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
  12. const serviceRoot = resolve(process.env.HERMES_YAOYAO_SERVICE_ROOT || sourceProjectRoot)
  13. const uid = process.getuid?.() ?? 501
  14. const domain = `gui/${uid}`
  15. const launchAgents = join(homedir(), 'Library', 'LaunchAgents')
  16. const plistPath = join(launchAgents, `${label}.plist`)
  17. const dataHome = process.env.HERMES_YAOYAO_HOME || join(homedir(), '.hermes-yaoyao')
  18. const logDir = join(homedir(), 'Library', 'Logs')
  19. const serverEntry = join(serviceRoot, 'dist-server', 'server', 'index.js')
  20. function run(command, args, options = {}) {
  21. return execFileSync(command, args, { encoding: 'utf8', stdio: options.inherit ? 'inherit' : 'pipe' })
  22. }
  23. function escapeXml(value) {
  24. return String(value)
  25. .replaceAll('&', '&')
  26. .replaceAll('<', '&lt;')
  27. .replaceAll('>', '&gt;')
  28. .replaceAll('"', '&quot;')
  29. .replaceAll("'", '&apos;')
  30. }
  31. function environment(env = process.env) {
  32. const allowed = [
  33. 'HERMES_YAOYAO_HOST',
  34. 'HERMES_YAOYAO_PORT',
  35. 'HERMES_YAOYAO_UPSTREAM',
  36. 'HERMES_YAOYAO_UPSTREAM_USERNAME',
  37. 'HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE',
  38. 'HERMES_YAOYAO_ALLOWED_HOSTS',
  39. 'HERMES_YAOYAO_HOME',
  40. 'HERMES_YAOYAO_TLS_CERT',
  41. 'HERMES_YAOYAO_TLS_KEY',
  42. 'HERMES_YAOYAO_ALLOW_INSECURE_LAN',
  43. 'HERMES_YAOYAO_SUPERVISE_DASHBOARD',
  44. 'HERMES_YAOYAO_CHAT_CACHE_MODE',
  45. 'HERMES_YAOYAO_RELEASE_SOURCE',
  46. 'HERMES_YAOYAO_RELEASE_ROOT',
  47. 'HERMES_YAOYAO_ALLOW_REMOTE_UPDATE',
  48. 'HERMES_YAOYAO_APNS_KEY_FILE',
  49. 'HERMES_YAOYAO_APNS_KEY_ID',
  50. 'HERMES_YAOYAO_APNS_TEAM_ID',
  51. 'HERMES_YAOYAO_APNS_TOPIC',
  52. 'HERMES_YAOYAO_FCM_SERVICE_ACCOUNT_FILE',
  53. 'HERMES_YAOYAO_FCM_PROJECT_ID',
  54. 'HERMES_YAOYAO_FCM_PACKAGE_NAME',
  55. 'HERMES_YAOYAO_SERVICE_ROOT',
  56. ]
  57. return { ...Object.fromEntries(allowed.flatMap(key => env[key] ? [[key, env[key]]] : [])),
  58. HERMES_YAOYAO_RELEASE_SOURCE: normalizeReleaseSource(env.HERMES_YAOYAO_RELEASE_SOURCE) }
  59. }
  60. export function launchAgentPlist(options = {}) {
  61. const plistServiceRoot = resolve(options.serviceRoot || serviceRoot)
  62. const plistServerEntry = join(plistServiceRoot, 'dist-server', 'server', 'index.js')
  63. const node = process.execPath
  64. const envEntries = {
  65. PATH: `${dirname(node)}:${join(homedir(), '.local', 'bin')}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
  66. NODE_ENV: 'production',
  67. HERMES_YAOYAO_HOME: dataHome,
  68. HERMES_YAOYAO_PORT: '15300',
  69. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:9119',
  70. HERMES_YAOYAO_SUPERVISE_DASHBOARD: '1',
  71. ...environment(options.environment),
  72. HERMES_YAOYAO_HOST: '0.0.0.0',
  73. HERMES_YAOYAO_ALLOW_INSECURE_LAN: '1',
  74. }
  75. const envXml = Object.entries(envEntries).map(([key, value]) => (
  76. ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`
  77. )).join('\n')
  78. const logPath = join(logDir, 'hermes-yaoyao.log')
  79. return `<?xml version="1.0" encoding="UTF-8"?>
  80. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  81. <plist version="1.0">
  82. <dict>
  83. <key>Label</key><string>${label}</string>
  84. <key>ProgramArguments</key>
  85. <array><string>${escapeXml(node)}</string><string>${escapeXml(plistServerEntry)}</string></array>
  86. <key>WorkingDirectory</key><string>${escapeXml(plistServiceRoot)}</string>
  87. <key>EnvironmentVariables</key>
  88. <dict>
  89. ${envXml}
  90. </dict>
  91. <key>RunAtLoad</key><true/>
  92. <key>KeepAlive</key><true/>
  93. <key>ThrottleInterval</key><integer>10</integer>
  94. <key>ProcessType</key><string>Interactive</string>
  95. <key>Umask</key><integer>63</integer>
  96. <key>StandardOutPath</key><string>${escapeXml(logPath)}</string>
  97. <key>StandardErrorPath</key><string>${escapeXml(logPath)}</string>
  98. </dict>
  99. </plist>
  100. `
  101. }
  102. function loaded() {
  103. try {
  104. run('launchctl', ['print', `${domain}/${label}`])
  105. return true
  106. } catch {
  107. return false
  108. }
  109. }
  110. function launchctlBootstrapRetryable(error) {
  111. const detail = [error?.message, error?.stdout, error?.stderr]
  112. .filter(Boolean)
  113. .map(String)
  114. .join('\n')
  115. return /Bootstrap failed:\s*5:\s*Input\/output error/i.test(detail)
  116. }
  117. export async function bootstrapLaunchAgent(
  118. runCommand = run,
  119. wait = delay,
  120. options = {},
  121. ) {
  122. const timeoutMs = options.timeoutMs ?? 20_000
  123. const initialDelayMs = options.initialDelayMs ?? 250
  124. const maximumDelayMs = options.maximumDelayMs ?? 2_000
  125. const now = options.now ?? Date.now
  126. const deadline = now() + timeoutMs
  127. let retryDelayMs = initialDelayMs
  128. for (;;) {
  129. try {
  130. return runCommand('launchctl', ['bootstrap', domain, plistPath])
  131. } catch (error) {
  132. if (!launchctlBootstrapRetryable(error)) throw error
  133. const remainingMs = deadline - now()
  134. if (remainingMs <= 0) throw error
  135. const waitMs = Math.min(retryDelayMs, maximumDelayMs, remainingMs)
  136. await wait(waitMs)
  137. retryDelayMs = Math.min(retryDelayMs * 2, maximumDelayMs)
  138. }
  139. }
  140. }
  141. async function install() {
  142. if (!existsSync(serverEntry)) {
  143. throw new Error('未找到生产构建,请先运行 npm run build')
  144. }
  145. await mkdir(launchAgents, { recursive: true })
  146. await mkdir(dataHome, { recursive: true, mode: 0o700 })
  147. await mkdir(logDir, { recursive: true })
  148. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  149. await writeFile(plistPath, launchAgentPlist(), { mode: 0o600 })
  150. await chmod(plistPath, 0o600)
  151. run('plutil', ['-lint', plistPath], { inherit: true })
  152. await bootstrapLaunchAgent()
  153. process.stdout.write(`已安装并启动 ${label}\n`)
  154. }
  155. async function start() {
  156. if (!existsSync(plistPath)) throw new Error('服务尚未安装')
  157. if (!loaded()) await bootstrapLaunchAgent()
  158. else run('launchctl', ['kickstart', '-k', `${domain}/${label}`])
  159. process.stdout.write(`已启动 ${label}\n`)
  160. }
  161. function stop() {
  162. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  163. process.stdout.write(`已停止 ${label};Hermes 9119 未被操作\n`)
  164. }
  165. async function uninstall() {
  166. stop()
  167. if (existsSync(plistPath)) await unlink(plistPath)
  168. process.stdout.write(`已卸载 ${label};运行数据保留在 ${dataHome}\n`)
  169. }
  170. function status() {
  171. if (!loaded()) {
  172. process.stdout.write(`${label}: stopped\n`)
  173. process.exitCode = 3
  174. return
  175. }
  176. process.stdout.write(run('launchctl', ['print', `${domain}/${label}`]))
  177. }
  178. async function pruneUploads(args) {
  179. const index = args.indexOf('--older-than')
  180. const days = index >= 0 ? Number(args[index + 1]) : 30
  181. if (!Number.isFinite(days) || days < 1) throw new Error('--older-than 必须是大于 0 的天数')
  182. if (!args.includes('--yes')) {
  183. throw new Error('这是显式清理操作,请增加 --yes')
  184. }
  185. const root = join(dataHome, 'uploads', 'pending')
  186. if (!existsSync(root)) return
  187. const cutoff = Date.now() - days * 86_400_000
  188. let removed = 0
  189. for (const entry of await readdir(root)) {
  190. const target = join(root, entry)
  191. const info = await stat(target)
  192. if (info.isFile() && info.mtimeMs < cutoff) {
  193. await unlink(target)
  194. removed += 1
  195. }
  196. }
  197. process.stdout.write(`已清理 ${removed} 个未提交上传文件\n`)
  198. }
  199. async function main() {
  200. const [, , group, command, ...args] = process.argv
  201. if (group === 'service') {
  202. if (command === 'install') return install()
  203. if (command === 'start') return start()
  204. if (command === 'stop') return stop()
  205. if (command === 'status') return status()
  206. if (command === 'uninstall') return uninstall()
  207. }
  208. if (group === 'uploads' && command === 'prune') return pruneUploads(args)
  209. process.stdout.write(`夭夭 Web\n\n用法:\n hermes-yaoyao service install|start|stop|status|uninstall\n hermes-yaoyao uploads prune --older-than 30 --yes\n`)
  210. }
  211. export function isMainModule(entry = process.argv[1]) {
  212. if (!entry) return false
  213. try {
  214. return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))
  215. } catch {
  216. return resolve(entry) === fileURLToPath(import.meta.url)
  217. }
  218. }
  219. if (isMainModule()) {
  220. main().catch(error => {
  221. process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
  222. process.exitCode = 1
  223. })
  224. }