hermes-yaoyao.mjs 7.6 KB

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