remote-login.test.mjs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import {test} from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import {createServer} from 'node:http'
  4. import {randomUUID,randomBytes} from 'node:crypto'
  5. import {remoteSession,enrollDesktopHost,normalizeServerURL,inspectServer} from './remote-login.mjs'
  6. test('server inspection requests local login metadata without binding Hermes', async () => {
  7. const calls = []
  8. const info = { authenticated: true, csrfToken: 'fixture', serverKind: 'yaoyao-web', user: { username: 'admin' } }
  9. const result = await inspectServer('http://127.0.0.1:15300', async (url, options) => {
  10. calls.push({ path: url.pathname + url.search, method: options.method ?? 'GET' })
  11. return Response.json(info)
  12. })
  13. assert.deepEqual(result, info)
  14. assert.deepEqual(calls, [{ path: '/api/app/bootstrap?inspectOnly=1', method: 'GET' }])
  15. })
  16. test('server addresses are normalized like browser URLs',()=>{
  17. assert.equal(normalizeServerURL('192.168.1.10:15300'),'http://192.168.1.10:15300')
  18. assert.equal(normalizeServerURL('http://192.168.1.10:15300/'),'http://192.168.1.10:15300')
  19. assert.equal(normalizeServerURL('https://yaoyao.example.com'),'https://yaoyao.example.com')
  20. assert.throws(()=>normalizeServerURL(''),/服务器地址/)
  21. assert.throws(()=>normalizeServerURL('https://user:pass@example.com'),/无效/)
  22. assert.throws(()=>normalizeServerURL('http://example.com/path'),/无效/)
  23. assert.throws(()=>normalizeServerURL('ftp://example.com'),/无效/)
  24. })
  25. async function fakeServer(){
  26. const csrf=randomUUID(),session=randomBytes(24).toString('base64url'),token=randomBytes(32).toString('base64url'),hostId=randomUUID()
  27. const requests=[]
  28. const server=createServer((req,res)=>{
  29. const chunks=[];req.on('data',chunk=>chunks.push(chunk));req.on('end',()=>{
  30. const body=Buffer.concat(chunks).toString()
  31. requests.push({method:req.method,url:req.url,origin:req.headers.origin,csrf:req.headers['x-csrf-token'],cookie:req.headers.cookie??'',body})
  32. const json=payload=>{res.setHeader('content-type','application/json');res.end(JSON.stringify(payload))}
  33. if(req.url==='/api/app/bootstrap'&&(req.method==='GET'||req.method==='HEAD')){res.setHeader('set-cookie','csrf=test-csrf; Path=/; HttpOnly');return json({authRequired:true,csrfToken:csrf})}
  34. if(req.url==='/api/app/login'&&req.method==='POST'){
  35. const credentials=JSON.parse(body||'{}')
  36. if(credentials.username!=='admin'||credentials.password!=='pass'){res.statusCode=401;return json({error:'invalid'})}
  37. if(req.headers['x-csrf-token']!==csrf||!String(req.headers.cookie).includes('csrf=')){res.statusCode=403;return json({error:'csrf'})}
  38. res.setHeader('set-cookie',[`session=${session}; Path=/; HttpOnly`,`csrf=${csrf}.sig; Path=/; HttpOnly`])
  39. return json({user:{id:randomUUID(),username:'admin',role:'admin'},csrfToken:csrf+'-rotated'})
  40. }
  41. if(req.url==='/api/app/admin/desktop-hosts'&&req.method==='POST'){
  42. if(req.headers['x-csrf-token']!==csrf+'-rotated'||!String(req.headers.cookie).includes(`session=${session}`)){res.statusCode=403;return json({error:'session'})}
  43. return json({host:{id:hostId,name:JSON.parse(body||'{}').name,enabled:true},token})
  44. }
  45. res.statusCode=404;json({error:'not found'})
  46. })
  47. })
  48. await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
  49. return {server,url:`http://127.0.0.1:${server.address().port}`,requests,csrf,session,token,hostId}
  50. }
  51. test('logs in with username and password and enrolls this Mac as a computer',async()=>{
  52. const fake=await fakeServer()
  53. try{
  54. const auth=await remoteSession(fake.url,{username:'admin',password:'pass'})
  55. assert.equal(auth.user.role,'admin')
  56. assert.equal(auth.origin,fake.url)
  57. assert.ok(auth.cookies.some(([name])=>name==='session'))
  58. const installId='22222222-2222-4222-8222-222222222222',previousHostId='33333333-3333-4333-8333-333333333333'
  59. const enrollment=await enrollDesktopHost(auth,{name:'书房 iMac',installId,previousHostId})
  60. assert.equal(enrollment.host.id,fake.hostId)
  61. assert.equal(enrollment.token,fake.token)
  62. const [bootstrap,login,enroll]=fake.requests
  63. assert.equal(bootstrap.url,'/api/app/bootstrap')
  64. assert.equal(login.origin,fake.url)
  65. assert.equal(login.csrf,fake.csrf)
  66. assert.equal(enroll.csrf,fake.csrf+'-rotated')
  67. assert.ok(enroll.cookie.includes(`session=${fake.session}`))
  68. assert.deepEqual(JSON.parse(enroll.body),{name:'书房 iMac',installId,previousHostId})
  69. }finally{
  70. fake.server.close();fake.server.closeAllConnections?.()
  71. }
  72. })
  73. test('wrong credentials and non-admin accounts surface clear errors',async()=>{
  74. const fake=await fakeServer()
  75. try{
  76. await assert.rejects(()=>remoteSession(fake.url,{username:'admin',password:'wrong'}),/用户名或密码不正确/)
  77. await assert.rejects(()=>remoteSession(fake.url,{username:'',password:'pass'}),/用户名和密码/)
  78. const auth={origin:fake.url,csrfToken:'stale',cookies:[['session','x']]}
  79. await assert.rejects(()=>enrollDesktopHost(auth,{name:'x'}),/管理员账号|注册电脑失败/)
  80. }finally{
  81. fake.server.close();fake.server.closeAllConnections?.()
  82. }
  83. })
  84. test('native login preserves cookie expiry, scope and same-site policy', async () => {
  85. let request = 0
  86. const before = Date.now() / 1000
  87. const auth = await remoteSession('https://server.test', { username: 'admin', password: 'password' }, async () => {
  88. if (++request === 1) return new Response(JSON.stringify({ csrfToken: 'fixture' }), { headers: { 'set-cookie': 'csrf=one; Path=/; HttpOnly; Secure; SameSite=Strict' } })
  89. return new Response(JSON.stringify({ user: { id: 'admin', role: 'admin' } }), { headers: { 'set-cookie': 'session=two; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Strict' } })
  90. })
  91. const session = auth.cookieDetails.find(cookie => cookie.name === 'session')
  92. assert.equal(session.secure, true); assert.equal(session.httpOnly, true); assert.equal(session.sameSite, 'strict')
  93. assert.equal(session.path, '/')
  94. assert.ok(session.expirationDate >= before + 3600 && session.expirationDate <= Date.now() / 1000 + 3600)
  95. assert.equal(auth.cookieDetails.find(cookie => cookie.name === 'csrf').expirationDate, undefined)
  96. })
  97. test('pending approval is not mislabeled as a bad password', async () => {
  98. let calls = 0
  99. await assert.rejects(() => remoteSession('https://server.test', { username: 'child', password: 'password' }, async () => {
  100. if (++calls === 1) return Response.json({ csrfToken: 'csrf' })
  101. return Response.json({ code: 'account_pending_approval', error: '账号尚未开通,请等待管理员开通。' }, { status: 403 })
  102. }), /等待管理员开通/)
  103. })
  104. test('registration uses only anonymous bootstrap and does not return a session', async () => {
  105. const { remoteRegistration } = await import('./remote-login.mjs')
  106. const calls = []
  107. await remoteRegistration('https://server.test', { username: ' child ', password: 'password' }, async (url, options) => {
  108. calls.push(url.pathname)
  109. if (url.pathname.endsWith('bootstrap')) return Response.json({ registrationAvailable: true, csrfToken: 'csrf' }, { headers: { 'set-cookie': 'csrf-cookie=value; Path=/; HttpOnly' } })
  110. assert.equal(options.headers.origin, 'https://server.test')
  111. assert.equal(options.headers['x-csrf-token'], 'csrf')
  112. assert.match(options.headers.cookie, /csrf-cookie=value/)
  113. assert.deepEqual(JSON.parse(options.body), { username: 'child', password: 'password' })
  114. return Response.json({ registrationStatus: 'pending' }, { status: 201 })
  115. })
  116. assert.deepEqual(calls, ['/api/app/bootstrap', '/api/app/register'])
  117. })