hermes-yaoyao.mjs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env node
  2. import { execFileSync } from 'node:child_process'
  3. import { existsSync } 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 { fileURLToPath } from 'node:url'
  8. const label = 'com.samien.hermes-yaoyao'
  9. const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
  10. const uid = process.getuid?.() ?? 501
  11. const domain = `gui/${uid}`
  12. const launchAgents = join(homedir(), 'Library', 'LaunchAgents')
  13. const plistPath = join(launchAgents, `${label}.plist`)
  14. const dataHome = process.env.HERMES_YAOYAO_HOME || join(homedir(), '.hermes-yaoyao')
  15. const logDir = join(homedir(), 'Library', 'Logs')
  16. const serverEntry = join(projectRoot, 'dist-server', 'server', 'index.js')
  17. function run(command, args, options = {}) {
  18. return execFileSync(command, args, { encoding: 'utf8', stdio: options.inherit ? 'inherit' : 'pipe' })
  19. }
  20. function escapeXml(value) {
  21. return String(value)
  22. .replaceAll('&', '&')
  23. .replaceAll('<', '&lt;')
  24. .replaceAll('>', '&gt;')
  25. .replaceAll('"', '&quot;')
  26. .replaceAll("'", '&apos;')
  27. }
  28. function environment() {
  29. const allowed = [
  30. 'HERMES_YAOYAO_HOST',
  31. 'HERMES_YAOYAO_PORT',
  32. 'HERMES_YAOYAO_UPSTREAM',
  33. 'HERMES_YAOYAO_ALLOWED_HOSTS',
  34. 'HERMES_YAOYAO_HOME',
  35. 'HERMES_YAOYAO_TLS_CERT',
  36. 'HERMES_YAOYAO_TLS_KEY',
  37. 'HERMES_YAOYAO_ALLOW_INSECURE_LAN',
  38. 'HERMES_YAOYAO_SUPERVISE_DASHBOARD',
  39. ]
  40. return Object.fromEntries(allowed.flatMap(key => process.env[key] ? [[key, process.env[key]]] : []))
  41. }
  42. export function launchAgentPlist() {
  43. const node = process.execPath
  44. const envEntries = {
  45. PATH: `${dirname(node)}:${join(homedir(), '.local', 'bin')}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
  46. NODE_ENV: 'production',
  47. HERMES_YAOYAO_HOME: dataHome,
  48. HERMES_YAOYAO_HOST: '127.0.0.1',
  49. HERMES_YAOYAO_PORT: '8800',
  50. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:9119',
  51. HERMES_YAOYAO_SUPERVISE_DASHBOARD: '1',
  52. ...environment(),
  53. }
  54. const envXml = Object.entries(envEntries).map(([key, value]) => (
  55. ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`
  56. )).join('\n')
  57. const logPath = join(logDir, 'hermes-yaoyao.log')
  58. return `<?xml version="1.0" encoding="UTF-8"?>
  59. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  60. <plist version="1.0">
  61. <dict>
  62. <key>Label</key><string>${label}</string>
  63. <key>ProgramArguments</key>
  64. <array><string>${escapeXml(node)}</string><string>${escapeXml(serverEntry)}</string></array>
  65. <key>WorkingDirectory</key><string>${escapeXml(projectRoot)}</string>
  66. <key>EnvironmentVariables</key>
  67. <dict>
  68. ${envXml}
  69. </dict>
  70. <key>RunAtLoad</key><true/>
  71. <key>KeepAlive</key><true/>
  72. <key>ThrottleInterval</key><integer>10</integer>
  73. <key>ProcessType</key><string>Interactive</string>
  74. <key>Umask</key><integer>63</integer>
  75. <key>StandardOutPath</key><string>${escapeXml(logPath)}</string>
  76. <key>StandardErrorPath</key><string>${escapeXml(logPath)}</string>
  77. </dict>
  78. </plist>
  79. `
  80. }
  81. function loaded() {
  82. try {
  83. run('launchctl', ['print', `${domain}/${label}`])
  84. return true
  85. } catch {
  86. return false
  87. }
  88. }
  89. async function install() {
  90. if (!existsSync(serverEntry)) {
  91. throw new Error('未找到生产构建,请先运行 npm run build')
  92. }
  93. await mkdir(launchAgents, { recursive: true })
  94. await mkdir(dataHome, { recursive: true, mode: 0o700 })
  95. await mkdir(logDir, { recursive: true })
  96. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  97. await writeFile(plistPath, launchAgentPlist(), { mode: 0o600 })
  98. await chmod(plistPath, 0o600)
  99. run('plutil', ['-lint', plistPath], { inherit: true })
  100. run('launchctl', ['bootstrap', domain, plistPath])
  101. process.stdout.write(`已安装并启动 ${label}\n`)
  102. }
  103. function start() {
  104. if (!existsSync(plistPath)) throw new Error('服务尚未安装')
  105. if (!loaded()) run('launchctl', ['bootstrap', domain, plistPath])
  106. else run('launchctl', ['kickstart', '-k', `${domain}/${label}`])
  107. process.stdout.write(`已启动 ${label}\n`)
  108. }
  109. function stop() {
  110. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  111. process.stdout.write(`已停止 ${label};Hermes 9119 未被操作\n`)
  112. }
  113. async function uninstall() {
  114. stop()
  115. if (existsSync(plistPath)) await unlink(plistPath)
  116. process.stdout.write(`已卸载 ${label};运行数据保留在 ${dataHome}\n`)
  117. }
  118. function status() {
  119. if (!loaded()) {
  120. process.stdout.write(`${label}: stopped\n`)
  121. process.exitCode = 3
  122. return
  123. }
  124. process.stdout.write(run('launchctl', ['print', `${domain}/${label}`]))
  125. }
  126. async function pruneUploads(args) {
  127. const index = args.indexOf('--older-than')
  128. const days = index >= 0 ? Number(args[index + 1]) : 30
  129. if (!Number.isFinite(days) || days < 1) throw new Error('--older-than 必须是大于 0 的天数')
  130. if (!args.includes('--yes')) {
  131. throw new Error('这是显式清理操作,请增加 --yes')
  132. }
  133. const root = join(dataHome, 'uploads', 'pending')
  134. if (!existsSync(root)) return
  135. const cutoff = Date.now() - days * 86_400_000
  136. let removed = 0
  137. for (const entry of await readdir(root)) {
  138. const target = join(root, entry)
  139. const info = await stat(target)
  140. if (info.isFile() && info.mtimeMs < cutoff) {
  141. await unlink(target)
  142. removed += 1
  143. }
  144. }
  145. process.stdout.write(`已清理 ${removed} 个未提交上传文件\n`)
  146. }
  147. async function main() {
  148. const [, , group, command, ...args] = process.argv
  149. if (group === 'service') {
  150. if (command === 'install') return install()
  151. if (command === 'start') return start()
  152. if (command === 'stop') return stop()
  153. if (command === 'status') return status()
  154. if (command === 'uninstall') return uninstall()
  155. }
  156. if (group === 'uploads' && command === 'prune') return pruneUploads(args)
  157. 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`)
  158. }
  159. if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  160. main().catch(error => {
  161. process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
  162. process.exitCode = 1
  163. })
  164. }