Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/Socket/messages-recv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@
return
}

let data: any

Check warning on line 186 in src/Socket/messages-recv.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
try {
data = JSON.parse(mexNode.content.toString())
} catch (error) {
Expand Down Expand Up @@ -279,7 +279,7 @@
case 'update':
const settingsNode = getBinaryNodeChild(child, 'settings')
if (settingsNode) {
const update: Record<string, any> = {}

Check warning on line 282 in src/Socket/messages-recv.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
const nameNode = getBinaryNodeChild(settingsNode, 'name')
if (nameNode?.content) update.name = nameNode.content.toString()

Expand Down Expand Up @@ -884,6 +884,12 @@
const handlePrivacyTokenNotification = async (node: BinaryNode) => {
const tokensNode = getBinaryNodeChild(node, 'tokens')
const from = jidNormalizedUser(node.attrs.from)
let lidForPN: string | null = null
try {
lidForPN = await signalRepository.lidMapping.getLIDForPN(from)
} catch (error) {
logger.warn({ error, jid: from }, 'Failed to get lid for PN in handlePrivacyTokenNotification.')
}

if (!tokensNode) return

Expand All @@ -907,6 +913,12 @@
await authState.keys.set({
tctoken: { [from]: { token: content, timestamp } }
})

if (lidForPN) {
await authState.keys.set({
tctoken: { [lidForPN]: { token: content, timestamp } }
})
}
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/Socket/messages-send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,8 +508,8 @@
const meLid = authState.creds.me?.lid
const meLidUser = meLid ? jidDecode(meLid)?.user : null

const encryptionPromises = (patchedMessages as any).map(

Check warning on line 511 in src/Socket/messages-send.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
async ({ recipientJid: jid, message: patchedMessage }: any) => {

Check warning on line 512 in src/Socket/messages-send.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
if (!jid) return null
let msgToEncrypt = patchedMessage
if (dsmMessage) {
Expand Down Expand Up @@ -1098,7 +1098,7 @@
content.url = getUrlFromDirectPath(content.directPath!)

logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
} catch (err: any) {

Check warning on line 1101 in src/Socket/messages-send.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
error = err
}
}
Expand All @@ -1118,6 +1118,10 @@
},
sendMessage: async (jid: string, content: AnyMessageContent, options: MiscMessageGenerationOptions = {}) => {
const userJid = authState.creds.me!.id
if (!options.messageId) {
options.messageId = generateMessageIDV2(sock.user?.id)

Check failure on line 1122 in src/Socket/messages-send.ts

View workflow job for this annotation

GitHub Actions / check-lint

Delete `·`
}

if (
typeof content === 'object' &&
'disappearingMessagesInChat' in content &&
Expand Down Expand Up @@ -1152,7 +1156,6 @@
upload: waUploadToServer,
mediaCache: config.mediaCache,
options: config.options,
messageId: generateMessageIDV2(sock.user?.id),
...options
})
const isEventMsg = 'event' in content && !!content.event
Expand Down
16 changes: 2 additions & 14 deletions src/Socket/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@

const msgId = node.attrs.id

const result = await promiseTimeout<any>(timeoutMs, async (resolve, reject) => {

Check warning on line 195 in src/Socket/socket.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
const result = waitForMessage(msgId, timeoutMs).catch(reject)
sendNode(node)
.then(async () => resolve(await result))
Expand Down Expand Up @@ -420,7 +420,7 @@
let node: proto.IClientPayload
if (!creds.me) {
node = generateRegistrationNode(creds, config)
logger.info({ node }, 'not logged in, attempting registration...')
//logger.info({ node }, 'not logged in, attempting registration...')
} else {
node = generateLoginNode(creds.me.id, config)
logger.info({ node }, 'logging in...')
Expand Down Expand Up @@ -612,7 +612,7 @@
}

closed = true
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
//logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')

clearInterval(keepAliveReq)
clearTimeout(qrTimer)
Expand Down Expand Up @@ -826,7 +826,7 @@
ws.on('open', async () => {
try {
await validateConnection()
} catch (err: any) {

Check warning on line 829 in src/Socket/socket.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
logger.error({ err }, 'error in validating connection')
end(err)
}
Expand Down Expand Up @@ -894,7 +894,7 @@
ev.emit('connection.update', { isNewLogin: true, qr: undefined })

await sendNode(reply)
} catch (error: any) {

Check warning on line 897 in src/Socket/socket.ts

View workflow job for this annotation

GitHub Actions / check-lint

Unexpected any. Specify a different type
logger.info({ trace: error.stack }, 'error in pairing')
end(error)
}
Expand Down Expand Up @@ -986,15 +986,7 @@
}
})

let didStartBuffer = false
process.nextTick(() => {
if (creds.me?.id) {
// start buffering important events
// if we're logged in
ev.buffer()
didStartBuffer = true
}

ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
})

Expand All @@ -1004,10 +996,6 @@
const offlineNotifs = +(child?.attrs.count || 0)

logger.info(`handled ${offlineNotifs} offline messages/notifications`)
if (didStartBuffer) {
ev.flush()
logger.trace('flushed events for initial buffer')
}

ev.emit('connection.update', { receivedPendingNotifications: true })
})
Expand Down
66 changes: 38 additions & 28 deletions src/Utils/messages-media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@
const hasher = Crypto.createHash('sha256')
const filePath = join(tmpdir(), mediaType + generateMessageIDV2())
const fileWriteStream = createWriteStream(filePath)

let fileLength = 0

try {
for await (const data of stream) {
fileLength += data.length
Expand All @@ -68,24 +68,20 @@
}
}

fileWriteStream.end()
await once(fileWriteStream, 'finish')
stream.destroy()
await waitForCloseOrFinishStream(fileWriteStream)

const fileSha256 = hasher.digest()
logger?.debug('hashed data for raw upload')

return {
filePath: filePath,
fileSha256,
fileLength
}
} catch (error) {
fileWriteStream.destroy()
stream.destroy()
try {
await fs.unlink(filePath)
} catch {
//
}
try { stream.destroy() } catch { }

Check failure on line 82 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Replace `·stream.destroy()·}·catch·{·` with `⏎↹↹↹stream.destroy()⏎↹↹}·catch·{`
await waitForCloseOrFinishStream(fileWriteStream)

Check failure on line 83 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Expected blank line before this statement
try { await fs.unlink(filePath) } catch { }

Check failure on line 84 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Replace `·await·fs.unlink(filePath)·}·catch·{·` with `⏎↹↹↹await·fs.unlink(filePath)⏎↹↹}·catch·{`

throw error
}
Expand Down Expand Up @@ -381,6 +377,13 @@
opts?: RequestInit
}

