499 lines
30 KiB
JavaScript
499 lines
30 KiB
JavaScript
import assert from 'node:assert/strict'
|
|
import { generateKeyPairSync, randomBytes, randomUUID, 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'
|
|
|
|
function call(path, method = 'GET', token, body) {
|
|
return fetch(base + '/api/v1' + path, {
|
|
method,
|
|
headers: {
|
|
...(token && { Authorization: 'Bearer ' + token }),
|
|
...(body && { 'Content-Type': 'application/json' }),
|
|
},
|
|
body: body && JSON.stringify(body),
|
|
signal: AbortSignal.timeout(10_000),
|
|
})
|
|
}
|
|
|
|
async function json(path, method, token, body, status = 200) {
|
|
const response = await call(path, method, token, body)
|
|
assert.equal(response.status, status, await response.clone().text())
|
|
return response.json()
|
|
}
|
|
|
|
async function authenticate(mode, username, password, { publicKey, privateKey } = generateKeyPairSync('ed25519')) {
|
|
const { challenge } = await json('/auth/challenge', 'POST')
|
|
return json('/auth/' + mode, 'POST', null, {
|
|
username,
|
|
password,
|
|
deviceName: '投递验收设备',
|
|
platform: 'web',
|
|
challenge,
|
|
publicKey: publicKey.export({ format: 'jwk' }).x,
|
|
signature: sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), privateKey).toString('base64url'),
|
|
}, mode === 'register' ? 201 : 200)
|
|
}
|
|
|
|
function register(keys, password = randomBytes(24).toString('hex')) {
|
|
return authenticate('register', 'qa_' + randomBytes(6).toString('hex'), password, keys)
|
|
}
|
|
|
|
async function contact(actor, target, action) {
|
|
const reply = await call('/contacts/' + target.user.id, 'POST', actor.token, { action })
|
|
assert.equal(reply.status, 204, await reply.text())
|
|
}
|
|
|
|
async function watchRealtime(actor, t) {
|
|
const { ticket } = await json('/realtime/ticket', 'POST', actor.token)
|
|
const ws = new WebSocket(base.replace(/^http/, 'ws') + '/api/v1/realtime', ['xhchat.v1', 'ticket.' + ticket], { origin: base })
|
|
t.after(() => ws.terminate())
|
|
assert.deepEqual(JSON.parse((await once(ws, 'message', { signal: AbortSignal.timeout(4000) }))[0]),
|
|
{ type: 'ready', deviceId: actor.device.id })
|
|
return ws
|
|
}
|
|
|
|
// Opaque fixture with the MLS header. Crypto interoperability is tested separately in crypto/.
|
|
function frame(kind = 2) {
|
|
return Buffer.concat([Buffer.from([0, 1, 0, kind]), randomBytes(96)]).toString('base64')
|
|
}
|
|
|
|
test('群组邀请、授权、成员移除、版本变更与实时提示', { timeout: 25_000 }, async (t) => {
|
|
const owner = await register()
|
|
const member = await register()
|
|
const other = await register()
|
|
const group = await json('/groups', 'POST', owner.token, { name: '发布验收群' }, 201)
|
|
const path = '/groups/' + group.id
|
|
const preferences = path + '/preferences'
|
|
const act = async (actor, action, target, expected = 204, name) => {
|
|
const reply = await call(path, 'POST', actor.token, { action, target, name })
|
|
assert.equal(reply.status, expected, await reply.text())
|
|
}
|
|
await json(path, 'GET', other.token, undefined, 404)
|
|
await act(owner, 'invite', member.user.id, 409)
|
|
await contact(owner, member, 'request')
|
|
await contact(member, owner, 'accept')
|
|
const [ownerSocket, memberSocket, otherSocket] = await Promise.all([owner, member, other].map((actor) => watchRealtime(actor, t)))
|
|
const unrelated = []
|
|
otherSocket.on('message', (data) => unrelated.push(JSON.parse(data)))
|
|
async function expectHint(sockets, action) {
|
|
const pending = Promise.all(sockets.map((socket) => once(socket, 'message', { signal: AbortSignal.timeout(4000) })))
|
|
const [events] = await Promise.all([pending, action()])
|
|
for (const [data] of events) assert.deepEqual(JSON.parse(data), { type: 'group_list_changed' })
|
|
}
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id))
|
|
const invitation = await json(path, 'GET', member.token)
|
|
assert.equal(invitation.state, 'invited')
|
|
await json(preferences, 'POST', member.token, { muted: true }, 404)
|
|
await json(preferences, 'POST', other.token, { pinned: true }, 404)
|
|
assert.deepEqual(invitation.members, [])
|
|
assert.equal(invitation.membershipVersion, '1')
|
|
await expectHint([ownerSocket, memberSocket], () => act(member, 'decline'))
|
|
await json(path, 'GET', member.token, undefined, 404)
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id))
|
|
await expectHint([ownerSocket, memberSocket], () => act(member, 'accept'))
|
|
const active = await json(path, 'GET', member.token)
|
|
assert.equal(active.pinned, false)
|
|
assert.equal(active.muted, false)
|
|
const preferenceHint = once(memberSocket, 'message', { signal: AbortSignal.timeout(4000) })
|
|
assert.deepEqual(await json(preferences, 'POST', member.token, { pinned: true, muted: true }), { pinned: true, muted: true })
|
|
assert.deepEqual(JSON.parse((await preferenceHint)[0]), { type: 'group_list_changed' })
|
|
const [ownView, otherView] = await Promise.all([member, owner].map((actor) => json(path, 'GET', actor.token)))
|
|
assert.deepEqual([ownView.pinned, ownView.muted, otherView.pinned, otherView.muted], [true, true, false, false])
|
|
let nextGroup
|
|
await expectHint([memberSocket], async () => {
|
|
nextGroup = await json('/groups', 'POST', member.token, { name: '较新的群' }, 201)
|
|
})
|
|
assert.deepEqual((await json('/groups', 'GET', member.token)).map((item) => item.id), [group.id, nextGroup.id])
|
|
await expectHint([memberSocket], async () => {
|
|
assert.equal((await call('/groups/' + nextGroup.id, 'POST', member.token, { action: 'disband' })).status, 204)
|
|
})
|
|
assert.equal(active.membershipVersion, '2')
|
|
assert.deepEqual(active.members.map((item) => item.role).sort(), ['member', 'owner'])
|
|
await act(member, 'transfer', owner.user.id, 409)
|
|
await act(member, 'remove', owner.user.id, 409)
|
|
await act(member, 'rename', undefined, 409, '未授权名称')
|
|
const candidate = await register()
|
|
for (const [actor, target, action] of [[owner, candidate, 'request'], [candidate, owner, 'accept']]) {
|
|
const pending = once(ownerSocket, 'message', { signal: AbortSignal.timeout(4000) })
|
|
const [[data]] = await Promise.all([pending, contact(actor, target, action)])
|
|
assert.deepEqual(JSON.parse(data), { type: 'contacts_changed' })
|
|
}
|
|
const candidateSocket = await watchRealtime(candidate, t)
|
|
const ordinaryMemberEvents = []
|
|
const recordMemberEvent = (data) => ordinaryMemberEvents.push(JSON.parse(data))
|
|
memberSocket.on('message', recordMemberEvent)
|
|
await expectHint([ownerSocket, candidateSocket], () => act(owner, 'invite', candidate.user.id))
|
|
assert.deepEqual((await json(path, 'GET', member.token)).members.map((entry) => entry.state), ['active', 'active'])
|
|
await expectHint([ownerSocket, candidateSocket], () => act(candidate, 'decline'))
|
|
memberSocket.off('message', recordMemberEvent)
|
|
assert.deepEqual(ordinaryMemberEvents, [])
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'promote', member.user.id))
|
|
await expectHint([ownerSocket, memberSocket], () => act(member, 'rename', undefined, 204, '管理员改名'))
|
|
const renamed = await json(path, 'GET', owner.token)
|
|
assert.equal(renamed.name, '管理员改名')
|
|
assert.equal(renamed.membershipVersion, '2')
|
|
await act(member, 'transfer', owner.user.id, 409)
|
|
await act(owner, 'transfer', other.user.id, 409)
|
|
await act(owner, 'transfer', owner.user.id, 409)
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'transfer', member.user.id))
|
|
assert.equal((await json(path, 'GET', owner.token)).role, 'member')
|
|
const newOwner = await json(path, 'GET', member.token)
|
|
assert.equal(newOwner.role, 'owner')
|
|
assert.equal(newOwner.membershipVersion, '3')
|
|
await act(owner, 'disband', undefined, 409)
|
|
await expectHint([ownerSocket, memberSocket], () => act(member, 'transfer', owner.user.id))
|
|
await act(member, 'disband', undefined, 409)
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'remove', member.user.id))
|
|
await json(path, 'GET', member.token, undefined, 404)
|
|
assert.deepEqual(await json('/groups', 'GET', member.token), [])
|
|
assert.equal((await json(path, 'GET', owner.token)).membershipVersion, '5')
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id))
|
|
await act(owner, 'transfer', member.user.id, 409)
|
|
await expectHint([ownerSocket, memberSocket], () => act(owner, 'disband'))
|
|
await json(path, 'GET', owner.token, undefined, 404)
|
|
assert.deepEqual(await json('/groups', 'GET', member.token), [])
|
|
assert.deepEqual(unrelated, [])
|
|
})
|
|
|
|
test('群邀请链接可轮换、撤销且只能领取一次', { timeout: 25_000 }, async () => {
|
|
const [owner, first, second] = await Promise.all([register(), register(), register()])
|
|
const group = await json('/groups', 'POST', owner.token, { name: '群链接验收' }, 201)
|
|
const path = '/groups/' + group.id
|
|
const issue = () => json(path + '/invite-link', 'POST', owner.token, undefined, 201)
|
|
const redeem = (actor, code) => call('/group-invites/redeem', 'POST', actor.token, { code })
|
|
assert.equal((await call(path + '/invite-link', 'POST', first.token)).status, 404)
|
|
const initial = await issue()
|
|
assert.match(initial.code, /^[A-Za-z0-9_-]{43}$/)
|
|
assert.ok(Date.parse(initial.expiresAt) - Date.now() > 23 * 60 * 60 * 1000)
|
|
const current = await issue()
|
|
assert.equal((await redeem(first, initial.code)).status, 404)
|
|
assert.equal((await redeem(owner, current.code)).status, 409)
|
|
const results = await Promise.all([redeem(first, current.code), redeem(second, current.code)])
|
|
assert.deepEqual(results.map((result) => result.status).sort(), [200, 404])
|
|
const winner = results[0].ok ? first : second
|
|
const other = results[0].ok ? second : first
|
|
assert.deepEqual(await results.find((result) => result.ok).json(), { groupId: group.id })
|
|
const pending = await json(path, 'GET', winner.token)
|
|
assert.equal(pending.state, 'invited')
|
|
assert.deepEqual(pending.members, [])
|
|
assert.equal((await call(path + '/messages', 'GET', winner.token)).status, 404)
|
|
assert.equal((await call(path, 'POST', winner.token, { action: 'accept' })).status, 204)
|
|
assert.equal((await json(path, 'GET', winner.token)).membershipVersion, '2')
|
|
assert.equal((await call(path + '/invite-link', 'POST', winner.token)).status, 409)
|
|
const revoked = await issue()
|
|
assert.equal((await call(path + '/invite-link', 'DELETE', owner.token)).status, 204)
|
|
assert.equal((await redeem(other, revoked.code)).status, 404)
|
|
const previousOwner = await issue()
|
|
assert.equal((await call(path, 'POST', owner.token, { action: 'transfer', target: winner.user.id })).status, 204)
|
|
assert.equal((await redeem(other, previousOwner.code)).status, 404)
|
|
})
|
|
|
|
test('群密文和实时提示只投递到名单设备,移除或撤销阻断旧世代', { timeout: 25_000 }, async (t) => {
|
|
const enroll = async () => {
|
|
const keys = generateKeyPairSync('ed25519')
|
|
const actor = await register(keys)
|
|
const publicKey = randomBytes(32)
|
|
const bytes = Buffer.concat([Buffer.from('XHChat MLS credential v1\n' + actor.user.id + '\n' + actor.device.id + '\n'), publicKey])
|
|
const response = await call('/mls-credential', 'POST', actor.token, {
|
|
publicKey: publicKey.toString('base64'), signature: sign(null, bytes, keys.privateKey).toString('base64'),
|
|
})
|
|
assert.equal(response.status, 204)
|
|
const rawPackage = Buffer.concat([Buffer.from([0, 1, 0, 5]), randomBytes(96)])
|
|
const binding = Buffer.concat([Buffer.from('XHChat MLS KeyPackage v1\n' + actor.user.id + '\n' + actor.device.id + '\n'), rawPackage])
|
|
actor.keyPackage = { package: rawPackage.toString('base64'), signature: sign(null, binding, keys.privateKey).toString('base64') }
|
|
assert.equal((await call('/key-packages', 'POST', actor.token, actor.keyPackage)).status, 204)
|
|
return actor
|
|
}
|
|
const owner = await enroll()
|
|
const member = await enroll()
|
|
const outsider = await enroll()
|
|
const group = await json('/groups', 'POST', owner.token, { name: '密文投递验收' }, 201)
|
|
const path = '/groups/' + group.id
|
|
const publish = async (actor, input, expected = 204) => {
|
|
const response = await call(path + '/epochs', 'POST', actor.token, input)
|
|
assert.equal(response.status, expected, await response.text())
|
|
}
|
|
const change = async (actor, action, target) => {
|
|
const response = await call(path, 'POST', actor.token, { action, target })
|
|
assert.equal(response.status, 204, await response.text())
|
|
}
|
|
const welcome = Buffer.concat([Buffer.from([0, 1, 0, 3]), randomBytes(96)]).toString('base64')
|
|
const first = { id: randomUUID(), membershipVersion: '1', devices: [{ device: owner.device.id }] }
|
|
await publish(owner, first)
|
|
await publish(owner, first)
|
|
const firstMessage = { id: randomUUID(), epoch: first.id, wire: frame() }
|
|
await json(path + '/messages', 'POST', owner.token, firstMessage)
|
|
await contact(owner, member, 'request')
|
|
await contact(member, owner, 'accept')
|
|
await change(owner, 'invite', member.user.id)
|
|
await json(path + '/epochs', 'GET', member.token, undefined, 404)
|
|
await json(path + '/devices', 'GET', member.token, undefined, 404)
|
|
await json(path + '/devices/' + member.device.id + '/claim', 'POST', owner.token, undefined, 404)
|
|
await change(member, 'accept')
|
|
await json(path + '/devices', 'GET', outsider.token, undefined, 404)
|
|
const directory = await json(path + '/devices', 'GET', member.token)
|
|
assert.deepEqual(directory.map((device) => device.id), [owner.device.id, member.device.id].sort())
|
|
assert.equal(directory.find((device) => device.id === owner.device.id).user, owner.user.id)
|
|
await json(path + '/devices/' + owner.device.id + '/claim', 'POST', member.token, undefined, 409)
|
|
assert.deepEqual(await json(path + '/devices/' + member.device.id + '/claim', 'POST', owner.token), member.keyPackage)
|
|
await json(path + '/devices/' + member.device.id + '/claim', 'POST', owner.token, undefined, 404)
|
|
await json(path + '/messages', 'POST', owner.token, { ...firstMessage, id: randomUUID() }, 409)
|
|
assert.deepEqual(await json(path + '/messages', 'GET', member.token), [])
|
|
const second = { id: randomUUID(), membershipVersion: '2', devices: [
|
|
{ device: owner.device.id }, { device: member.device.id, wire: welcome },
|
|
] }
|
|
await publish(owner, { ...second, devices: [second.devices[0], { device: outsider.device.id, wire: welcome }] }, 409)
|
|
await publish(member, { ...second, devices: [{ device: member.device.id }, { device: owner.device.id, wire: welcome }] }, 409)
|
|
const [ownerSocket, memberSocket, outsiderSocket] = await Promise.all([owner, member, outsider].map((actor) => watchRealtime(actor, t)))
|
|
const outsiderEvents = []
|
|
const memberEvents = []
|
|
outsiderSocket.on('message', (data) => outsiderEvents.push(JSON.parse(data)))
|
|
memberSocket.on('message', (data) => memberEvents.push(JSON.parse(data)))
|
|
const hint = { type: 'group_changed', groupId: group.id }
|
|
const epochHint = once(memberSocket, 'message', { signal: AbortSignal.timeout(4000) })
|
|
await publish(owner, second)
|
|
assert.deepEqual(JSON.parse((await epochHint)[0]), hint)
|
|
await publish(owner, second)
|
|
await publish(owner, { ...second, id: randomUUID() }, 409)
|
|
const epochs = await json(path + '/epochs', 'GET', member.token)
|
|
assert.deepEqual(epochs, [{ id: second.id, membershipVersion: '2', creatorDevice: owner.device.id, welcome, current: true,
|
|
roster: [owner.device.id, member.device.id].sort() }])
|
|
await json(path + '/messages', 'GET', outsider.token, undefined, 404)
|
|
const message = { id: randomUUID(), epoch: second.id, wire: frame() }
|
|
const messageHint = once(ownerSocket, 'message', { signal: AbortSignal.timeout(4000) })
|
|
const sequence = await json(path + '/messages', 'POST', member.token, message)
|
|
assert.deepEqual(JSON.parse((await messageHint)[0]), { ...hint, notify: true })
|
|
assert.deepEqual(await json(path + '/messages', 'POST', member.token, message), sequence)
|
|
const received = await json(path + '/messages', 'GET', member.token)
|
|
assert.deepEqual(received.map((item) => item.wire), [message.wire])
|
|
const unread = async (actor) => (await json('/groups', 'GET', actor.token)).find((entry) => entry.id === group.id)?.unread
|
|
const seen = (actor, cursor) => call(path + '/seen', 'POST', actor.token, { sequence: cursor })
|
|
assert.equal(await unread(owner), 1)
|
|
assert.equal(await unread(member), 0)
|
|
assert.equal(await unread(outsider), undefined)
|
|
assert.equal((await seen(outsider, sequence.sequence)).status, 404)
|
|
assert.equal((await seen(member, '0')).status, 400)
|
|
|
|
await json(path + '/preferences', 'POST', member.token, { muted: true })
|
|
|
|
const attachmentId = randomUUID()
|
|
const attachment = path + '/attachments/' + attachmentId
|
|
const bytes = randomBytes(16_384)
|
|
const upload = (token, epoch, body) => fetch(base + '/api/v1' + attachment + '?epoch=' + epoch, {
|
|
method: 'POST', headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/octet-stream' },
|
|
body, signal: AbortSignal.timeout(10_000),
|
|
})
|
|
const linked = { id: randomUUID(), epoch: second.id, wire: frame(), attachmentId }
|
|
await json(path + '/messages', 'POST', owner.token, linked, 409)
|
|
assert.equal((await upload(outsider.token, second.id, bytes)).status, 404)
|
|
assert.equal((await upload(owner.token, first.id, bytes)).status, 409)
|
|
assert.equal((await upload(owner.token, second.id, Buffer.alloc(8 * 1024 * 1024 + 17))).status, 413)
|
|
assert.equal((await upload(owner.token, second.id, bytes)).status, 204)
|
|
assert.equal((await upload(owner.token, second.id, bytes)).status, 204)
|
|
assert.equal((await upload(owner.token, second.id, randomBytes(64))).status, 409)
|
|
await json(attachment, 'GET', owner.token, undefined, 404)
|
|
await json(attachment, 'GET', member.token, undefined, 404)
|
|
await json(path + '/messages', 'POST', member.token, linked, 409)
|
|
const posted = await json(path + '/messages', 'POST', owner.token, linked)
|
|
assert.equal(await unread(member), 1)
|
|
assert.equal((await seen(member, posted.sequence)).status, 204)
|
|
assert.equal((await seen(member, sequence.sequence)).status, 204)
|
|
assert.equal(await unread(member), 0)
|
|
assert.equal(await unread(owner), 1)
|
|
assert.deepEqual(await json(path + '/messages', 'POST', owner.token, linked), posted)
|
|
await json(path + '/messages', 'POST', owner.token, { ...linked, id: randomUUID() }, 409)
|
|
await json(path + '/messages', 'POST', owner.token, { ...linked, attachmentId: undefined }, 409)
|
|
assert.equal((await json(path + '/messages?after=' + sequence.sequence, 'GET', member.token))[0].attachmentId, attachmentId)
|
|
const download = await call(attachment, 'GET', member.token)
|
|
assert.equal(download.status, 200)
|
|
assert.equal(download.headers.get('cache-control'), 'no-store')
|
|
assert.deepEqual(Buffer.from(await download.arrayBuffer()), bytes)
|
|
await json(attachment, 'GET', outsider.token, undefined, 404)
|
|
await change(owner, 'remove', member.user.id)
|
|
assert.equal((await seen(member, posted.sequence)).status, 404)
|
|
await json(path + '/messages', 'GET', member.token, undefined, 404)
|
|
await json(attachment, 'GET', member.token, undefined, 404)
|
|
await json(path + '/messages', 'POST', owner.token, { ...message, id: randomUUID() }, 409)
|
|
await change(owner, 'invite', member.user.id)
|
|
await change(member, 'accept')
|
|
assert.equal(await unread(member), 0)
|
|
assert.equal((await seen(member, posted.sequence)).status, 404)
|
|
await json(attachment, 'GET', member.token, undefined, 404)
|
|
assert.equal((await call(attachment, 'GET', owner.token)).status, 200)
|
|
assert.deepEqual(await json(path + '/messages', 'GET', member.token), [])
|
|
assert.deepEqual(await json(path + '/epochs', 'GET', member.token), [])
|
|
const next = { ...second, id: randomUUID(), membershipVersion: '4' }
|
|
await publish(owner, next)
|
|
assert.equal((await call('/devices/' + member.device.id, 'DELETE', member.token)).status, 204)
|
|
await json(path + '/messages', 'POST', owner.token, { id: randomUUID(), epoch: next.id, wire: frame() }, 409)
|
|
assert.equal((await json(path + '/epochs', 'GET', owner.token)).every((epoch) => !epoch.current), true)
|
|
await change(owner, 'disband')
|
|
await json(attachment, 'GET', owner.token, undefined, 404)
|
|
assert.ok(memberEvents.some((event) => event.type === 'group_changed' && event.groupId === group.id))
|
|
assert.ok(memberEvents.every((event) => event.notify === undefined))
|
|
assert.deepEqual(outsiderEvents, [])
|
|
})
|
|
|
|
test('设备密文投递、幂等、离线补拉、免打扰与撤销', { timeout: 25000 }, async (t) => {
|
|
const sender = await register()
|
|
const recipientPassword = randomBytes(24).toString('hex')
|
|
const recipient = await register(undefined, recipientPassword)
|
|
const other = await register()
|
|
const payload = { messageId: randomUUID(), recipientDevice: recipient.device.id, ciphertext: frame() }
|
|
const preferences = '/contacts/' + sender.user.id
|
|
const unread = (actor) => json('/inbox/unread', 'GET', actor.token)
|
|
const markSeen = (actor, sequence, senderDevice = sender.device.id) =>
|
|
call('/inbox/seen', 'POST', actor.token, { senderDevice, sequence })
|
|
await json('/inbox', 'POST', sender.token, payload, 404)
|
|
await json(preferences, 'POST', recipient.token, { action: 'mute' }, 409)
|
|
await json(preferences, 'POST', recipient.token, { action: 'pin' }, 409)
|
|
await contact(sender, recipient, 'request')
|
|
await contact(recipient, sender, 'accept')
|
|
const sibling = await authenticate('login', recipient.user.username, recipientPassword)
|
|
assert.notEqual(sibling.device.id, recipient.device.id)
|
|
await json('/inbox', 'POST', sender.token, { ...payload, ciphertext: Buffer.from('plaintext').toString('base64') }, 400)
|
|
await json('/inbox', 'POST', sender.token, { ...payload, text: 'plaintext' }, 400)
|
|
|
|
const first = await json('/inbox', 'POST', sender.token, payload)
|
|
assert.deepEqual(await json('/inbox', 'POST', sender.token, payload), first)
|
|
await json('/inbox', 'POST', sender.token, { ...payload, ciphertext: frame() }, 409)
|
|
const [item] = await json('/inbox', 'GET', recipient.token)
|
|
assert.equal(item.sequence, first.sequence)
|
|
assert.equal(item.ciphertext, payload.ciphertext)
|
|
assert.equal(item.senderDevice, sender.device.id)
|
|
assert.deepEqual(await json('/inbox?after=' + first.sequence, 'GET', recipient.token), [])
|
|
assert.deepEqual(await json('/inbox', 'GET', sender.token), [])
|
|
assert.deepEqual(await json('/inbox', 'GET', other.token), [])
|
|
assert.deepEqual(await unread(recipient), { [sender.user.id]: 1 })
|
|
assert.deepEqual(await unread(other), {})
|
|
assert.deepEqual(await unread(sibling), {})
|
|
await json('/inbox', 'POST', sender.token, { ...payload, recipientDevice: sibling.device.id })
|
|
assert.deepEqual(await unread(sibling), { [sender.user.id]: 1 })
|
|
assert.equal((await markSeen(other, first.sequence)).status, 404)
|
|
assert.equal((await markSeen(recipient, first.sequence, other.device.id)).status, 404)
|
|
|
|
const [socket, senderSocket] = await Promise.all([recipient, sender].map((actor) => watchRealtime(actor, t)))
|
|
const senderEvents = []
|
|
senderSocket.on('message', (data) => senderEvents.push(JSON.parse(data)))
|
|
async function expectEvent(type, act) {
|
|
const arrival = once(socket, 'message', { signal: AbortSignal.timeout(4000) })
|
|
const [[data], result] = await Promise.all([arrival, act()])
|
|
assert.deepEqual(JSON.parse(data), type)
|
|
return result
|
|
}
|
|
const syncOnly = { type: 'inbox_changed' }
|
|
const alert = { ...syncOnly, contactId: sender.user.id, notify: true }
|
|
const contactsChanged = { type: 'contacts_changed' }
|
|
const newPayload = (ciphertext = frame()) => ({ ...payload, messageId: randomUUID(), ciphertext })
|
|
const deliver = (expected, packet) => expectEvent(expected, () => json('/inbox', 'POST', sender.token, packet))
|
|
const second = newPayload()
|
|
const result = await deliver(alert, second)
|
|
assert.deepEqual(await deliver(syncOnly, second), result)
|
|
await deliver(syncOnly, newPayload(frame(3)))
|
|
await deliver(syncOnly, { ...newPayload(), silent: true })
|
|
|
|
await expectEvent(contactsChanged, () => contact(recipient, sender, 'mute'))
|
|
await expectEvent(contactsChanged, () => contact(recipient, sender, 'pin'))
|
|
await expectEvent(contactsChanged, async () => {
|
|
const reply = await call(preferences, 'POST', recipient.token, { action: 'preferences', alias: '朋友', category: '测试' })
|
|
assert.equal(reply.status, 204, await reply.text())
|
|
})
|
|
assert.deepEqual((await json('/contacts', 'GET', recipient.token))[0], {
|
|
id: sender.user.id, username: sender.user.username, state: 'friend', alias: '朋友', category: '测试', muted: true, pinned: true,
|
|
})
|
|
const senderView = (await json('/contacts', 'GET', sender.token))[0]
|
|
assert.deepEqual([senderView.muted, senderView.pinned], [false, false])
|
|
const siblingView = (await json('/contacts', 'GET', sibling.token))[0]
|
|
assert.deepEqual([siblingView.muted, siblingView.pinned], [true, true])
|
|
const muted = newPayload()
|
|
const mutedResult = await deliver(syncOnly, muted)
|
|
assert.deepEqual(await unread(recipient), { [sender.user.id]: 3 })
|
|
assert.equal((await markSeen(recipient, result.sequence)).status, 204)
|
|
assert.equal((await markSeen(recipient, first.sequence)).status, 204)
|
|
assert.deepEqual(await unread(recipient), { [sender.user.id]: 1 })
|
|
assert.equal((await markSeen(recipient, mutedResult.sequence)).status, 204)
|
|
assert.deepEqual(await unread(recipient), {})
|
|
assert.deepEqual(await unread(sibling), { [sender.user.id]: 1 })
|
|
const pending = await json('/inbox?after=' + first.sequence, 'GET', recipient.token)
|
|
assert.equal(pending.length, 4)
|
|
assert.equal(pending[0].ciphertext, second.ciphertext)
|
|
assert.equal(pending.at(-1).ciphertext, muted.ciphertext)
|
|
await expectEvent(contactsChanged, () => contact(recipient, sender, 'unmute'))
|
|
const unmuted = (await json('/contacts', 'GET', recipient.token))[0]
|
|
assert.deepEqual([unmuted.muted, unmuted.pinned, unmuted.alias, unmuted.category], [false, true, '朋友', '测试'])
|
|
await expectEvent(contactsChanged, () => contact(recipient, sender, 'unpin'))
|
|
assert.equal((await json('/contacts', 'GET', recipient.token))[0].pinned, false)
|
|
await deliver(alert, newPayload())
|
|
assert.deepEqual(senderEvents, [])
|
|
assert.equal((await call('/devices/' + recipient.device.id, 'DELETE', recipient.token)).status, 204)
|
|
await json('/inbox', 'GET', recipient.token, undefined, 401)
|
|
assert.equal((await markSeen(recipient, mutedResult.sequence)).status, 401)
|
|
await json('/inbox', 'POST', sender.token, newPayload(), 404)
|
|
})
|
|
|
|
test('设备密钥包验证签名并只领取一次', { timeout: 25000 }, async () => {
|
|
const keys = generateKeyPairSync('ed25519')
|
|
const owner = await register(keys)
|
|
const contactUser = await register()
|
|
const stranger = await register()
|
|
const directory = '/contacts/' + owner.user.id + '/devices'
|
|
const claim = directory + '/' + owner.device.id + '/claim'
|
|
const bytes = Buffer.concat([Buffer.from([0, 1, 0, 5]), randomBytes(96)])
|
|
const binding = Buffer.concat([Buffer.from('XHChat MLS KeyPackage v1\n' + owner.user.id + '\n' + owner.device.id + '\n'), bytes])
|
|
const packageData = { package: bytes.toString('base64'), signature: sign(null, binding, keys.privateKey).toString('base64') }
|
|
assert.deepEqual(await json('/key-packages', 'GET', owner.token), { available: 0 })
|
|
await json('/key-packages', 'POST', owner.token, { ...packageData, signature: randomBytes(64).toString('base64') }, 400)
|
|
assert.equal((await call('/key-packages', 'POST', owner.token, packageData)).status, 204)
|
|
assert.deepEqual(await json('/key-packages', 'GET', owner.token), { available: 1 })
|
|
assert.deepEqual(await json('/key-packages', 'GET', stranger.token), { available: 0 })
|
|
assert.deepEqual(await json(directory, 'GET', contactUser.token), [])
|
|
await json(claim, 'POST', contactUser.token, null, 404)
|
|
await contact(owner, contactUser, 'request')
|
|
await contact(contactUser, owner, 'accept')
|
|
const [record] = await json(directory, 'GET', contactUser.token)
|
|
assert.equal(record.id, owner.device.id)
|
|
assert.deepEqual(Buffer.from(record.publicKey, 'base64'), Buffer.from(keys.publicKey.export({format:'jwk'}).x, 'base64url'))
|
|
assert.deepEqual(await json(directory, 'GET', stranger.token), [])
|
|
const attempts = await Promise.all([call(claim, 'POST', contactUser.token), call(claim, 'POST', contactUser.token)])
|
|
assert.deepEqual(attempts.map((reply) => reply.status).sort(), [200, 404])
|
|
assert.deepEqual(await attempts.find((reply) => reply.ok).json(), packageData)
|
|
assert.deepEqual(await json('/key-packages', 'GET', owner.token), { available: 0 })
|
|
assert.equal((await call('/key-packages', 'POST', owner.token, packageData)).status, 204)
|
|
await json(claim, 'POST', contactUser.token, null, 404)
|
|
assert.equal((await call('/devices/' + owner.device.id, 'DELETE', owner.token)).status, 204)
|
|
assert.deepEqual(await json(directory, 'GET', contactUser.token), [])
|
|
})
|
|
|
|
test('附件访问按设备授权并支持相同密文重试', { timeout: 15000 }, async () => {
|
|
const sender = await register()
|
|
const recipient = await register()
|
|
const stranger = await register()
|
|
const path = '/api/v1/attachments/' + randomUUID()
|
|
const bytes = randomBytes(256)
|
|
const upload = (body) => fetch(base + path + '?recipient=' + recipient.device.id, {
|
|
method: 'POST',
|
|
headers: { Authorization: 'Bearer ' + sender.token, 'Content-Type': 'application/octet-stream' },
|
|
body,
|
|
signal: AbortSignal.timeout(10_000),
|
|
})
|
|
const download = (token) => fetch(base + path, {
|
|
headers: { Authorization: 'Bearer ' + token },
|
|
signal: AbortSignal.timeout(10_000),
|
|
})
|
|
assert.equal((await upload(bytes)).status, 404)
|
|
await contact(sender, recipient, 'request')
|
|
await contact(recipient, sender, 'accept')
|
|
assert.equal((await upload(bytes)).status, 204)
|
|
assert.equal((await upload(bytes)).status, 204)
|
|
assert.equal((await upload(randomBytes(256))).status, 409)
|
|
assert.equal((await download(stranger.token)).status, 404)
|
|
const response = await download(recipient.token)
|
|
assert.equal(response.status, 200)
|
|
assert.deepEqual(Buffer.from(await response.arrayBuffer()), bytes)
|
|
assert.equal((await call('/devices/' + recipient.device.id, 'DELETE', recipient.token)).status, 204)
|
|
assert.equal((await download(recipient.token)).status, 401)
|
|
})
|