chore: format everything

This commit is contained in:
canove
2025-05-06 12:10:19 -03:00
parent 04afa20244
commit fa706d0b50
76 changed files with 8241 additions and 7142 deletions

View File

@@ -4,7 +4,6 @@ import { processSyncAction } from '../Utils/chat-utils'
import logger from '../Utils/logger'
describe('App State Sync Tests', () => {
const me: Contact = { id: randomJid() }
// case when initial sync is off
it('should return archive=false event', () => {
@@ -57,7 +56,7 @@ describe('App State Sync Tests', () => {
]
]
for(const mutations of CASES) {
for (const mutations of CASES) {
const events = processSyncAction(mutations, me, undefined, logger)
expect(events['chats.update']).toHaveLength(1)
const event = events['chats.update']?.[0]
@@ -129,7 +128,7 @@ describe('App State Sync Tests', () => {
}
}
}
],
]
]
const ctx: InitialAppStateSyncOptions = {
@@ -139,7 +138,7 @@ describe('App State Sync Tests', () => {
accountSettings: { unarchiveChats: true }
}
for(const mutations of CASES) {
for (const mutations of CASES) {
const events = processSyncActions(mutations, me, ctx, logger)
expect(events['chats.update']?.length).toBeFalsy()
}
@@ -152,7 +151,7 @@ describe('App State Sync Tests', () => {
const index = ['archive', jid]
const now = unixTimestampSeconds()
const CASES: { settings: AccountSettings, mutations: ChatMutation[] }[] = [
const CASES: { settings: AccountSettings; mutations: ChatMutation[] }[] = [
{
settings: { unarchiveChats: true },
mutations: [
@@ -169,7 +168,7 @@ describe('App State Sync Tests', () => {
}
}
}
],
]
},
{
settings: { unarchiveChats: false },
@@ -187,11 +186,11 @@ describe('App State Sync Tests', () => {
}
}
}
],
]
}
]
for(const { mutations, settings } of CASES) {
for (const { mutations, settings } of CASES) {
const ctx: InitialAppStateSyncOptions = {
recvChats: {
[jid]: { lastMsgRecvTimestamp: now }
@@ -204,4 +203,4 @@ describe('App State Sync Tests', () => {
expect(event.archive).toEqual(true)
}
})
})
})

View File

@@ -5,15 +5,14 @@ import logger from '../Utils/logger'
import { randomJid } from './utils'
describe('Event Buffer Tests', () => {
let ev: ReturnType<typeof makeEventBuffer>
beforeEach(() => {
const _logger = logger.child({ })
const _logger = logger.child({})
_logger.level = 'trace'
ev = makeEventBuffer(_logger)
})
it('should buffer a chat upsert & update event', async() => {
it('should buffer a chat upsert & update event', async () => {
const chatId = randomJid()
const chats: Chat[] = []
@@ -23,14 +22,14 @@ describe('Event Buffer Tests', () => {
ev.buffer()
await Promise.all([
(async() => {
(async () => {
ev.buffer()
await delay(100)
ev.emit('chats.upsert', [{ id: chatId, conversationTimestamp: 123, unreadCount: 1 }])
const flushed = ev.flush()
expect(flushed).toBeFalsy()
})(),
(async() => {
(async () => {
ev.buffer()
await delay(200)
ev.emit('chats.update', [{ id: chatId, conversationTimestamp: 124, unreadCount: 1 }])
@@ -47,7 +46,7 @@ describe('Event Buffer Tests', () => {
expect(chats[0].unreadCount).toEqual(2)
})
it('should overwrite a chats.delete event', async() => {
it('should overwrite a chats.delete event', async () => {
const chatId = randomJid()
const chats: Partial<Chat>[] = []
@@ -65,7 +64,7 @@ describe('Event Buffer Tests', () => {
expect(chats).toHaveLength(1)
})
it('should overwrite a chats.update event', async() => {
it('should overwrite a chats.update event', async () => {
const chatId = randomJid()
const chatsDeleted: string[] = []
@@ -82,7 +81,7 @@ describe('Event Buffer Tests', () => {
expect(chatsDeleted).toHaveLength(1)
})
it('should release a conditional update at the right time', async() => {
it('should release a conditional update at the right time', async () => {
const chatId = randomJid()
const chatId2 = randomJid()
const chatsUpserted: Chat[] = []
@@ -93,41 +92,49 @@ describe('Event Buffer Tests', () => {
ev.on('chats.update', () => fail('not should have emitted'))
ev.buffer()
ev.emit('chats.update', [{
id: chatId,
archived: true,
conditional(buff) {
if(buff.chatUpserts[chatId]) {
return true
ev.emit('chats.update', [
{
id: chatId,
archived: true,
conditional(buff) {
if (buff.chatUpserts[chatId]) {
return true
}
}
}
}])
ev.emit('chats.update', [{
id: chatId2,
archived: true,
conditional(buff) {
if(buff.historySets.chats[chatId2]) {
return true
])
ev.emit('chats.update', [
{
id: chatId2,
archived: true,
conditional(buff) {
if (buff.historySets.chats[chatId2]) {
return true
}
}
}
}])
])
ev.flush()
ev.buffer()
ev.emit('chats.upsert', [{
id: chatId,
conversationTimestamp: 123,
unreadCount: 1,
muteEndTime: 123
}])
ev.emit('messaging-history.set', {
chats: [{
id: chatId2,
ev.emit('chats.upsert', [
{
id: chatId,
conversationTimestamp: 123,
unreadCount: 1,
muteEndTime: 123
}],
}
])
ev.emit('messaging-history.set', {
chats: [
{
id: chatId2,
conversationTimestamp: 123,
unreadCount: 1,
muteEndTime: 123
}
],
contacts: [],
messages: [],
isLatest: false
@@ -144,7 +151,7 @@ describe('Event Buffer Tests', () => {
expect(chatsSynced[0].archived).toEqual(true)
})
it('should discard a conditional update', async() => {
it('should discard a conditional update', async () => {
const chatId = randomJid()
const chatsUpserted: Chat[] = []
@@ -152,21 +159,25 @@ describe('Event Buffer Tests', () => {
ev.on('chats.update', () => fail('not should have emitted'))
ev.buffer()
ev.emit('chats.update', [{
id: chatId,
archived: true,
conditional(buff) {
if(buff.chatUpserts[chatId]) {
return false
ev.emit('chats.update', [
{
id: chatId,
archived: true,
conditional(buff) {
if (buff.chatUpserts[chatId]) {
return false
}
}
}
}])
ev.emit('chats.upsert', [{
id: chatId,
conversationTimestamp: 123,
unreadCount: 1,
muteEndTime: 123
}])
])
ev.emit('chats.upsert', [
{
id: chatId,
conversationTimestamp: 123,
unreadCount: 1,
muteEndTime: 123
}
])
ev.flush()
@@ -174,7 +185,7 @@ describe('Event Buffer Tests', () => {
expect(chatsUpserted[0].archived).toBeUndefined()
})
it('should overwrite a chats.update event with a history event', async() => {
it('should overwrite a chats.update event with a history event', async () => {
const chatId = randomJid()
let chatRecv: Chat | undefined
@@ -199,7 +210,7 @@ describe('Event Buffer Tests', () => {
expect(chatRecv?.archived).toBeTruthy()
})
it('should buffer message upsert events', async() => {
it('should buffer message upsert events', async () => {
const messageTimestamp = unixTimestampSeconds()
const msg: proto.IWebMessageInfo = {
key: {
@@ -235,7 +246,7 @@ describe('Event Buffer Tests', () => {
expect(msgs[0].status).toEqual(WAMessageStatus.READ)
})
it('should buffer a message receipt update', async() => {
it('should buffer a message receipt update', async () => {
const msg: proto.IWebMessageInfo = {
key: {
remoteJid: randomJid(),
@@ -269,7 +280,7 @@ describe('Event Buffer Tests', () => {
expect(msgs[0].userReceipt).toHaveLength(1)
})
it('should buffer multiple status updates', async() => {
it('should buffer multiple status updates', async () => {
const key: WAMessageKey = {
remoteJid: randomJid(),
id: generateMessageID(),
@@ -290,7 +301,7 @@ describe('Event Buffer Tests', () => {
expect(msgs[0].update.status).toEqual(WAMessageStatus.READ)
})
it('should remove chat unread counter', async() => {
it('should remove chat unread counter', async () => {
const msg: proto.IWebMessageInfo = {
key: {
remoteJid: '12345@s.whatsapp.net',
@@ -316,4 +327,4 @@ describe('Event Buffer Tests', () => {
expect(chats[0].unreadCount).toBeUndefined()
})
})
})

View File

@@ -5,55 +5,44 @@ import { makeMockSignalKeyStore } from './utils'
logger.level = 'trace'
describe('Key Store w Transaction Tests', () => {
const rawStore = makeMockSignalKeyStore()
const store = addTransactionCapability(
rawStore,
logger,
{
maxCommitRetries: 1,
delayBetweenTriesMs: 10
}
)
const store = addTransactionCapability(rawStore, logger, {
maxCommitRetries: 1,
delayBetweenTriesMs: 10
})
it('should use transaction cache when mutated', async() => {
it('should use transaction cache when mutated', async () => {
const key = '123'
const value = new Uint8Array(1)
const ogGet = rawStore.get
await store.transaction(
async() => {
await store.set({ 'session': { [key]: value } })
await store.transaction(async () => {
await store.set({ session: { [key]: value } })
rawStore.get = () => {
throw new Error('should not have been called')
}
const { [key]: stored } = await store.get('session', [key])
expect(stored).toEqual(new Uint8Array(1))
rawStore.get = () => {
throw new Error('should not have been called')
}
)
const { [key]: stored } = await store.get('session', [key])
expect(stored).toEqual(new Uint8Array(1))
})
rawStore.get = ogGet
})
it('should not commit a failed transaction', async() => {
it('should not commit a failed transaction', async () => {
const key = 'abcd'
await expect(
store.transaction(
async() => {
await store.set({ 'session': { [key]: new Uint8Array(1) } })
throw new Error('fail')
}
)
).rejects.toThrowError(
'fail'
)
store.transaction(async () => {
await store.set({ session: { [key]: new Uint8Array(1) } })
throw new Error('fail')
})
).rejects.toThrowError('fail')
const { [key]: stored } = await store.get('session', [key])
expect(stored).toBeUndefined()
})
it('should handle overlapping transactions', async() => {
it('should handle overlapping transactions', async () => {
// promise to let transaction 2
// know that transaction 1 has started
let promiseResolve: () => void
@@ -61,32 +50,28 @@ describe('Key Store w Transaction Tests', () => {
promiseResolve = resolve
})
store.transaction(
async() => {
await store.set({
'session': {
'1': new Uint8Array(1)
}
})
// wait for the other transaction to start
await delay(5)
// reolve the promise to let the other transaction continue
promiseResolve()
}
)
store.transaction(async () => {
await store.set({
session: {
'1': new Uint8Array(1)
}
})
// wait for the other transaction to start
await delay(5)
// reolve the promise to let the other transaction continue
promiseResolve()
})
await store.transaction(
async() => {
await promise
await delay(5)
await store.transaction(async () => {
await promise
await delay(5)
expect(store.isInTransaction()).toBe(true)
}
)
expect(store.isInTransaction()).toBe(true)
})
expect(store.isInTransaction()).toBe(false)
// ensure that the transaction were committed
const { ['1']: stored } = await store.get('session', ['1'])
expect(stored).toEqual(new Uint8Array(1))
})
})
})

View File

@@ -3,8 +3,7 @@ import { SignalAuthState, SignalDataTypeMap } from '../Types'
import { Curve, generateRegistrationId, generateSignalPubKey, signedKeyPair } from '../Utils'
describe('Signal Tests', () => {
it('should correctly encrypt/decrypt 1 message', async() => {
it('should correctly encrypt/decrypt 1 message', async () => {
const user1 = makeUser()
const user2 = makeUser()
@@ -12,39 +11,31 @@ describe('Signal Tests', () => {
await prepareForSendingMessage(user1, user2)
const result = await user1.repository.encryptMessage(
{ jid: user2.jid, data: msg }
)
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
const dec = await user2.repository.decryptMessage(
{ jid: user1.jid, ...result }
)
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
expect(dec).toEqual(msg)
})
it('should correctly override a session', async() => {
it('should correctly override a session', async () => {
const user1 = makeUser()
const user2 = makeUser()
const msg = Buffer.from('hello there!')
for(let preKeyId = 2; preKeyId <= 3;preKeyId++) {
for (let preKeyId = 2; preKeyId <= 3; preKeyId++) {
await prepareForSendingMessage(user1, user2, preKeyId)
const result = await user1.repository.encryptMessage(
{ jid: user2.jid, data: msg }
)
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
const dec = await user2.repository.decryptMessage(
{ jid: user1.jid, ...result }
)
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
expect(dec).toEqual(msg)
}
})
it('should correctly encrypt/decrypt multiple messages', async() => {
it('should correctly encrypt/decrypt multiple messages', async () => {
const user1 = makeUser()
const user2 = makeUser()
@@ -52,56 +43,46 @@ describe('Signal Tests', () => {
await prepareForSendingMessage(user1, user2)
for(let i = 0;i < 10;i++) {
const result = await user1.repository.encryptMessage(
{ jid: user2.jid, data: msg }
)
for (let i = 0; i < 10; i++) {
const result = await user1.repository.encryptMessage({ jid: user2.jid, data: msg })
const dec = await user2.repository.decryptMessage(
{ jid: user1.jid, ...result }
)
const dec = await user2.repository.decryptMessage({ jid: user1.jid, ...result })
expect(dec).toEqual(msg)
}
})
it('should encrypt/decrypt messages from group', async() => {
it('should encrypt/decrypt messages from group', async () => {
const groupId = '123456@g.us'
const participants = [...Array(5)].map(makeUser)
const msg = Buffer.from('hello there!')
const sender = participants[0]
const enc = await sender.repository.encryptGroupMessage(
{
group: groupId,
meId: sender.jid,
data: msg
}
)
const enc = await sender.repository.encryptGroupMessage({
group: groupId,
meId: sender.jid,
data: msg
})
for(const participant of participants) {
if(participant === sender) {
for (const participant of participants) {
if (participant === sender) {
continue
}
await participant.repository.processSenderKeyDistributionMessage(
{
item: {
groupId,
axolotlSenderKeyDistributionMessage: enc.senderKeyDistributionMessage
},
authorJid: sender.jid
}
)
await participant.repository.processSenderKeyDistributionMessage({
item: {
groupId,
axolotlSenderKeyDistributionMessage: enc.senderKeyDistributionMessage
},
authorJid: sender.jid
})
const dec = await participant.repository.decryptGroupMessage(
{
group: groupId,
authorJid: sender.jid,
msg: enc.ciphertext
}
)
const dec = await participant.repository.decryptGroupMessage({
group: groupId,
authorJid: sender.jid,
msg: enc.ciphertext
})
expect(dec).toEqual(msg)
}
})
@@ -116,30 +97,24 @@ function makeUser() {
return { store, jid, repository }
}
async function prepareForSendingMessage(
sender: User,
receiver: User,
preKeyId = 2
) {
async function prepareForSendingMessage(sender: User, receiver: User, preKeyId = 2) {
const preKey = Curve.generateKeyPair()
await sender.repository.injectE2ESession(
{
jid: receiver.jid,
session: {
registrationId: receiver.store.creds.registrationId,
identityKey: generateSignalPubKey(receiver.store.creds.signedIdentityKey.public),
signedPreKey: {
keyId: receiver.store.creds.signedPreKey.keyId,
publicKey: generateSignalPubKey(receiver.store.creds.signedPreKey.keyPair.public),
signature: receiver.store.creds.signedPreKey.signature,
},
preKey: {
keyId: preKeyId,
publicKey: generateSignalPubKey(preKey.public),
}
await sender.repository.injectE2ESession({
jid: receiver.jid,
session: {
registrationId: receiver.store.creds.registrationId,
identityKey: generateSignalPubKey(receiver.store.creds.signedIdentityKey.public),
signedPreKey: {
keyId: receiver.store.creds.signedPreKey.keyId,
publicKey: generateSignalPubKey(receiver.store.creds.signedPreKey.keyPair.public),
signature: receiver.store.creds.signedPreKey.signature
},
preKey: {
keyId: preKeyId,
publicKey: generateSignalPubKey(preKey.public)
}
}
)
})
await receiver.store.keys.set({
'pre-key': {
@@ -156,14 +131,14 @@ function makeTestAuthState(): SignalAuthState {
creds: {
signedIdentityKey: identityKey,
registrationId: generateRegistrationId(),
signedPreKey: signedKeyPair(identityKey, 1),
signedPreKey: signedKeyPair(identityKey, 1)
},
keys: {
get(type, ids) {
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
for(const id of ids) {
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
for (const id of ids) {
const item = store[getUniqueId(type, id)]
if(typeof item !== 'undefined') {
if (typeof item !== 'undefined') {
data[id] = item
}
}
@@ -171,16 +146,16 @@ function makeTestAuthState(): SignalAuthState {
return data
},
set(data) {
for(const type in data) {
for(const id in data[type]) {
for (const type in data) {
for (const id in data[type]) {
store[getUniqueId(type, id)] = data[type][id]
}
}
},
}
}
}
function getUniqueId(type: string, id: string) {
return `${type}.${id}`
}
}
}

View File

@@ -31,38 +31,37 @@ const TEST_VECTORS: TestVector[] = [
)
),
plaintext: readFileSync('./Media/icon.png')
},
}
]
describe('Media Download Tests', () => {
it('should download a full encrypted media correctly', async() => {
for(const { type, message, plaintext } of TEST_VECTORS) {
it('should download a full encrypted media correctly', async () => {
for (const { type, message, plaintext } of TEST_VECTORS) {
const readPipe = await downloadContentFromMessage(message, type)
let buffer = Buffer.alloc(0)
for await (const read of readPipe) {
buffer = Buffer.concat([ buffer, read ])
buffer = Buffer.concat([buffer, read])
}
expect(buffer).toEqual(plaintext)
}
})
it('should download an encrypted media correctly piece', async() => {
for(const { type, message, plaintext } of TEST_VECTORS) {
it('should download an encrypted media correctly piece', async () => {
for (const { type, message, plaintext } of TEST_VECTORS) {
// check all edge cases
const ranges = [
{ startByte: 51, endByte: plaintext.length - 100 }, // random numbers
{ startByte: 1024, endByte: 2038 }, // larger random multiples of 16
{ startByte: 1, endByte: plaintext.length - 1 } // borders
]
for(const range of ranges) {
for (const range of ranges) {
const readPipe = await downloadContentFromMessage(message, type, range)
let buffer = Buffer.alloc(0)
for await (const read of readPipe) {
buffer = Buffer.concat([ buffer, read ])
buffer = Buffer.concat([buffer, read])
}
const hex = buffer.toString('hex')
@@ -73,4 +72,4 @@ describe('Media Download Tests', () => {
}
}
})
})
})

View File

@@ -2,9 +2,8 @@ import { WAMessageContent } from '../Types'
import { normalizeMessageContent } from '../Utils'
describe('Messages Tests', () => {
it('should correctly unwrap messages', () => {
const CONTENT = { imageMessage: { } }
const CONTENT = { imageMessage: {} }
expectRightContent(CONTENT)
expectRightContent({
ephemeralMessage: { message: CONTENT }
@@ -29,9 +28,7 @@ describe('Messages Tests', () => {
})
function expectRightContent(content: WAMessageContent) {
expect(
normalizeMessageContent(content)
).toHaveProperty('imageMessage')
expect(normalizeMessageContent(content)).toHaveProperty('imageMessage')
}
})
})
})

View File

@@ -11,10 +11,10 @@ export function makeMockSignalKeyStore(): SignalKeyStore {
return {
get(type, ids) {
const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
for(const id of ids) {
const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
for (const id of ids) {
const item = store[getUniqueId(type, id)]
if(typeof item !== 'undefined') {
if (typeof item !== 'undefined') {
data[id] = item
}
}
@@ -22,15 +22,15 @@ export function makeMockSignalKeyStore(): SignalKeyStore {
return data
},
set(data) {
for(const type in data) {
for(const id in data[type]) {
for (const type in data) {
for (const id in data[type]) {
store[getUniqueId(type, id)] = data[type][id]
}
}
},
}
}
function getUniqueId(type: string, id: string) {
return `${type}.${id}`
}
}
}