const waitForCloseOrFinishStream = async (stream?: WriteStream) => {
if (!stream) return;

Check failure on line 381 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Delete `;`
try { if (!stream.writableEnded) stream.end(); } catch { }

Check failure on line 382 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Replace `·if·(!stream.writableEnded)·stream.end();·}·catch·{·` with `⏎↹↹if·(!stream.writableEnded)·stream.end()⏎↹}·catch·{`
if (stream.destroyed || stream.closed || stream.writableFinished) return;

Check failure on line 383 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Delete `;`

Check failure on line 383 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Expected blank line before this statement
try { await Promise.race([once(stream, 'finish'), once(stream, 'close')]); } catch { }

Check failure on line 384 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Replace `·await·Promise.race([once(stream,·'finish'),·once(stream,·'close')]);·}·catch·{·` with `⏎↹↹await·Promise.race([once(stream,·'finish'),·once(stream,·'close')])⏎↹}·catch·{`
}

export const encryptedStream = async (
media: WAMediaUpload,
mediaType: MediaType,
Expand Down Expand Up @@ -410,10 +413,12 @@
const sha256Plain = Crypto.createHash('sha256')
const sha256Enc = Crypto.createHash('sha256')

const onChunk = (buff: Buffer) => {
const writeChunk = async (buff: Buffer) => {
if (!encFileWriteStream.write(buff)) {
await once(encFileWriteStream, 'drain')
}
sha256Enc.update(buff)

Check failure on line 420 in src/Utils/messages-media.ts

View workflow job for this annotation

GitHub Actions / check-lint

Expected blank line before this statement
hmac.update(buff)
encFileWriteStream.write(buff)
}

try {
Expand All @@ -437,22 +442,25 @@
}

sha256Plain.update(data)
onChunk(aes.update(data))
await writeChunk(aes.update(data))
}

onChunk(aes.final())
await writeChunk(aes.final())

const mac = hmac.digest().slice(0, 10)
sha256Enc.update(mac)

const fileSha256 = sha256Plain.digest()
const fileEncSha256 = sha256Enc.digest()

encFileWriteStream.write(mac)
if (!encFileWriteStream.write(mac)) {
await once(encFileWriteStream, 'drain')
}

encFileWriteStream.end()
originalFileStream?.end?.()
stream.destroy()
await Promise.allSettled([
waitForCloseOrFinishStream(encFileWriteStream),
waitForCloseOrFinishStream(originalFileStream)
])

logger?.debug('encrypted data successfully')

Expand All @@ -466,15 +474,13 @@
fileLength
}
} catch (error) {
// destroy all streams with error
encFileWriteStream.destroy()
originalFileStream?.destroy?.()
aes.destroy()
hmac.destroy()
sha256Plain.destroy()
sha256Enc.destroy()
stream.destroy()

try { stream.destroy() } catch { }
try {
await Promise.allSettled([
waitForCloseOrFinishStream(encFileWriteStream),
waitForCloseOrFinishStream(originalFileStream)
])
} catch { }
try {
await fs.unlink(encFilePath)
if (originalFilePath) {
Expand All @@ -483,6 +489,10 @@
} catch (err) {
logger?.error({ err }, 'failed deleting tmp files')
}
try { aes.destroy() } catch { }
try { hmac.destroy() } catch { }
try { sha256Plain.destroy() } catch { }
try { sha256Enc.destroy() } catch { }

throw error
}
Expand Down
18 changes: 9 additions & 9 deletions src/Utils/process-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,15 +264,15 @@ const processMessage = async (
const process = shouldProcessHistoryMsg
const isLatest = !creds.processedHistoryMessages?.length

logger?.info(
{
histNotification,
process,
id: message.key.id,
isLatest
},
'got history notification'
)
//logger?.info(
// {
// histNotification,
// process,
// id: message.key.id,
// isLatest
// },
// 'got history notification'
//)

if (process) {
// TODO: investigate
Expand Down
Loading