hermes-yaoyao.mjs 6.0 KB

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