Files
XHChat/tests/account-security.test.mjs

78 lines
4.9 KiB
JavaScript

import assert from 'node:assert/strict'
import { generateKeyPairSync, randomBytes, sign } from 'node:crypto'
import { once } from 'node:events'
import test from 'node:test'
import { WebSocket } from 'ws'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
async function call(path, method = 'GET', token, body, status = 200) {
const response = await fetch(base + '/api/v1' + path, {
method, headers: { ...(token && { Authorization: 'Bearer ' + token }), ...(body && { 'Content-Type': 'application/json' }) },
body: body && JSON.stringify(body), signal: AbortSignal.timeout(10000),
})
assert.equal(response.status, status, await response.clone().text())
return response.status === 204 ? undefined : response.json()
}
test('密码修改、会话退出、设备重命名与登录记录隔离', { timeout: 30000 }, async () => {
const username = 'safe_' + randomBytes(6).toString('hex')
const password = randomBytes(24).toString('hex')
const nextPassword = randomBytes(24).toString('hex')
const pair = generateKeyPairSync('ed25519')
async function auth(mode, name = username, pass = password, keys = pair, status = 200) {
const { challenge } = await call('/auth/challenge', 'POST')
return call('/auth/' + mode, 'POST', '', { username: name, password: pass, deviceName: '安全测试设备', platform: 'web', challenge,
publicKey: keys.publicKey.export({ format: 'jwk' }).x,
signature: sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), keys.privateKey).toString('base64url'),
}, status)
}
const first = await auth('register', username, password, pair, 201)
const second = await auth('login', username, password, generateKeyPairSync('ed25519'))
const outsider = await auth('register', 'other_' + randomBytes(6).toString('hex'), password, pair, 201)
await call('/devices/' + first.device.id, 'POST', outsider.token, { name: '越权修改' }, 404)
await call('/devices/' + first.device.id, 'POST', first.token, { name: '\n' }, 400)
await call('/devices/' + first.device.id, 'POST', first.token, { name: '我的电脑' }, 204)
const renamed = await auth('login')
assert.equal(renamed.device.name, '我的电脑')
assert.equal(renamed.device.id, first.device.id)
const history = await call('/auth/history', 'GET', first.token)
assert.equal(history.length, 3)
assert.equal(history[0].deviceName, '我的电脑')
assert.deepEqual(history.map((item) => item.currentDevice), [true, false, true])
assert.equal((await call('/auth/history', 'GET', outsider.token)).length, 1)
assert.deepEqual(Object.keys(history[0]).sort(), ['createdAt','currentDevice','deviceName','id','platform'])
const { ticket } = await call('/realtime/ticket', 'POST', second.token)
const socket = new WebSocket(base.replace(/^http/, 'ws') + '/api/v1/realtime', ['xhchat.v1', 'ticket.' + ticket], { origin: base })
try {
await once(socket, 'message', { signal: AbortSignal.timeout(5000) })
const closed = once(socket, 'close', { signal: AbortSignal.timeout(9000) })
await call('/auth/logout-others', 'POST', first.token, {}, 204)
await call('/me', 'GET', first.token)
await call('/me', 'GET', second.token, undefined, 401)
await call('/me', 'GET', renamed.token, undefined, 401)
assert.equal((await closed)[0], 1008)
await call('/auth/password', 'POST', first.token, { currentPassword: password, newPassword: 'short' }, 400)
await call('/auth/password', 'POST', first.token, { currentPassword: password + 'x', newPassword: nextPassword }, 403)
await call('/me', 'GET', first.token)
const activeSecond = await auth('login', username, password, generateKeyPairSync('ed25519'))
const [changed, racingLogin] = await Promise.all([
call('/auth/password', 'POST', first.token, { currentPassword: password, newPassword: nextPassword }, 204),
(async () => { const { challenge } = await call('/auth/challenge', 'POST'); return fetch(base + '/api/v1/auth/login', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username,password,challenge,deviceName:'并发登录',platform:'web',
publicKey: pair.publicKey.export({format:'jwk'}).x,
signature: sign(null,Buffer.from('XHChat device authentication v1\n'+challenge),pair.privateKey).toString('base64url') }),
}) })(),
])
assert.equal(changed, undefined)
assert.ok([200,401].includes(racingLogin.status))
if (racingLogin.status === 200) await call('/me','GET',(await racingLogin.json()).token,undefined,401)
await call('/me', 'GET', first.token, undefined, 401)
await call('/me', 'GET', activeSecond.token, undefined, 401)
await auth('login', username, password, pair, 401)
const restored = await auth('login', username, nextPassword)
assert.equal(restored.device.id, first.device.id)
assert.equal(restored.device.name, '我的电脑')
await call('/me', 'GET', outsider.token)
} finally { socket.terminate() }
})