systemManagementDialog.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
  2. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  3. import { nextTick } from 'vue'
  4. import SystemManagementDialog from '@/components/app/SystemManagementDialog.vue'
  5. import { getUpstreamConnectionStatus, listUsers } from '@/api/admin'
  6. import { getPushSystemStatus, saveFCMPushSystemConfig, savePushSystemConfig, type PushSystemStatus } from '@/api/push'
  7. vi.mock('@/api/admin', () => ({
  8. createUser: vi.fn(async () => undefined),
  9. deleteUser: vi.fn(async () => undefined),
  10. getAllowedHostsSettings: vi.fn(async () => ({
  11. source: 'none', hosts: [], editableHosts: [], environmentHosts: [],
  12. })),
  13. getUpstreamConnectionStatus: vi.fn(async () => ({
  14. endpoint: 'embedded', authMode: 'embedded', networkScope: 'local', version: '0.23.0', hermesHome: '/data/.yaoyao/hermes',
  15. webNetworkScope: 'network', ready: true, lastVerifiedAt: 1_788_273_600_000,
  16. })),
  17. listUsers: vi.fn(async () => []),
  18. saveAllowedHostsSettings: vi.fn(async (hosts: string[]) => ({
  19. source: 'file', hosts, editableHosts: hosts, environmentHosts: [],
  20. })),
  21. setUpstreamCredentials: vi.fn(async () => undefined),
  22. updateUser: vi.fn(async () => undefined),
  23. }))
  24. vi.mock('@/api/push', () => ({
  25. getPushSystemStatus: vi.fn(),
  26. saveFCMPushSystemConfig: vi.fn(),
  27. savePushSystemConfig: vi.fn(),
  28. }))
  29. function pushStatus(overrides: Partial<PushSystemStatus> = {}): PushSystemStatus {
  30. return {
  31. configured: false,
  32. healthy: false,
  33. topic: 'cn.samien.yaoyao.hermes',
  34. registrationCount: 0,
  35. pendingCount: 0,
  36. source: 'none',
  37. editable: true,
  38. managementAvailable: true,
  39. environments: ['development', 'production'],
  40. warnings: [],
  41. ...overrides,
  42. }
  43. }
  44. async function mountOpen(): Promise<VueWrapper> {
  45. const wrapper = mount(SystemManagementDialog, {
  46. attachTo: document.body,
  47. props: { open: false },
  48. global: { stubs: { AppIcon: true } },
  49. })
  50. await wrapper.setProps({ open: true })
  51. await flushPromises()
  52. return wrapper
  53. }
  54. function input(name: string): HTMLInputElement {
  55. return document.querySelector<HTMLInputElement>(`input[name="${name}"]`)!
  56. }
  57. function enter(name: string, value: string) {
  58. const element = input(name)
  59. element.value = value
  60. element.dispatchEvent(new Event('input'))
  61. }
  62. function button(label: string): HTMLButtonElement | undefined {
  63. return [...document.querySelectorAll<HTMLButtonElement>('button')]
  64. .find(element => element.textContent?.includes(label))
  65. }
  66. beforeEach(() => {
  67. vi.mocked(listUsers).mockResolvedValue([])
  68. vi.mocked(getPushSystemStatus).mockResolvedValue(pushStatus())
  69. vi.mocked(savePushSystemConfig).mockResolvedValue(pushStatus({ configured: true, healthy: true, source: 'file' }))
  70. vi.mocked(saveFCMPushSystemConfig).mockResolvedValue(pushStatus())
  71. })
  72. afterEach(() => {
  73. document.body.innerHTML = ''
  74. vi.clearAllMocks()
  75. })
  76. describe('System management APNs configuration', () => {
  77. it('shows the embedded Hermes status without 9119 credentials or the bridge plugin', async () => {
  78. const wrapper = await mountOpen()
  79. expect(document.body.textContent).toContain('内置 Hermes 内核已就绪')
  80. expect(document.body.textContent).toContain('/data/.yaoyao/hermes')
  81. expect(document.body.textContent).toContain('局域网可访问')
  82. expect(document.body.textContent).not.toContain('9119 网络范围')
  83. expect(input('upstream-username')).toBeNull()
  84. expect(input('upstream-password')).toBeNull()
  85. wrapper.unmount()
  86. })
  87. it('explains a missing kernel installation', async () => {
  88. vi.mocked(getUpstreamConnectionStatus).mockResolvedValueOnce({
  89. endpoint: 'embedded', authMode: 'embedded', networkScope: 'local',
  90. webNetworkScope: 'network', ready: false, error: '内置 Hermes 内核尚未安装,请运行 yaoyao setup',
  91. })
  92. const wrapper = await mountOpen()
  93. expect(document.body.textContent).toContain('内置 Hermes 内核尚未安装')
  94. expect(button('验证并保存')).toBeUndefined()
  95. wrapper.unmount()
  96. })
  97. it('includes the target username in every row action accessible name', async () => {
  98. vi.mocked(listUsers).mockResolvedValueOnce([{
  99. id: 'user-1',
  100. username: 'member',
  101. role: 'user',
  102. enabled: true,
  103. mustChangePassword: false,
  104. createdAt: 1,
  105. updatedAt: 1,
  106. }])
  107. const wrapper = await mountOpen()
  108. expect(document.querySelector('[aria-label="为用户 member 重置密码"]')).not.toBeNull()
  109. expect(document.querySelector('[aria-label="禁用用户 member"]')).not.toBeNull()
  110. expect(document.querySelector('[aria-label="删除用户 member"]')).not.toBeNull()
  111. wrapper.unmount()
  112. })
  113. it('validates and saves an FCM service-account path without exposing secret contents', async () => {
  114. const fcm = {
  115. configured: false,
  116. healthy: false,
  117. registrationCount: 0,
  118. pendingCount: 0,
  119. source: 'none' as const,
  120. editable: true,
  121. managementAvailable: true,
  122. packageName: 'cn.samien.yaoyao.hermes',
  123. warnings: [],
  124. }
  125. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({ providers: { fcm } }))
  126. vi.mocked(saveFCMPushSystemConfig).mockResolvedValueOnce(pushStatus({
  127. providers: { fcm: { ...fcm, configured: true, healthy: true, source: 'file' } },
  128. }))
  129. const wrapper = await mountOpen()
  130. enter('fcm-service-account-file', ' /srv/secrets/firebase-service-account.json ')
  131. enter('fcm-project-id', ' yaoyao-test-project ')
  132. enter('fcm-package-name', ' cn.samien.yaoyao.hermes ')
  133. await nextTick()
  134. const form = input('fcm-service-account-file').closest('form')!
  135. form.dispatchEvent(new Event('submit'))
  136. await flushPromises()
  137. expect(saveFCMPushSystemConfig).toHaveBeenCalledWith({
  138. serviceAccountFile: '/srv/secrets/firebase-service-account.json',
  139. projectId: 'yaoyao-test-project',
  140. packageName: 'cn.samien.yaoyao.hermes',
  141. })
  142. expect(document.body.textContent).toContain('Firebase 权限与项目验证通过,FCM 已启用')
  143. expect(document.body.textContent).toContain('FCM 推送服务正常')
  144. wrapper.unmount()
  145. })
  146. it('sends a server-local path and both environments through validation and enablement', async () => {
  147. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({ environments: [] }))
  148. vi.mocked(savePushSystemConfig).mockResolvedValueOnce(pushStatus({
  149. configured: true,
  150. healthy: true,
  151. source: 'file',
  152. keyFile: '/srv/secrets/AuthKey_TEST.p8',
  153. keyId: 'KEY123',
  154. teamId: 'TEAM123',
  155. warnings: [{
  156. code: 'apns_key_permissions',
  157. message: 'APNs 已启用,但密钥文件权限为 0644;建议调整为 0600,此提示不会影响当前推送。',
  158. actualMode: '0644',
  159. recommendedMode: '0600',
  160. }],
  161. }))
  162. const wrapper = await mountOpen()
  163. enter('push-key-file', ' /srv/secrets/AuthKey_TEST.p8 ')
  164. enter('push-key-id', ' KEY123 ')
  165. enter('push-team-id', ' TEAM123 ')
  166. enter('push-topic', ' cn.samien.yaoyao.hermes ')
  167. await nextTick()
  168. const save = button('验证并启用')!
  169. expect(save.disabled).toBe(false)
  170. save.click()
  171. await flushPromises()
  172. expect(savePushSystemConfig).toHaveBeenCalledWith({
  173. keyFile: '/srv/secrets/AuthKey_TEST.p8',
  174. keyId: 'KEY123',
  175. teamId: 'TEAM123',
  176. topic: 'cn.samien.yaoyao.hermes',
  177. environments: ['development', 'production'],
  178. })
  179. expect(document.body.textContent).toContain('Sandbox 与 Production 验证通过,APNs 已启用')
  180. expect(document.querySelector('.push-warning')?.textContent).toContain('权限为 0644')
  181. expect(button('验证并启用')?.disabled).toBe(false)
  182. wrapper.unmount()
  183. })
  184. it('shows environment-managed configuration as read-only', async () => {
  185. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({
  186. configured: true,
  187. healthy: true,
  188. source: 'environment',
  189. editable: false,
  190. keyFile: '/Users/test/.hermes/secrets/AuthKey_TEST.p8',
  191. keyId: 'KEY123',
  192. teamId: 'TEAM123',
  193. }))
  194. const wrapper = await mountOpen()
  195. expect(document.body.textContent).toContain('由服务环境变量管理,Web 仅可查看')
  196. expect(input('push-key-file').readOnly).toBe(true)
  197. expect(document.querySelector<HTMLFieldSetElement>('.push-config-form fieldset')?.disabled).toBe(true)
  198. expect(button('验证并启用')).toBeUndefined()
  199. document.querySelector<HTMLFormElement>('.push-config-form')!.dispatchEvent(new Event('submit'))
  200. await nextTick()
  201. expect(savePushSystemConfig).not.toHaveBeenCalled()
  202. wrapper.unmount()
  203. })
  204. it('surfaces an invalid startup configuration instead of calling it unconfigured', async () => {
  205. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({
  206. configured: false,
  207. healthy: false,
  208. source: 'environment',
  209. editable: false,
  210. lastError: 'APNs key file must contain an ES256 private key',
  211. }))
  212. const wrapper = await mountOpen()
  213. expect(document.body.textContent).toContain('APNs 配置无效:APNs key file must contain an ES256 private key')
  214. wrapper.unmount()
  215. })
  216. it('keeps an old status-only response safe and does not expose editing controls', async () => {
  217. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({
  218. configured: true,
  219. healthy: true,
  220. managementAvailable: false,
  221. editable: false,
  222. }))
  223. const wrapper = await mountOpen()
  224. expect(document.body.textContent).toContain('APNs 推送服务正常')
  225. expect(document.body.textContent).toContain('当前服务版本只提供推送状态')
  226. expect(document.querySelector('.push-config-form')).toBeNull()
  227. expect(savePushSystemConfig).not.toHaveBeenCalled()
  228. wrapper.unmount()
  229. })
  230. it('rejects an empty environment set locally and preserves input after a server error', async () => {
  231. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({
  232. source: 'file',
  233. keyFile: '/srv/secrets/AuthKey_TEST.p8',
  234. keyId: 'KEY123',
  235. teamId: 'TEAM123',
  236. environments: ['development'],
  237. }))
  238. const wrapper = await mountOpen()
  239. const development = document.querySelector<HTMLInputElement>('input[type="checkbox"][value="development"]')!
  240. development.checked = false
  241. development.dispatchEvent(new Event('change'))
  242. await nextTick()
  243. document.querySelector<HTMLFormElement>('.push-config-form')!.dispatchEvent(new Event('submit'))
  244. await nextTick()
  245. expect(document.querySelector('[role="alert"]')?.textContent).toContain('至少选择 Sandbox 或 Production')
  246. expect(savePushSystemConfig).not.toHaveBeenCalled()
  247. development.checked = true
  248. development.dispatchEvent(new Event('change'))
  249. await nextTick()
  250. vi.mocked(savePushSystemConfig).mockRejectedValueOnce(new Error('15300 无法读取该密钥文件,请检查路径和服务账户权限'))
  251. button('验证并启用')!.click()
  252. await flushPromises()
  253. expect(document.querySelector('[role="alert"]')?.textContent).toContain('15300 无法读取该密钥文件')
  254. expect(input('push-key-file').value).toBe('/srv/secrets/AuthKey_TEST.p8')
  255. wrapper.unmount()
  256. })
  257. it('preserves an unsaved FCM draft while APNs is saved and locks the sibling form during the request', async () => {
  258. const fcm = {
  259. configured: true,
  260. healthy: true,
  261. registrationCount: 0,
  262. pendingCount: 0,
  263. source: 'file' as const,
  264. editable: true,
  265. managementAvailable: true,
  266. serviceAccountFile: '/srv/secrets/firebase.json',
  267. projectId: 'server-project',
  268. packageName: 'cn.samien.yaoyao.hermes',
  269. warnings: [],
  270. }
  271. vi.mocked(getPushSystemStatus).mockResolvedValueOnce(pushStatus({
  272. source: 'file',
  273. keyFile: '/srv/secrets/AuthKey_TEST.p8',
  274. keyId: 'KEY123',
  275. teamId: 'TEAM123',
  276. providers: { fcm },
  277. }))
  278. let resolveSave: ((status: PushSystemStatus) => void) | undefined
  279. vi.mocked(savePushSystemConfig).mockReturnValueOnce(new Promise(resolve => { resolveSave = resolve }))
  280. const wrapper = await mountOpen()
  281. enter('fcm-project-id', 'local-unsaved-project')
  282. await nextTick()
  283. button('验证并启用')!.click()
  284. await nextTick()
  285. expect(input('fcm-project-id').readOnly).toBe(true)
  286. resolveSave?.(pushStatus({
  287. configured: true,
  288. healthy: true,
  289. source: 'file',
  290. keyFile: '/srv/secrets/AuthKey_TEST.p8',
  291. keyId: 'KEY123',
  292. teamId: 'TEAM123',
  293. providers: { fcm: { ...fcm, projectId: 'server-response-project' } },
  294. }))
  295. await flushPromises()
  296. expect(input('fcm-project-id').value).toBe('local-unsaved-project')
  297. expect(input('fcm-project-id').readOnly).toBe(false)
  298. wrapper.unmount()
  299. })
  300. })