dashboardSupervisor.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { execFileSync, spawn } from 'node:child_process'
  2. import { randomBytes, scryptSync } from 'node:crypto'
  3. import { createConnection } from 'node:net'
  4. export const DEFAULT_DASHBOARD_USERNAME = 'admin'
  5. export const DEFAULT_DASHBOARD_PASSWORD = 'admin'
  6. const DASHBOARD_PORT = 9119
  7. const SUPERVISION_INTERVAL_MS = 5_000
  8. const RESTART_READY_TIMEOUT_MS = 15_000
  9. type Run = (args: readonly string[]) => string
  10. type Launch = (args: readonly string[]) => void
  11. type Probe = (host: string, port: number) => Promise<boolean>
  12. export interface DashboardSupervisorOptions {
  13. allowLan: boolean
  14. command?: string
  15. intervalMs?: number
  16. run?: Run
  17. launch?: Launch
  18. probe?: Probe
  19. log?: (message: string) => void
  20. credentials?: { username: string; password: string }
  21. }
  22. function defaultRun(command: string): Run {
  23. return (args) => execFileSync(command, args, { encoding: 'utf8', stdio: 'pipe' })
  24. }
  25. function defaultLaunch(command: string): Launch {
  26. return (args) => {
  27. const child = spawn(command, [...args], { detached: true, stdio: 'ignore' })
  28. child.unref()
  29. }
  30. }
  31. function portIsListening(host: string, port: number): Promise<boolean> {
  32. return new Promise((resolve) => {
  33. const socket = createConnection({ host, port })
  34. const finish = (value: boolean) => {
  35. socket.removeAllListeners()
  36. socket.destroy()
  37. resolve(value)
  38. }
  39. socket.setTimeout(1_000)
  40. socket.once('connect', () => finish(true))
  41. socket.once('timeout', () => finish(false))
  42. socket.once('error', () => finish(false))
  43. })
  44. }
  45. function delay(milliseconds: number): Promise<void> {
  46. return new Promise((resolve) => setTimeout(resolve, milliseconds))
  47. }
  48. function passwordHash(password: string): string {
  49. const salt = randomBytes(16)
  50. const derived = scryptSync(password, salt, 32, { N: 2 ** 14, r: 8, p: 1, maxmem: 64 * 1024 * 1024 })
  51. return `scrypt$16384$8$1$${salt.toString('base64')}$${derived.toString('base64')}`
  52. }
  53. /** Keeps the local Hermes Dashboard available for the managed 8800 service. */
  54. export class DashboardSupervisor {
  55. private readonly command: string
  56. private readonly dashboardHost: string
  57. private readonly run: Run
  58. private readonly launch: Launch
  59. private readonly probe: Probe
  60. private readonly log: (message: string) => void
  61. private readonly intervalMs: number
  62. private readonly credentials: { username: string; password: string }
  63. private timer: NodeJS.Timeout | undefined
  64. private checking = false
  65. constructor(options: DashboardSupervisorOptions) {
  66. this.command = options.command ?? 'hermes'
  67. this.dashboardHost = options.allowLan ? '0.0.0.0' : '127.0.0.1'
  68. this.run = options.run ?? defaultRun(this.command)
  69. this.launch = options.launch ?? defaultLaunch(this.command)
  70. this.probe = options.probe ?? portIsListening
  71. this.log = options.log ?? console.info
  72. this.intervalMs = options.intervalMs ?? SUPERVISION_INTERVAL_MS
  73. this.credentials = options.credentials ?? {
  74. username: DEFAULT_DASHBOARD_USERNAME,
  75. password: DEFAULT_DASHBOARD_PASSWORD,
  76. }
  77. }
  78. start(): void {
  79. void this.checkNow()
  80. this.timer = setInterval(() => { void this.checkNow() }, this.intervalMs)
  81. this.timer.unref()
  82. }
  83. stop(): void {
  84. if (this.timer) clearInterval(this.timer)
  85. this.timer = undefined
  86. }
  87. async restart(): Promise<void> {
  88. while (this.checking) await delay(25)
  89. this.run(['dashboard', '--stop'])
  90. await this.checkNow()
  91. const deadline = Date.now() + RESTART_READY_TIMEOUT_MS
  92. while (Date.now() < deadline) {
  93. if (await this.probe('127.0.0.1', DASHBOARD_PORT)) return
  94. await delay(100)
  95. }
  96. throw new Error('Hermes Dashboard did not return on 9119 after restart')
  97. }
  98. async checkNow(): Promise<void> {
  99. if (this.checking) return
  100. this.checking = true
  101. try {
  102. const credentialsChanged = this.ensureBasicAuthentication()
  103. let running = await this.probe('127.0.0.1', DASHBOARD_PORT)
  104. if (credentialsChanged && running) {
  105. this.log('Hermes Dashboard authentication was configured; restarting 9119 to load it.')
  106. this.run(['dashboard', '--stop'])
  107. running = await this.probe('127.0.0.1', DASHBOARD_PORT)
  108. }
  109. if (running) return
  110. this.log(`Hermes Dashboard is unavailable on 9119; starting it on ${this.dashboardHost}.`)
  111. this.launch(['dashboard', '--host', this.dashboardHost, '--no-open'])
  112. } catch (error) {
  113. this.log(`Hermes Dashboard supervision failed: ${error instanceof Error ? error.message : String(error)}`)
  114. } finally {
  115. this.checking = false
  116. }
  117. }
  118. private value(key: string): string {
  119. try {
  120. return this.run(['config', 'get', key]).trim()
  121. } catch {
  122. return ''
  123. }
  124. }
  125. private set(key: string, value: string): void {
  126. this.run(['config', 'set', key, value])
  127. }
  128. private ensureBasicAuthentication(): boolean {
  129. const username = this.value('dashboard.basic_auth.username')
  130. const configuredPasswordHash = this.value('dashboard.basic_auth.password_hash')
  131. const password = this.value('dashboard.basic_auth.password')
  132. const secret = this.value('dashboard.basic_auth.secret')
  133. let changed = false
  134. if (!username) {
  135. this.set('dashboard.basic_auth.username', this.credentials.username)
  136. changed = true
  137. }
  138. if (!configuredPasswordHash && !password) {
  139. this.set('dashboard.basic_auth.password_hash', passwordHash(this.credentials.password))
  140. changed = true
  141. }
  142. if (!secret) {
  143. this.set('dashboard.basic_auth.secret', randomBytes(32).toString('base64url'))
  144. changed = true
  145. }
  146. return changed
  147. }
  148. }