localAuthRoutes.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. await agent.post('/api/app/admin/users')
  68. .set('Host', '127.0.0.1:8800').set('Origin', 'http://127.0.0.1:8800')
  69. .set('X-CSRF-Token', ready.body.csrfToken)
  70. .send({ username: 'member', password: 'temporary-password' }).expect(201)
  71. const users = await agent.get('/api/app/admin/users').set('Host', '127.0.0.1:8800').expect(200)
  72. expect(users.body.items.map((user: { username: string }) => user.username)).toEqual(['owner', 'member'])
  73. expect(cookies(changed)).not.toContain('admin')
  74. const accountPairing = await agent.post('/api/app/account-pairings')
  75. .set('Host', '127.0.0.1:8800').set('Origin', 'http://127.0.0.1:8800')
  76. .set('X-CSRF-Token', ready.body.csrfToken).send({}).expect(201)
  77. const loginCode = new URL(accountPairing.body.qrPayload)
  78. expect(loginCode.hostname).toBe('login')
  79. const scanned = request.agent(runtime.app.callback())
  80. await scanned.post('/api/account-pair/v1/claim').set('Host', '127.0.0.1:8800')
  81. .send({ pairingId: loginCode.searchParams.get('id'), secret: loginCode.searchParams.get('secret') })
  82. .expect(201)
  83. const scannedIdentity = await scanned.get('/api/auth/me').set('Host', '127.0.0.1:8800').expect(200)
  84. expect(scannedIdentity.body).toMatchObject({ username: 'owner', role: 'admin' })
  85. await request(runtime.app.callback()).post('/api/account-pair/v1/claim')
  86. .set('Host', '127.0.0.1:8800')
  87. .send({ pairingId: loginCode.searchParams.get('id'), secret: loginCode.searchParams.get('secret') })
  88. .expect(409)
  89. const native = request.agent(runtime.app.callback())
  90. await native.get('/api/status').set('Host', '127.0.0.1:8800').expect(200, /yaoyao-web/)
  91. await native.post('/auth/password-login').set('Host', '127.0.0.1:8800')
  92. .send({ provider: 'basic', username: 'owner', password: 'new-password', next: '' }).expect(200)
  93. const identity = await native.get('/api/auth/me').set('Host', '127.0.0.1:8800').expect(200)
  94. expect(identity.body).toMatchObject({ username: 'owner', role: 'admin', server_kind: 'yaoyao-web' })
  95. const nativeProfiles = await native.get('/api/profiles').set('Host', '127.0.0.1:8800').expect(200)
  96. expect(nativeProfiles.body.profiles[0]).toMatchObject({
  97. name: 'default', description: '丫头', display_name: '丫头', agentName: '丫头',
  98. })
  99. await native.post('/api/auth/ws-ticket').set('Host', '127.0.0.1:8800').send({}).expect(200, /upstream-ticket/)
  100. expect(wsTicketForwardedFor).toBeNull()
  101. })
  102. it('lets one 8800 claim another 8800 as a direct child node', async () => {
  103. const registrations: unknown[] = []
  104. const make = (label: string) => {
  105. const home = mkdtempSync(join(tmpdir(), `yaoyao-${label}-`)); roots.push(home)
  106. const config: ServerConfig = {
  107. host: '127.0.0.1', port: 0, upstream: new URL('http://127.0.0.1:9119'),
  108. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  109. mediaOwner: 'tester', allowInsecureLan: true, insecureLan: true, production: false,
  110. superviseDashboard: true,
  111. }
  112. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  113. const path = new URL(input instanceof Request ? input.url : String(input)).pathname
  114. const headers = new Headers(init?.headers)
  115. if (path === '/api/status') return Response.json({ auth_required: true })
  116. if (path === '/api/auth/me') return headers.get('cookie') ? Response.json({ user_id: 'service' }) : Response.json({}, { status: 401 })
  117. if (path === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
  118. if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), { headers: { 'content-type': 'application/json', 'set-cookie': `service_${label}=session; Path=/; HttpOnly` } })
  119. if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true, model: 'test' }] })
  120. if (path === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [] })
  121. if (path === '/api/plugins/yaoyao/v1/nodes' && init?.method === 'POST') {
  122. registrations.push(JSON.parse(String(init.body))); return Response.json({ nodeId: JSON.parse(String(init.body)).nodeId })
  123. }
  124. return Response.json({ ok: true })
  125. }) as typeof fetch
  126. const app = createApplication({ config, fetchImpl })
  127. const node = createNodeServer(app); nodeRuntimes.push(node)
  128. return { app, node, config }
  129. }
  130. const child = make('child')
  131. const parent = make('parent')
  132. await Promise.all([child, parent].map(({ node, config }) => new Promise<void>(resolve => {
  133. node.server.listen(0, '127.0.0.1', () => {
  134. config.port = (node.server.address() as { port: number }).port
  135. resolve()
  136. })
  137. })))
  138. const authenticate = async (runtime: ApplicationRuntime, port: number) => {
  139. const agent = request.agent(runtime.app.callback())
  140. const initial = await agent.get('/api/app/bootstrap').set('Host', `127.0.0.1:${port}`)
  141. const login = await agent.post('/api/app/login').set('Host', `127.0.0.1:${port}`)
  142. .set('Origin', `http://127.0.0.1:${port}`).set('X-CSRF-Token', initial.body.csrfToken)
  143. .send({ username: 'admin', password: 'admin' })
  144. const changed = await agent.put('/api/app/account/credentials').set('Host', `127.0.0.1:${port}`)
  145. .set('Origin', `http://127.0.0.1:${port}`).set('X-CSRF-Token', login.body.csrfToken)
  146. .send({ currentPassword: 'admin', newPassword: 'new-password', username: 'admin' })
  147. const ready = await agent.get('/api/app/bootstrap').set('Host', `127.0.0.1:${port}`)
  148. return { agent, csrf: ready.body.csrfToken, origin: `http://127.0.0.1:${port}`, changed }
  149. }
  150. const childAuth = await authenticate(child.app, child.config.port)
  151. const parentAuth = await authenticate(parent.app, parent.config.port)
  152. const pairing = await childAuth.agent.post('/api/app/pairings').set('Host', `127.0.0.1:${child.config.port}`)
  153. .set('Origin', childAuth.origin).set('X-CSRF-Token', childAuth.csrf)
  154. .send({ scopes: ['agents.read', 'history.read', 'sessions.execute', 'groups.read', 'groups.execute'] }).expect(201)
  155. await parentAuth.agent.post('/api/app/groups/nodes/pair').set('Host', `127.0.0.1:${parent.config.port}`)
  156. .set('Origin', parentAuth.origin).set('X-CSRF-Token', parentAuth.csrf)
  157. .send({ qrPayload: pairing.body.qrPayload, name: '子 8800' }).expect(201)
  158. expect(registrations).toHaveLength(1)
  159. expect(registrations[0]).toMatchObject({ name: '子 8800', profiles: [{ name: 'default' }] })
  160. })
  161. })