hermes-yaoyao.mjs 8.3 KB

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