hermes-yaoyao.mjs 6.9 KB

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