pairing.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { mkdtempSync, readFileSync, rmSync } 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 type { ApplicationRuntime } from '../../src/server/app.js'
  7. import type { ServerConfig } from '../../src/server/config.js'
  8. import { NodePairingStore } from '../../src/server/pairing.js'
  9. import { createAuthenticatedApplication as createApplication } from './authenticatedApplication.js'
  10. const homes: string[] = []
  11. const runtimes: ApplicationRuntime[] = []
  12. afterEach(() => {
  13. for (const runtime of runtimes.splice(0)) runtime.close()
  14. for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
  15. })
  16. function temporaryHome(): string {
  17. const home = mkdtempSync(join(tmpdir(), 'hermes-yaoyao-pairing-'))
  18. homes.push(home)
  19. return home
  20. }
  21. function config(home: string): ServerConfig {
  22. return {
  23. host: '127.0.0.1',
  24. port: 15300,
  25. upstream: new URL('http://127.0.0.1:9119'),
  26. allowedHosts: new Set(),
  27. home,
  28. mediaRoot: join(home, 'media'),
  29. attachmentsRoot: join(home, 'attachments'),
  30. imagesRoot: join(home, 'images'),
  31. mediaOwner: 'tester',
  32. allowInsecureLan: false,
  33. insecureLan: false,
  34. production: false,
  35. }
  36. }
  37. function cookies(response: request.Response): string {
  38. const values = response.headers['set-cookie'] as unknown as string[] | undefined
  39. return (values ?? []).map((value) => value.split(';', 1)[0]).join('; ')
  40. }
  41. describe('Hermes node pairing', () => {
  42. it('stores only encrypted delegated cookies and rejects replayed pairing secrets', () => {
  43. const home = temporaryHome()
  44. let now = 1_000
  45. const store = new NodePairingStore(home, () => now)
  46. const pairing = store.create('hermes_session_rt=refresh-secret', ['agents.read', 'history.read'])
  47. const claimed = store.claim({
  48. pairingID: pairing.id,
  49. secret: pairing.secret,
  50. deviceName: '测试 iPhone',
  51. })
  52. expect(store.authorize(claimed.device.id, claimed.token, 'history.read'))
  53. .toBe('hermes_session_rt=refresh-secret')
  54. expect(() => store.claim({
  55. pairingID: pairing.id,
  56. secret: pairing.secret,
  57. deviceName: '重放设备',
  58. })).toThrowError(/already used/i)
  59. expect(() => store.authorize(claimed.device.id, claimed.token, 'groups.execute'))
  60. .toThrowError(/lacks groups.execute/i)
  61. const persisted = readFileSync(join(home, 'paired-devices.json'), 'utf8')
  62. expect(persisted).not.toContain('refresh-secret')
  63. expect(persisted).not.toContain(claimed.token)
  64. now += 1
  65. const restored = new NodePairingStore(home, () => now)
  66. expect(restored.nodeID).toBe(store.nodeID)
  67. expect(restored.authorize(claimed.device.id, claimed.token, 'agents.read'))
  68. .toBe('hermes_session_rt=refresh-secret')
  69. })
  70. it('expires unclaimed QR secrets after two minutes', () => {
  71. const home = temporaryHome()
  72. let now = 10_000
  73. const store = new NodePairingStore(home, () => now)
  74. const pairing = store.create('hermes_session_at=access')
  75. now = pairing.expiresAt + 1
  76. expect(store.status(pairing.id)).toEqual({ state: 'expired' })
  77. expect(() => store.claim({
  78. pairingID: pairing.id,
  79. secret: pairing.secret,
  80. deviceName: '迟到的设备',
  81. })).toThrowError(/expired/i)
  82. })
  83. it('claims from the QR and exposes a revocable Hermes-compatible node proxy', async () => {
  84. const home = temporaryHome()
  85. const upstreamRequests: Array<{
  86. path: string
  87. cookie: string
  88. authorization: string
  89. contentType: string
  90. nodeClient: string
  91. body?: Buffer
  92. }> = []
  93. const fetchImpl: typeof fetch = (async (input: string | URL | Request, init?: RequestInit) => {
  94. const url = new URL(input instanceof Request ? input.url : String(input))
  95. const headers = new Headers(init?.headers)
  96. const recordedBody = init?.body === undefined
  97. ? undefined
  98. : Buffer.from(await new Response(init.body).arrayBuffer())
  99. upstreamRequests.push({
  100. path: url.pathname,
  101. cookie: headers.get('cookie') ?? '',
  102. authorization: headers.get('authorization') ?? '',
  103. contentType: headers.get('content-type') ?? '',
  104. nodeClient: headers.get('x-yaoyao-node-client') ?? '',
  105. body: recordedBody,
  106. })
  107. const responseHeaders = new Headers({ 'content-type': 'application/json' })
  108. if (url.pathname === '/api/status') {
  109. responseHeaders.append('set-cookie', 'hermes_session_at=paired-access; Path=/; HttpOnly')
  110. return new Response(JSON.stringify({ auth_required: true }), { headers: responseHeaders })
  111. }
  112. if (url.pathname === '/api/auth/me') {
  113. return new Response(JSON.stringify({ user_id: 'owner', display_name: 'Owner' }), { headers: responseHeaders })
  114. }
  115. if (url.pathname === '/api/profiles') {
  116. return new Response(JSON.stringify({ profiles: [{ name: 'default', is_default: true }] }), { headers: responseHeaders })
  117. }
  118. if (url.pathname === '/api/plugins/yaoyao/profiles') {
  119. return new Response(JSON.stringify({ profiles: [{ name: 'default', botName: '竹儿', agentName: '旧插件名称' }] }), { headers: responseHeaders })
  120. }
  121. if (url.pathname === '/api/auth/providers') {
  122. return new Response(JSON.stringify({
  123. providers: [{ name: 'basic', supports_password: true }],
  124. }), { headers: responseHeaders })
  125. }
  126. if (url.pathname === '/auth/password-login') {
  127. responseHeaders.append('set-cookie', 'hermes_session_rt=independent-refresh; Path=/; HttpOnly')
  128. return new Response(JSON.stringify({ ok: true }), { headers: responseHeaders })
  129. }
  130. return new Response(JSON.stringify({ ok: true }), { headers: responseHeaders })
  131. }) as typeof fetch
  132. const runtime = createApplication({ config: config(home), fetchImpl })
  133. runtimes.push(runtime)
  134. const bootstrap = await request(runtime.app.callback())
  135. .get('/api/app/bootstrap')
  136. .set('Host', '127.0.0.1:15300')
  137. .expect(200)
  138. const cookie = cookies(bootstrap)
  139. await request(runtime.app.callback())
  140. .post('/api/app/pairings')
  141. .set('Host', '127.0.0.1:15300')
  142. .set('Origin', 'http://127.0.0.1:15300')
  143. .set('Cookie', cookie)
  144. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  145. .send({ scopes: ['unknown.scope'] })
  146. .expect(400)
  147. const pairing = await request(runtime.app.callback())
  148. .post('/api/app/pairings')
  149. .set('Host', '127.0.0.1:15300')
  150. .set('Origin', 'http://127.0.0.1:15300')
  151. .set('Cookie', cookie)
  152. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  153. .send({
  154. scopes: ['agents.read', 'history.read', 'sessions.execute', 'groups.execute'],
  155. })
  156. .expect(201)
  157. const deepLink = new URL(pairing.body.qrPayload)
  158. expect(deepLink.protocol).toBe('yaoyao:')
  159. expect(deepLink.searchParams.get('secret')).toBeTruthy()
  160. const claim = await request(runtime.app.callback())
  161. .post('/api/pair/v1/claim')
  162. .set('Host', '127.0.0.1:15300')
  163. .send({
  164. pairingId: pairing.body.pairingId,
  165. secret: deepLink.searchParams.get('secret'),
  166. deviceName: 'YaoYao iPhone',
  167. })
  168. .expect(201)
  169. expect(claim.body.serverUrl).toBe(`http://127.0.0.1:15300/node/${claim.body.deviceId}`)
  170. expect(readFileSync(join(home, 'paired-devices.json'), 'utf8'))
  171. .not.toContain('paired-access')
  172. const profiles = await request(runtime.app.callback())
  173. .get(`/node/${claim.body.deviceId}/api/profiles`)
  174. .set('Host', '127.0.0.1:15300')
  175. .set('Authorization', `Bearer ${claim.body.token}`)
  176. .expect(200)
  177. expect(profiles.body.profiles[0].name).toBe('default')
  178. expect(upstreamRequests.at(-1)).toMatchObject({
  179. path: '/api/profiles',
  180. authorization: '',
  181. })
  182. expect(upstreamRequests.at(-1)?.cookie).toContain('hermes_session_at=paired-access')
  183. expect(upstreamRequests.at(-1)?.cookie).not.toContain('hermes_session_rt=independent-refresh')
  184. const attachment = Buffer.from('remote attachment')
  185. await request(runtime.app.callback())
  186. .post(`/node/${claim.body.deviceId}/api/plugins/yaoyao/v1/node-worker/sessions/runtime-1/attachments`)
  187. .set('Host', '127.0.0.1:15300')
  188. .set('Authorization', `Bearer ${claim.body.token}`)
  189. .set('Content-Type', 'application/octet-stream')
  190. .set('X-File-Name-B64', Buffer.from('note.txt').toString('base64url'))
  191. .set('X-Mime-Type', 'text/plain')
  192. .send(attachment)
  193. .expect(410)
  194. expect(upstreamRequests.some(r => r.path.includes('/node-worker/'))).toBe(false)
  195. await request(runtime.app.callback())
  196. .delete(`/api/app/paired-devices/${claim.body.deviceId}`)
  197. .set('Host', '127.0.0.1:15300')
  198. .set('Origin', 'http://127.0.0.1:15300')
  199. .set('Cookie', cookie)
  200. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  201. .expect(200)
  202. await request(runtime.app.callback())
  203. .get(`/node/${claim.body.deviceId}/api/profiles`)
  204. .set('Host', '127.0.0.1:15300')
  205. .set('Authorization', `Bearer ${claim.body.token}`)
  206. .expect(401)
  207. })
  208. })