localAuthRoutes.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. import { mkdtempSync, 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 { createApplication, createNodeServer, type ApplicationRuntime, type NodeServerRuntime } from '../../src/server/app.js'
  7. import type { ServerConfig } from '../../src/server/config.js'
  8. const roots: string[] = []
  9. const runtimes: ApplicationRuntime[] = []
  10. const nodeRuntimes: NodeServerRuntime[] = []
  11. afterEach(async () => {
  12. for (const runtime of nodeRuntimes.splice(0)) await runtime.close()
  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 cookies(response: request.Response): string {
  17. const values = response.headers['set-cookie'] as unknown as string[] | undefined
  18. return (values ?? []).map(value => value.split(';', 1)[0]).join('; ')
  19. }
  20. describe('8800 local authentication routes', () => {
  21. it('installs without upstream credentials while keeping local login and CSRF mandatory', async () => {
  22. const home = mkdtempSync(join(tmpdir(), 'yaoyao-local-token-')); roots.push(home)
  23. const token = 'fixture_local_only_session_token_123456'
  24. const config: ServerConfig = {
  25. host: '127.0.0.1', port: 8800, upstream: new URL('http://127.0.0.1:9119'),
  26. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  27. mediaOwner: 'tester', allowInsecureLan: false, insecureLan: false, production: false, superviseDashboard: true,
  28. }
  29. const runtime = createApplication({ config, fetchImpl: (async (input, init) => {
  30. const path = new URL(String(input)).pathname
  31. if (path === '/api/status') return Response.json({ auth_required: false })
  32. if (path === '/') return new Response(`<script>window.__HERMES_SESSION_TOKEN__="${token}";</script>`)
  33. if (new Headers(init?.headers).get('x-hermes-session-token') !== token) return Response.json({}, { status: 401 })
  34. return Response.json({ profiles: [{ name: 'default', is_default: true }] })
  35. }) as typeof fetch }); runtimes.push(runtime)
  36. expect(runtime.auth.upstreamCredentials()).toBeUndefined()
  37. const agent = request.agent(runtime.app.callback()), origin = 'http://127.0.0.1:8800'
  38. await agent.get('/api/realtime/capabilities').set('Host', '127.0.0.1:8800').expect(401)
  39. const boot = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  40. expect(boot.body.authRequired).toBe(true)
  41. const login = await agent.post('/api/app/login').set('Host', '127.0.0.1:8800').set('Origin', origin)
  42. .set('X-CSRF-Token', boot.body.csrfToken).send({ username: 'admin', password: 'admin' }).expect(200)
  43. await agent.put('/api/app/account/credentials').set('Host', '127.0.0.1:8800').set('Origin', origin)
  44. .set('X-CSRF-Token', login.body.csrfToken).send({ currentPassword: 'admin', newPassword: 'fixture-password', username: 'owner' }).expect(200)
  45. const ready = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  46. expect(ready.body).toMatchObject({ authRequired: true, authenticated: true, upstreamReady: true })
  47. expect(ready.body.profiles).toHaveLength(1)
  48. expect(JSON.stringify([ready.body, ready.headers])).not.toContain(token)
  49. expect(runtime.auth.upstreamCredentials()).toBeUndefined()
  50. await agent.post('/api/realtime/channels').set('Host', '127.0.0.1:8800').set('Origin', origin).send({ channel: 'chat' }).expect(403)
  51. await request(runtime.app.callback()).get('/api/realtime/capabilities').set('Host', '127.0.0.1:8800').expect(401)
  52. })
  53. it('forces admin/admin to change, then serves shared profiles through the service account', async () => {
  54. const home = mkdtempSync(join(tmpdir(), 'yaoyao-local-routes-'))
  55. roots.push(home)
  56. const config: ServerConfig = {
  57. host: '127.0.0.1', port: 8800, upstream: new URL('http://127.0.0.1:9119'),
  58. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  59. mediaOwner: 'tester', allowInsecureLan: false, insecureLan: false, production: false,
  60. superviseDashboard: true,
  61. upstreamUsername: 'service', upstreamPassword: 'fixture-password',
  62. }
  63. let wsTicketForwardedFor: string | null | undefined
  64. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  65. const path = new URL(input instanceof Request ? input.url : String(input)).pathname
  66. const headers = new Headers(init?.headers)
  67. if (path === '/api/status') return Response.json({ auth_required: true })
  68. if (path === '/api/auth/me') return headers.get('cookie')
  69. ? Response.json({ user_id: 'service' })
  70. : Response.json({ error: 'unauthorized' }, { status: 401 })
  71. if (path === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
  72. if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), {
  73. headers: { 'content-type': 'application/json', 'set-cookie': 'hermes_service=session; Path=/; HttpOnly' },
  74. })
  75. if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true }] })
  76. if (path === '/api/auth/ws-ticket') {
  77. wsTicketForwardedFor = headers.get('x-forwarded-for')
  78. return Response.json({ ticket: 'upstream-ticket' })
  79. }
  80. if (path === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [{ name: 'default', botName: '丫头' }] })
  81. return Response.json({ ok: true })
  82. }) as typeof fetch
  83. const runtime = createApplication({ config, fetchImpl })
  84. runtimes.push(runtime)
  85. const agent = request.agent(runtime.app.callback())
  86. const initial = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  87. const login = await agent.post('/api/app/login')
  88. .set('Host', '127.0.0.1:8800').set('Origin', 'http://127.0.0.1:8800')
  89. .set('X-CSRF-Token', initial.body.csrfToken).send({ username: 'admin', password: 'admin' }).expect(200)
  90. expect(login.body.user).toMatchObject({ username: 'admin', role: 'admin', mustChangePassword: true })
  91. expect(login.body.profiles).toEqual([])
  92. const changed = await agent.put('/api/app/account/credentials')
  93. .set('Host', '127.0.0.1:8800').set('Origin', 'http://127.0.0.1:8800')
  94. .set('X-CSRF-Token', login.body.csrfToken)
  95. .send({ currentPassword: 'admin', newPassword: 'new-password', username: 'owner' }).expect(200)
  96. expect(changed.body.user).toMatchObject({ username: 'owner', mustChangePassword: false })
  97. const ready = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  98. expect(ready.body).toMatchObject({ upstreamReady: true, serverKind: 'yaoyao-web' })
  99. expect(ready.body.profiles).toHaveLength(1)
  100. const connection = await agent.get('/api/app/admin/upstream-connection')
  101. .set('Host', '127.0.0.1:8800').expect(200)
  102. expect(connection.body).toMatchObject({
  103. endpoint: 'http://127.0.0.1:9119',
  104. authMode: 'password',
  105. networkScope: 'local',
  106. webNetworkScope: 'local',
  107. ready: true,
  108. })
  109. expect(connection.body.lastVerifiedAt).toEqual(expect.any(Number))
  110. await agent.post('/api/app/admin/users')
  111. .set('Host', '127.0.0.1:8800').set('Origin', 'http://127.0.0.1:8800')
  112. .set('X-CSRF-Token', ready.body.csrfToken)
  113. .send({ username: 'member', password: 'temporary-password' }).expect(201)
  114. const users = await agent.get('/api/app/admin/users').set('Host', '127.0.0.1:8800').expect(200)
  115. expect(users.body.items.map((user: { username: string }) => user.username)).toEqual(['owner', 'member'])
  116. expect(cookies(changed)).not.toContain('admin')
  117. const accountPairing = await agent.post('/api/app/account-pairings')
  118. .set('Host', '127.0.0.1:8800').set('Origin', 'http://127.0.0.1:8800')
  119. .set('X-CSRF-Token', ready.body.csrfToken).send({}).expect(201)
  120. const loginCode = new URL(accountPairing.body.qrPayload)
  121. expect(loginCode.hostname).toBe('login')
  122. const scanned = request.agent(runtime.app.callback())
  123. await scanned.post('/api/account-pair/v1/claim').set('Host', '127.0.0.1:8800')
  124. .send({ pairingId: loginCode.searchParams.get('id'), secret: loginCode.searchParams.get('secret') })
  125. .expect(201)
  126. const scannedIdentity = await scanned.get('/api/auth/me').set('Host', '127.0.0.1:8800').expect(200)
  127. expect(scannedIdentity.body).toMatchObject({ username: 'owner', role: 'admin' })
  128. await request(runtime.app.callback()).post('/api/account-pair/v1/claim')
  129. .set('Host', '127.0.0.1:8800')
  130. .send({ pairingId: loginCode.searchParams.get('id'), secret: loginCode.searchParams.get('secret') })
  131. .expect(409)
  132. const native = request.agent(runtime.app.callback())
  133. await native.get('/api/status').set('Host', '127.0.0.1:8800').expect(200, /yaoyao-web/)
  134. await native.post('/auth/password-login').set('Host', '127.0.0.1:8800')
  135. .send({ provider: 'basic', username: 'owner', password: 'new-password', next: '' }).expect(200)
  136. const identity = await native.get('/api/auth/me').set('Host', '127.0.0.1:8800').expect(200)
  137. expect(identity.body).toMatchObject({ username: 'owner', role: 'admin', server_kind: 'yaoyao-web' })
  138. const nativeProfiles = await native.get('/api/profiles').set('Host', '127.0.0.1:8800').expect(200)
  139. expect(nativeProfiles.body.profiles[0]).toMatchObject({
  140. name: 'default', description: '丫头', display_name: '丫头', agentName: '丫头',
  141. })
  142. await native.post('/api/auth/ws-ticket').set('Host', '127.0.0.1:8800').send({}).expect(410)
  143. expect(wsTicketForwardedFor).toBeUndefined()
  144. })
  145. it('lets one 8800 claim another 8800 as a direct child node', async () => {
  146. const registrations: unknown[] = []
  147. const make = (label: string) => {
  148. const home = mkdtempSync(join(tmpdir(), `yaoyao-${label}-`)); roots.push(home)
  149. const config: ServerConfig = {
  150. host: '127.0.0.1', port: 0, upstream: new URL('http://127.0.0.1:9119'),
  151. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  152. mediaOwner: 'tester', allowInsecureLan: true, insecureLan: true, production: false,
  153. superviseDashboard: true,
  154. upstreamUsername: 'service', upstreamPassword: 'fixture-password',
  155. }
  156. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  157. const path = new URL(input instanceof Request ? input.url : String(input)).pathname
  158. const headers = new Headers(init?.headers)
  159. if (path === '/api/status') return Response.json({ auth_required: true })
  160. if (path === '/api/auth/me') return headers.get('cookie') ? Response.json({ user_id: 'service' }) : Response.json({}, { status: 401 })
  161. if (path === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
  162. if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), { headers: { 'content-type': 'application/json', 'set-cookie': `service_${label}=session; Path=/; HttpOnly` } })
  163. if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true, model: 'test' }] })
  164. if (path === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [] })
  165. if (path === '/api/plugins/yaoyao/v1/nodes' && init?.method === 'POST') {
  166. registrations.push(JSON.parse(String(init.body))); return Response.json({ nodeId: JSON.parse(String(init.body)).nodeId })
  167. }
  168. return Response.json({ ok: true })
  169. }) as typeof fetch
  170. const app = createApplication({ config, fetchImpl })
  171. const node = createNodeServer(app); nodeRuntimes.push(node)
  172. return { app, node, config }
  173. }
  174. const child = make('child')
  175. const parent = make('parent')
  176. await Promise.all([child, parent].map(({ node, config }) => new Promise<void>(resolve => {
  177. node.server.listen(0, '127.0.0.1', () => {
  178. config.port = (node.server.address() as { port: number }).port
  179. resolve()
  180. })
  181. })))
  182. const authenticate = async (runtime: ApplicationRuntime, port: number) => {
  183. const agent = request.agent(runtime.app.callback())
  184. const initial = await agent.get('/api/app/bootstrap').set('Host', `127.0.0.1:${port}`)
  185. const login = await agent.post('/api/app/login').set('Host', `127.0.0.1:${port}`)
  186. .set('Origin', `http://127.0.0.1:${port}`).set('X-CSRF-Token', initial.body.csrfToken)
  187. .send({ username: 'admin', password: 'admin' })
  188. const changed = await agent.put('/api/app/account/credentials').set('Host', `127.0.0.1:${port}`)
  189. .set('Origin', `http://127.0.0.1:${port}`).set('X-CSRF-Token', login.body.csrfToken)
  190. .send({ currentPassword: 'admin', newPassword: 'new-password', username: 'admin' })
  191. const ready = await agent.get('/api/app/bootstrap').set('Host', `127.0.0.1:${port}`)
  192. return { agent, csrf: ready.body.csrfToken, origin: `http://127.0.0.1:${port}`, changed }
  193. }
  194. const childAuth = await authenticate(child.app, child.config.port)
  195. const parentAuth = await authenticate(parent.app, parent.config.port)
  196. const pairing = await childAuth.agent.post('/api/app/pairings').set('Host', `127.0.0.1:${child.config.port}`)
  197. .set('Origin', childAuth.origin).set('X-CSRF-Token', childAuth.csrf)
  198. .send({ scopes: ['agents.read', 'history.read', 'sessions.execute', 'groups.read', 'groups.execute'] }).expect(201)
  199. await parentAuth.agent.post('/api/app/groups/nodes/pair').set('Host', `127.0.0.1:${parent.config.port}`)
  200. .set('Origin', parentAuth.origin).set('X-CSRF-Token', parentAuth.csrf)
  201. .send({ qrPayload: pairing.body.qrPayload, name: '子 8800' }).expect(201)
  202. expect(registrations).toHaveLength(1)
  203. expect(registrations[0]).toMatchObject({ name: '子 8800', profiles: [{ name: 'default' }] })
  204. })
  205. })