realtimeApi.test.ts 4.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // @vitest-environment node
  2. import { mkdtempSync, rmSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import request from 'supertest'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { createApplication, type ApplicationRuntime } from '../../src/server/app.js'
  8. import type { ServerConfig } from '../../src/server/config.js'
  9. const roots: string[] = []
  10. const runtimes: ApplicationRuntime[] = []
  11. afterEach(() => {
  12. for (const runtime of runtimes.splice(0)) runtime.close()
  13. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  14. })
  15. describe('native Hermes chat and history are separated on 15300', () => {
  16. it('opens realtime chat while keeping non-Web history mutations read-only', async () => {
  17. const home = mkdtempSync(join(tmpdir(), 'yaoyao-native-history-'))
  18. roots.push(home)
  19. let upstreamCalls = 0, upstreamWrites = 0
  20. const config: ServerConfig = {
  21. host: '127.0.0.1', port: 15300, upstream: new URL('http://127.0.0.1:9119'),
  22. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home,
  23. imagesRoot: home, mediaOwner: 'test', allowInsecureLan: false,
  24. insecureLan: false, production: false,
  25. }
  26. const runtime = createApplication({
  27. config,
  28. fetchImpl: (async (input, init) => {
  29. upstreamCalls += 1
  30. if (!['GET', 'HEAD'].includes(init?.method ?? 'GET')) upstreamWrites += 1
  31. const path = new URL(String(input)).pathname
  32. if (path === '/api/status') return Response.json({ auth_required: true })
  33. if (path === '/api/auth/me') return Response.json({ user_id: 'service' })
  34. if (path === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
  35. if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), {
  36. headers: { 'content-type': 'application/json', 'set-cookie': 'hermes_service=session; Path=/; HttpOnly' },
  37. })
  38. if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default' }] })
  39. if (path === '/api/auth/ws-ticket') return Response.json({ ticket: 'fixture-ticket' })
  40. if (path === '/api/sessions/session-web') return Response.json(init?.method === 'PATCH' ? { ok: true } : { id: 'session-web', source: 'web' })
  41. return Response.json({ method: init?.method ?? 'GET' })
  42. }) as typeof fetch,
  43. })
  44. runtimes.push(runtime)
  45. const agent = request.agent(runtime.app.callback())
  46. const origin = 'http://127.0.0.1:15300'
  47. const bootstrap = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  48. const setup = await agent.post('/api/app/setup').set('Host', '127.0.0.1:15300')
  49. .set('Origin', origin).set('X-CSRF-Token', bootstrap.body.csrfToken)
  50. .send({ username: 'owner', password: 'fixture-password' }).expect(200)
  51. const csrf = setup.body.csrfToken
  52. const capabilities = await agent.get('/api/realtime/capabilities').set('Host', '127.0.0.1:15300').expect(200)
  53. expect(capabilities.body.channels).toEqual(['chat'])
  54. const beforeWrites = upstreamCalls, beforeUpstreamWrites = upstreamWrites
  55. for (const path of ['/api/app/sessions/session-1', '/api/sessions/session-1']) {
  56. const response = await agent.patch(path).set('Host', '127.0.0.1:15300')
  57. .set('Origin', origin).set('X-CSRF-Token', csrf).send({ title: '不能修改' }).expect(410)
  58. expect(response.body.code).toBe('native_sessions_read_only')
  59. }
  60. const pairing = runtime.pairings.create('hermes_device=session')
  61. const paired = runtime.pairings.claim({
  62. pairingID: pairing.id,
  63. secret: pairing.secret,
  64. deviceName: 'history-only fixture',
  65. })
  66. const pairedWrite = await request(runtime.app.callback())
  67. .patch(`/node/${paired.device.id}/api/sessions/session-1`)
  68. .set('Host', '127.0.0.1:15300')
  69. .set('Authorization', `Bearer ${paired.token}`)
  70. .send({ title: '不能修改' })
  71. .expect(410)
  72. expect(pairedWrite.body.code).toBe('native_sessions_read_only')
  73. expect(upstreamCalls).toBeGreaterThan(beforeWrites)
  74. expect(upstreamWrites).toBe(beforeUpstreamWrites)
  75. await agent.patch('/api/app/sessions/session-web?profile=default').set('Host', '127.0.0.1:15300')
  76. .set('Origin', origin).set('X-CSRF-Token', csrf).send({ title: '可修改的聊天' }).expect(200)
  77. expect(upstreamWrites).toBe(beforeUpstreamWrites + 1)
  78. })
  79. })