hermes-yaoyao.mjs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. options = {},
  110. ) {
  111. const timeoutMs = options.timeoutMs ?? 20_000
  112. const initialDelayMs = options.initialDelayMs ?? 250
  113. const maximumDelayMs = options.maximumDelayMs ?? 2_000
  114. const now = options.now ?? Date.now
  115. const deadline = now() + timeoutMs
  116. let retryDelayMs = initialDelayMs
  117. for (;;) {
  118. try {
  119. return runCommand('launchctl', ['bootstrap', domain, plistPath])
  120. } catch (error) {
  121. if (!launchctlBootstrapRetryable(error)) throw error
  122. const remainingMs = deadline - now()
  123. if (remainingMs <= 0) throw error
  124. const waitMs = Math.min(retryDelayMs, maximumDelayMs, remainingMs)
  125. await wait(waitMs)
  126. retryDelayMs = Math.min(retryDelayMs * 2, maximumDelayMs)
  127. }
  128. }
  129. }
  130. async function install() {
  131. if (!existsSync(serverEntry)) {
  132. throw new Error('未找到生产构建,请先运行 npm run build')
  133. }
  134. await mkdir(launchAgents, { recursive: true })
  135. await mkdir(dataHome, { recursive: true, mode: 0o700 })
  136. await mkdir(logDir, { recursive: true })
  137. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  138. await writeFile(plistPath, launchAgentPlist(), { mode: 0o600 })
  139. await chmod(plistPath, 0o600)
  140. run('plutil', ['-lint', plistPath], { inherit: true })
  141. await bootstrapLaunchAgent()
  142. process.stdout.write(`已安装并启动 ${label}\n`)
  143. }
  144. async function start() {
  145. if (!existsSync(plistPath)) throw new Error('服务尚未安装')
  146. if (!loaded()) await bootstrapLaunchAgent()
  147. else run('launchctl', ['kickstart', '-k', `${domain}/${label}`])
  148. process.stdout.write(`已启动 ${label}\n`)
  149. }
  150. function stop() {
  151. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  152. process.stdout.write(`已停止 ${label};Hermes 9119 未被操作\n`)
  153. }
  154. async function uninstall() {
  155. stop()
  156. if (existsSync(plistPath)) await unlink(plistPath)
  157. process.stdout.write(`已卸载 ${label};运行数据保留在 ${dataHome}\n`)
  158. }
  159. function status() {
  160. if (!loaded()) {
  161. process.stdout.write(`${label}: stopped\n`)
  162. process.exitCode = 3
  163. return
  164. }
  165. process.stdout.write(run('launchctl', ['print', `${domain}/${label}`]))
  166. }
  167. async function pruneUploads(args) {
  168. const index = args.indexOf('--older-than')
  169. const days = index >= 0 ? Number(args[index + 1]) : 30
  170. if (!Number.isFinite(days) || days < 1) throw new Error('--older-than 必须是大于 0 的天数')
  171. if (!args.includes('--yes')) {
  172. throw new Error('这是显式清理操作,请增加 --yes')
  173. }
  174. const root = join(dataHome, 'uploads', 'pending')
  175. if (!existsSync(root)) return
  176. const cutoff = Date.now() - days * 86_400_000
  177. let removed = 0
  178. for (const entry of await readdir(root)) {
  179. const target = join(root, entry)
  180. const info = await stat(target)
  181. if (info.isFile() && info.mtimeMs < cutoff) {
  182. await unlink(target)
  183. removed += 1
  184. }
  185. }
  186. process.stdout.write(`已清理 ${removed} 个未提交上传文件\n`)
  187. }
  188. async function main() {
  189. const [, , group, command, ...args] = process.argv
  190. if (group === 'service') {
  191. if (command === 'install') return install()
  192. if (command === 'start') return start()
  193. if (command === 'stop') return stop()
  194. if (command === 'status') return status()
  195. if (command === 'uninstall') return uninstall()
  196. }
  197. if (group === 'uploads' && command === 'prune') return pruneUploads(args)
  198. 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`)
  199. }
  200. export function isMainModule(entry = process.argv[1]) {
  201. if (!entry) return false
  202. try {
  203. return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))
  204. } catch {
  205. return resolve(entry) === fileURLToPath(import.meta.url)
  206. }
  207. }
  208. if (isMainModule()) {
  209. main().catch(error => {
  210. process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
  211. process.exitCode = 1
  212. })
  213. }