localAuthRoutes.test.ts 11 KB

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