systemUpdateRoutes.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import request from 'supertest'
  5. import { afterEach, describe, expect, it } from 'vitest'
  6. import { createApplication, type ApplicationRuntime } from '../../src/server/app.js'
  7. import type { ServerConfig } from '../../src/server/config.js'
  8. import { systemUpdateRequestAllowed } from '../../src/server/routes.js'
  9. import { SystemUpdateManager } from '../../src/server/updateManager.js'
  10. const runtimes: ApplicationRuntime[] = []
  11. const roots: string[] = []
  12. afterEach(() => {
  13. for (const runtime of runtimes.splice(0)) runtime.close()
  14. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  15. })
  16. function cookieHeader(response: request.Response): string {
  17. const values = response.headers['set-cookie'] as unknown as string[]
  18. return values.map(value => value.split(';', 1)[0]).join('; ')
  19. }
  20. function json(value: unknown, init: ResponseInit = {}) {
  21. return new Response(JSON.stringify(value), {
  22. ...init,
  23. headers: { 'content-type': 'application/json', ...init.headers },
  24. })
  25. }
  26. describe('system update routes', () => {
  27. it('allows loopback updates and requires an explicit opt-in for LAN clients', () => {
  28. expect(systemUpdateRequestAllowed('127.0.0.1')).toBe(true)
  29. expect(systemUpdateRequestAllowed('::ffff:127.0.0.1')).toBe(true)
  30. expect(systemUpdateRequestAllowed('192.168.1.8')).toBe(false)
  31. expect(systemUpdateRequestAllowed('192.168.1.8', true)).toBe(true)
  32. })
  33. it('checks and queues a fixed Web/plugin release through authenticated CSRF routes', async () => {
  34. const root = mkdtempSync(join(tmpdir(), 'hermes-system-update-routes-'))
  35. roots.push(root)
  36. const projectRoot = join(root, 'project')
  37. mkdirSync(projectRoot)
  38. writeFileSync(join(projectRoot, 'release.json'), JSON.stringify({
  39. schemaVersion: 1, releaseVersion: '0.2.0', webVersion: '0.2.0', pluginVersion: '1.7.1', gitTag: 'v0.2.0',
  40. }))
  41. const config: ServerConfig = {
  42. host: '127.0.0.1', port: 8800, upstream: new URL('http://127.0.0.1:9119'),
  43. allowedHosts: new Set(), home: join(root, 'data'), mediaRoot: join(root, 'media'),
  44. attachmentsRoot: join(root, 'attachments'), imagesRoot: join(root, 'images'), mediaOwner: 'tester',
  45. allowInsecureLan: false, insecureLan: false, production: false,
  46. releaseRoot: join(root, 'installed'), releaseSource: 'https://example.test/hermes-yaoyao.git',
  47. }
  48. const launched: string[] = []
  49. const latest = {
  50. schemaVersion: 1 as const, releaseVersion: '0.3.0', webVersion: '0.3.0', pluginVersion: '1.8.0', gitTag: 'v0.3.0',
  51. }
  52. const updates = new SystemUpdateManager(config, {
  53. projectRoot,
  54. inspectRemote: async () => ({ manifest: latest, commit: 'b'.repeat(40) }),
  55. launchUpdater: path => { launched.push(path) },
  56. platform: 'darwin',
  57. })
  58. let pluginVersion = '1.7.1'
  59. const fetchImpl = (async (input: string | URL | Request) => {
  60. const path = new URL(input instanceof Request ? input.url : String(input)).pathname
  61. if (path === '/api/status') return json({ auth_required: true }, { headers: { 'set-cookie': 'hermes_session_at=session; Path=/; HttpOnly' } })
  62. if (path === '/api/auth/me') return json({ user_id: 'admin', display_name: '管理员' })
  63. if (path === '/api/profiles') return json({ profiles: [{ name: 'default', is_default: true }] })
  64. if (path === '/api/plugins/yaoyao/profiles') return json({ profiles: [] })
  65. if (path === '/api/dashboard/plugins') return json([{ name: 'yaoyao', version: pluginVersion }])
  66. if (path === '/api/plugins/yaoyao/maintenance/storage') return json({ ready: true })
  67. if (path === '/api/dashboard/agent-plugins/install') {
  68. pluginVersion = '1.8.0'
  69. return json({ ok: true, plugin_name: 'yaoyao', enabled: true })
  70. }
  71. return json({ ok: true })
  72. }) as typeof fetch
  73. const runtime = createApplication({ config, fetchImpl, updates })
  74. runtimes.push(runtime)
  75. const bootstrap = await request(runtime.app.callback())
  76. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  77. const cookie = cookieHeader(bootstrap)
  78. const mutation = (path: string) => request(runtime.app.callback())
  79. .post(path)
  80. .set('Host', '127.0.0.1:8800')
  81. .set('Origin', 'http://127.0.0.1:8800')
  82. .set('Cookie', cookie)
  83. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  84. const status = await request(runtime.app.callback())
  85. .get('/api/app/system/update/status').set('Host', '127.0.0.1:8800').set('Cookie', cookie).expect(200)
  86. expect(status.body).toMatchObject({ installedPluginVersion: '1.7.1', versionsMatch: true, updateAvailable: false })
  87. const check = await mutation('/api/app/system/update/check').send({}).expect(200)
  88. expect(check.body).toMatchObject({ latest, updateAvailable: true })
  89. const queued = await mutation('/api/app/system/update/apply').send({ targetVersion: '0.3.0' }).expect(202)
  90. expect(queued.body).toMatchObject({ operation: 'update', state: 'queued', target: latest })
  91. expect(launched).toHaveLength(1)
  92. const jobResponse = await request(runtime.app.callback())
  93. .get(`/api/app/system/update/jobs/${queued.body.id}`)
  94. .set('Host', '127.0.0.1:8800').set('Cookie', cookie)
  95. .expect(200)
  96. expect(jobResponse.body).toMatchObject({ id: queued.body.id, state: 'queued' })
  97. })
  98. })