hermes-yaoyao.mjs 6.8 KB

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