hermes-yaoyao.mjs 8.3 KB

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