localAuthRoutes.test.ts 10 KB

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