localAuthRoutes.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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, type ApplicationRuntime } from '../../src/server/app.js'
  7. import type { Server } from 'node:http'
  8. import type { ServerConfig } from '../../src/server/config.js'
  9. const roots: string[] = []
  10. const runtimes: ApplicationRuntime[] = []
  11. const servers: Server[] = []
  12. async function listen(runtime: ApplicationRuntime) {
  13. // Keep one listener for the whole scenario. Repeated implicit Supertest
  14. // listen/close cycles can race pooled HTTP connections on recent Node versions.
  15. const server = runtime.app.listen(0, '127.0.0.1'); servers.push(server)
  16. await new Promise<void>(resolve => server.once('listening', resolve))
  17. return server
  18. }
  19. afterEach(async () => {
  20. for (const server of servers.splice(0)) await new Promise<void>((resolve, reject) => {
  21. server.closeAllConnections(); server.close(error => error ? reject(error) : resolve())
  22. })
  23. for (const runtime of runtimes.splice(0)) runtime.close()
  24. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  25. })
  26. function cookies(response: request.Response): string {
  27. const values = response.headers['set-cookie'] as unknown as string[] | undefined
  28. return (values ?? []).map(value => value.split(';', 1)[0]).join('; ')
  29. }
  30. describe('15300 local authentication routes', () => {
  31. it('installs without upstream credentials while keeping local login and CSRF mandatory', async () => {
  32. const home = mkdtempSync(join(tmpdir(), 'yaoyao-local-token-')); roots.push(home)
  33. const token = 'fixture_local_only_session_token_123456'
  34. const config: ServerConfig = {
  35. host: '127.0.0.1', port: 15300, upstream: new URL('http://127.0.0.1:9119'),
  36. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  37. mediaOwner: 'tester', allowInsecureLan: false, insecureLan: false, production: false, superviseDashboard: true,
  38. }
  39. const runtime = createApplication({ config, fetchImpl: (async (input, init) => {
  40. const path = new URL(String(input)).pathname
  41. if (path === '/api/status') return Response.json({ auth_required: false })
  42. if (path === '/') return new Response(`<script>window.__HERMES_SESSION_TOKEN__="${token}";</script>`)
  43. if (new Headers(init?.headers).get('x-hermes-session-token') !== token) return Response.json({}, { status: 401 })
  44. return Response.json({ profiles: [{ name: 'default', is_default: true, display_name: '丫头' }] })
  45. }) as typeof fetch }); runtimes.push(runtime)
  46. expect(runtime.auth.upstreamCredentials()).toBeUndefined()
  47. const server = await listen(runtime)
  48. const agent = request.agent(server), origin = 'http://127.0.0.1:15300'
  49. await agent.get('/api/realtime/capabilities').set('Host', '127.0.0.1:15300').expect(401)
  50. const boot = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  51. expect(boot.body).toMatchObject({ authRequired: true, setupRequired: true })
  52. await agent.post('/api/app/login').set('Host', '127.0.0.1:15300').set('Origin', origin)
  53. .set('X-CSRF-Token', boot.body.csrfToken).send({ username: 'admin', password: 'admin' }).expect(401)
  54. const setup = await agent.post('/api/app/setup').set('Host', '127.0.0.1:15300').set('Origin', origin)
  55. .set('X-CSRF-Token', boot.body.csrfToken).send({ username: 'owner', password: 'fixture-password' }).expect(200)
  56. await agent.post('/api/app/setup').set('Host', '127.0.0.1:15300').set('Origin', origin)
  57. .set('X-CSRF-Token', setup.body.csrfToken).send({ username: 'other', password: 'fixture-password' }).expect(409)
  58. const ready = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  59. expect(ready.body).toMatchObject({ authRequired: true, authenticated: true, upstreamReady: true })
  60. expect(ready.body.profiles).toHaveLength(1)
  61. expect(JSON.stringify([ready.body, ready.headers])).not.toContain(token)
  62. expect(runtime.auth.upstreamCredentials()).toBeUndefined()
  63. const avatar = 'data:image/png;base64,aGVsbG8='
  64. const avatarUpdate = await agent.put('/api/app/account/avatar').set('Host', '127.0.0.1:15300').set('Origin', origin)
  65. .set('X-CSRF-Token', ready.body.csrfToken).send({ avatar }).expect(200)
  66. expect(avatarUpdate.body.user.avatar).toBe(avatar)
  67. expect((await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)).body.user.avatar).toBe(avatar)
  68. expect((await agent.get('/api/auth/me').set('Host', '127.0.0.1:15300').expect(200)).body.avatar).toBe(avatar)
  69. await agent.put('/api/app/account/avatar').set('Host', '127.0.0.1:15300').set('Origin', origin)
  70. .set('X-CSRF-Token', ready.body.csrfToken).send({ avatar: 'https://example.test/avatar.png' }).expect(400)
  71. await agent.post('/api/realtime/channels').set('Host', '127.0.0.1:15300').set('Origin', origin).send({ channel: 'chat' }).expect(403)
  72. await request(server).get('/api/realtime/capabilities').set('Host', '127.0.0.1:15300').expect(401)
  73. })
  74. it('creates an explicit administrator, then serves shared profiles through the service account', async () => {
  75. const home = mkdtempSync(join(tmpdir(), 'yaoyao-local-routes-'))
  76. roots.push(home)
  77. const config: ServerConfig = {
  78. host: '127.0.0.1', port: 15300, upstream: new URL('http://127.0.0.1:9119'),
  79. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  80. mediaOwner: 'tester', allowInsecureLan: false, insecureLan: false, production: false,
  81. superviseDashboard: true,
  82. upstreamUsername: 'service', upstreamPassword: 'fixture-password',
  83. }
  84. let wsTicketForwardedFor: string | null | undefined
  85. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  86. const path = new URL(input instanceof Request ? input.url : String(input)).pathname
  87. const headers = new Headers(init?.headers)
  88. if (path === '/api/status') return Response.json({ auth_required: true })
  89. if (path === '/api/auth/me') return headers.get('cookie')
  90. ? Response.json({ user_id: 'service' })
  91. : Response.json({ error: 'unauthorized' }, { status: 401 })
  92. if (path === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
  93. if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), {
  94. headers: { 'content-type': 'application/json', 'set-cookie': 'hermes_service=session; Path=/; HttpOnly' },
  95. })
  96. if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true, display_name: '丫头' }] })
  97. if (path === '/api/auth/ws-ticket') {
  98. wsTicketForwardedFor = headers.get('x-forwarded-for')
  99. return Response.json({ ticket: 'upstream-ticket' })
  100. }
  101. if (path === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [{ name: 'default', botName: '丫头' }] })
  102. return Response.json({ ok: true })
  103. }) as typeof fetch
  104. const runtime = createApplication({ config, fetchImpl })
  105. runtimes.push(runtime)
  106. const server = await listen(runtime)
  107. const agent = request.agent(server)
  108. const initial = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  109. const setup = await agent.post('/api/app/setup')
  110. .set('Host', '127.0.0.1:15300').set('Origin', 'http://127.0.0.1:15300')
  111. .set('X-CSRF-Token', initial.body.csrfToken).send({ username: 'owner', password: 'new-password' }).expect(200)
  112. expect(setup.body.user).toMatchObject({ username: 'owner', role: 'admin', mustChangePassword: false })
  113. expect(setup.body.profiles).toHaveLength(1)
  114. const ready = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  115. expect(ready.body).toMatchObject({ upstreamReady: true, serverKind: 'yaoyao-web' })
  116. expect(ready.body.profiles).toHaveLength(1)
  117. const connection = await agent.get('/api/app/admin/upstream-connection')
  118. .set('Host', '127.0.0.1:15300').expect(200)
  119. expect(connection.body).toMatchObject({
  120. endpoint: 'http://127.0.0.1:9119',
  121. authMode: 'password',
  122. networkScope: 'local',
  123. webNetworkScope: 'local',
  124. ready: true,
  125. })
  126. expect(connection.body.lastVerifiedAt).toEqual(expect.any(Number))
  127. await agent.post('/api/app/admin/users')
  128. .set('Host', '127.0.0.1:15300').set('Origin', 'http://127.0.0.1:15300')
  129. .set('X-CSRF-Token', ready.body.csrfToken)
  130. .send({ username: 'member', password: 'temporary-password' }).expect(201)
  131. const users = await agent.get('/api/app/admin/users').set('Host', '127.0.0.1:15300').expect(200)
  132. expect(users.body.items.map((user: { username: string }) => user.username)).toEqual(['owner', 'member'])
  133. expect(cookies(setup)).not.toContain('admin')
  134. const accountPairing = await agent.post('/api/app/account-pairings')
  135. .set('Host', '127.0.0.1:15300').set('Origin', 'http://127.0.0.1:15300')
  136. .set('X-CSRF-Token', ready.body.csrfToken).send({}).expect(201)
  137. const loginCode = new URL(accountPairing.body.qrPayload)
  138. expect(loginCode.hostname).toBe('login')
  139. const scanned = request.agent(server)
  140. await scanned.post('/api/account-pair/v1/claim').set('Host', '127.0.0.1:15300')
  141. .send({ pairingId: loginCode.searchParams.get('id'), secret: loginCode.searchParams.get('secret') })
  142. .expect(201)
  143. const scannedIdentity = await scanned.get('/api/auth/me').set('Host', '127.0.0.1:15300').expect(200)
  144. expect(scannedIdentity.body).toMatchObject({ username: 'owner', role: 'admin' })
  145. await request(server).post('/api/account-pair/v1/claim')
  146. .set('Host', '127.0.0.1:15300')
  147. .send({ pairingId: loginCode.searchParams.get('id'), secret: loginCode.searchParams.get('secret') })
  148. .expect(409)
  149. const native = request.agent(server)
  150. await native.get('/api/status').set('Host', '127.0.0.1:15300').expect(200, /yaoyao-web/)
  151. await native.post('/auth/password-login').set('Host', '127.0.0.1:15300')
  152. .send({ provider: 'basic', username: 'owner', password: 'new-password', next: '' }).expect(200)
  153. const identity = await native.get('/api/auth/me').set('Host', '127.0.0.1:15300').expect(200)
  154. expect(identity.body).toMatchObject({ username: 'owner', role: 'admin', server_kind: 'yaoyao-web' })
  155. const nativeProfiles = await native.get('/api/profiles').set('Host', '127.0.0.1:15300').expect(200)
  156. expect(nativeProfiles.body.profiles[0]).toMatchObject({
  157. name: 'default', description: '丫头', display_name: '丫头', agentName: '丫头',
  158. })
  159. await native.post('/api/auth/ws-ticket').set('Host', '127.0.0.1:15300').send({}).expect(410)
  160. expect(wsTicketForwardedFor).toBeUndefined()
  161. })
  162. })