general: revert #1665

This commit is contained in:
Rajeh Taher
2025-10-03 18:14:30 +03:00
parent 55f09e8c84
commit 334977f983
29 changed files with 51841 additions and 3500 deletions
+2 -2
View File
@@ -1,3 +1,3 @@
yarn pbjs -t static-module --no-convert --no-beautify -w es6 --no-bundle --no-delimited --no-verify --no-comments -o ./index.js ./WAProto.proto; yarn pbjs -t static-module --no-beautify -w es6 --no-bundle --no-delimited --no-verify --no-comments -o ./index.js ./WAProto.proto;
yarn pbjs -t static-module --no-convert --no-beautify -w es6 --no-bundle --no-delimited --no-verify ./WAProto.proto | yarn pbts --no-comments -o ./index.d.ts -; yarn pbjs -t static-module --no-beautify -w es6 --no-bundle --no-delimited --no-verify ./WAProto.proto | yarn pbts --no-comments -o ./index.d.ts -;
node ./fix-imports.js node ./fix-imports.js
+289 -289
View File
File diff suppressed because it is too large Load Diff
+2795 -1514
View File
File diff suppressed because it is too large Load Diff
+48622 -1560
View File
File diff suppressed because it is too large Load Diff
@@ -1,7 +1,13 @@
import { proto } from '../../../WAProto/index.js' import { proto } from '../../../WAProto/index.js'
import { decodeAndHydrate } from '../../Utils/proto-utils'
import { CiphertextMessage } from './ciphertext-message' import { CiphertextMessage } from './ciphertext-message'
interface SenderKeyDistributionMessageStructure {
id: number
iteration: number
chainKey: Uint8Array
signingKey: Uint8Array
}
export class SenderKeyDistributionMessage extends CiphertextMessage { export class SenderKeyDistributionMessage extends CiphertextMessage {
private readonly id: number private readonly id: number
private readonly iteration: number private readonly iteration: number
@@ -21,7 +27,9 @@ export class SenderKeyDistributionMessage extends CiphertextMessage {
if (serialized) { if (serialized) {
try { try {
const message = serialized.slice(1) const message = serialized.slice(1)
const distributionMessage = decodeAndHydrate(proto.SenderKeyDistributionMessage, message) const distributionMessage = proto.SenderKeyDistributionMessage.decode(
message
).toJSON() as SenderKeyDistributionMessageStructure
this.serialized = serialized this.serialized = serialized
this.id = distributionMessage.id this.id = distributionMessage.id
+7 -2
View File
@@ -1,8 +1,13 @@
import { calculateSignature, verifySignature } from 'libsignal/src/curve' import { calculateSignature, verifySignature } from 'libsignal/src/curve'
import { proto } from '../../../WAProto/index.js' import { proto } from '../../../WAProto/index.js'
import { decodeAndHydrate } from '../../Utils/proto-utils'
import { CiphertextMessage } from './ciphertext-message' import { CiphertextMessage } from './ciphertext-message'
interface SenderKeyMessageStructure {
id: number
iteration: number
ciphertext: Buffer
}
export class SenderKeyMessage extends CiphertextMessage { export class SenderKeyMessage extends CiphertextMessage {
private readonly SIGNATURE_LENGTH = 64 private readonly SIGNATURE_LENGTH = 64
private readonly messageVersion: number private readonly messageVersion: number
@@ -25,7 +30,7 @@ export class SenderKeyMessage extends CiphertextMessage {
const version = serialized[0]! const version = serialized[0]!
const message = serialized.slice(1, serialized.length - this.SIGNATURE_LENGTH) const message = serialized.slice(1, serialized.length - this.SIGNATURE_LENGTH)
const signature = serialized.slice(-1 * this.SIGNATURE_LENGTH) const signature = serialized.slice(-1 * this.SIGNATURE_LENGTH)
const senderKeyMessage = decodeAndHydrate(proto.SenderKeyMessage, message) const senderKeyMessage = proto.SenderKeyMessage.decode(message).toJSON() as SenderKeyMessageStructure
this.serialized = serialized this.serialized = serialized
this.messageVersion = (version & 0xff) >> 4 this.messageVersion = (version & 0xff) >> 4
+1 -1
View File
@@ -368,7 +368,7 @@ export const makeCommunitiesSocket = (config: SocketConfig) => {
// update the invite message to be expired // update the invite message to be expired
if (key.id) { if (key.id) {
// create new invite message that is expired // create new invite message that is expired
inviteMessage = proto.Message.GroupInviteMessage.create(inviteMessage) inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
inviteMessage.inviteExpiration = 0 inviteMessage.inviteExpiration = 0
inviteMessage.inviteCode = '' inviteMessage.inviteCode = ''
ev.emit('messages.update', [ ev.emit('messages.update', [
+1 -1
View File
@@ -239,7 +239,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
// update the invite message to be expired // update the invite message to be expired
if (key.id) { if (key.id) {
// create new invite message that is expired // create new invite message that is expired
inviteMessage = proto.Message.GroupInviteMessage.create(inviteMessage) inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
inviteMessage.inviteExpiration = 0 inviteMessage.inviteExpiration = 0
inviteMessage.inviteCode = '' inviteMessage.inviteCode = ''
ev.emit('messages.update', [ ev.emit('messages.update', [
+10 -10
View File
@@ -11,6 +11,7 @@ import type {
SocketConfig, SocketConfig,
WACallEvent, WACallEvent,
WACallUpdateType, WACallUpdateType,
WAMessage,
WAMessageKey, WAMessageKey,
WAPatchName WAPatchName
} from '../Types' } from '../Types'
@@ -39,7 +40,6 @@ import {
xmppSignedPreKey xmppSignedPreKey
} from '../Utils' } from '../Utils'
import { makeMutex } from '../Utils/make-mutex' import { makeMutex } from '../Utils/make-mutex'
import { decodeAndHydrate } from '../Utils/proto-utils'
import { import {
areJidsSameUser, areJidsSameUser,
type BinaryNode, type BinaryNode,
@@ -294,8 +294,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
typeof plaintextNode.content === 'string' typeof plaintextNode.content === 'string'
? Buffer.from(plaintextNode.content, 'binary') ? Buffer.from(plaintextNode.content, 'binary')
: Buffer.from(plaintextNode.content as Uint8Array) : Buffer.from(plaintextNode.content as Uint8Array)
const messageProto = decodeAndHydrate(proto.Message, contentBuf) const messageProto = proto.Message.decode(contentBuf).toJSON()
const fullMessage = proto.WebMessageInfo.create({ const fullMessage = proto.WebMessageInfo.fromObject({
key: { key: {
remoteJid: from, remoteJid: from,
id: child.attrs.message_id || child.attrs.server_id, id: child.attrs.message_id || child.attrs.server_id,
@@ -303,7 +303,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}, },
message: messageProto, message: messageProto,
messageTimestamp: +child.attrs.t! messageTimestamp: +child.attrs.t!
}) }).toJSON() as WAMessage
await upsertMessage(fullMessage, 'append') await upsertMessage(fullMessage, 'append')
logger.info('Processed plaintext newsletter message') logger.info('Processed plaintext newsletter message')
} catch (error) { } catch (error) {
@@ -546,7 +546,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
} }
} }
const handleGroupNotification = (participant: string, child: BinaryNode, msg: Partial<proto.IWebMessageInfo>) => { const handleGroupNotification = (participant: string, child: BinaryNode, msg: Partial<WAMessage>) => {
const participantJid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || participant const participantJid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || participant
// TODO: Add participant LID // TODO: Add participant LID
switch (child?.tag) { switch (child?.tag) {
@@ -658,7 +658,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
} }
const processNotification = async (node: BinaryNode) => { const processNotification = async (node: BinaryNode) => {
const result: Partial<proto.IWebMessageInfo> = {} const result: Partial<WAMessage> = {}
const [child] = getAllBinaryNodeChildren(node) const [child] = getAllBinaryNodeChildren(node)
const nodeType = node.attrs.type const nodeType = node.attrs.type
const from = jidNormalizedUser(node.attrs.from) const from = jidNormalizedUser(node.attrs.from)
@@ -874,7 +874,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
await msgRetryCache.set(key, newValue) await msgRetryCache.set(key, newValue)
} }
const sendMessagesAgain = async (key: proto.IMessageKey, ids: string[], retryNode: BinaryNode) => { const sendMessagesAgain = async (key: WAMessageKey, ids: string[], retryNode: BinaryNode) => {
const remoteJid = key.remoteJid! const remoteJid = key.remoteJid!
const participant = key.participant || remoteJid const participant = key.participant || remoteJid
@@ -1089,7 +1089,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
msg.participant ??= node.attrs.participant msg.participant ??= node.attrs.participant
msg.messageTimestamp = +node.attrs.t! msg.messageTimestamp = +node.attrs.t!
const fullMsg = proto.WebMessageInfo.create(msg as proto.IWebMessageInfo) const fullMsg = proto.WebMessageInfo.fromObject(msg) as WAMessage
await upsertMessage(fullMsg, 'append') await upsertMessage(fullMsg, 'append')
} }
}) })
@@ -1445,7 +1445,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
// missed call + group call notification message generation // missed call + group call notification message generation
if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) { if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
const msg: proto.IWebMessageInfo = { const msg: WAMessage = {
key: { key: {
remoteJid: call.chatId, remoteJid: call.chatId,
id: call.id, id: call.id,
@@ -1465,7 +1465,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
msg.message = { call: { callKey: Buffer.from(call.id) } } msg.message = { call: { callKey: Buffer.from(call.id) } }
} }
const protoMsg = proto.WebMessageInfo.create(msg) const protoMsg = proto.WebMessageInfo.fromObject(msg) as WAMessage
upsertMessage(protoMsg, call.offline ? 'append' : 'notify') upsertMessage(protoMsg, call.offline ? 'append' : 'notify')
} }
}) })
+5 -4
View File
@@ -9,6 +9,7 @@ import type {
MessageRelayOptions, MessageRelayOptions,
MiscMessageGenerationOptions, MiscMessageGenerationOptions,
SocketConfig, SocketConfig,
WAMessage,
WAMessageKey WAMessageKey
} from '../Types' } from '../Types'
import { import {
@@ -1018,7 +1019,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
createParticipantNodes, createParticipantNodes,
getUSyncDevices, getUSyncDevices,
messageRetryManager, messageRetryManager,
updateMediaMessage: async (message: proto.IWebMessageInfo) => { updateMediaMessage: async (message: WAMessage) => {
const content = assertMediaContent(message.message) const content = assertMediaContent(message.message)
const mediaKey = content.mediaKey! const mediaKey = content.mediaKey!
const meId = authState.creds.me!.id const meId = authState.creds.me!.id
@@ -1036,15 +1037,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
try { try {
const media = await decryptMediaRetryData(result.media!, mediaKey, result.key.id!) const media = await decryptMediaRetryData(result.media!, mediaKey, result.key.id!)
if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) { if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
const resultStr = proto.MediaRetryNotification.ResultType[media.result] const resultStr = proto.MediaRetryNotification.ResultType[media.result!]
throw new Boom(`Media re-upload failed by device (${resultStr})`, { throw new Boom(`Media re-upload failed by device (${resultStr})`, {
data: media, data: media,
statusCode: getStatusCodeForMediaRetry(media.result) || 404 statusCode: getStatusCodeForMediaRetry(media.result!) || 404
}) })
} }
content.directPath = media.directPath content.directPath = media.directPath
content.url = getUrlFromDirectPath(content.directPath) content.url = getUrlFromDirectPath(content.directPath!)
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful') logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
} catch (err: any) { } catch (err: any) {
+2 -3
View File
@@ -33,7 +33,6 @@ import {
promiseTimeout promiseTimeout
} from '../Utils' } from '../Utils'
import { getPlatformId } from '../Utils/browser-utils' import { getPlatformId } from '../Utils/browser-utils'
import { decodeAndHydrate } from '../Utils/proto-utils'
import { import {
assertNodeErrorFree, assertNodeErrorFree,
type BinaryNode, type BinaryNode,
@@ -366,14 +365,14 @@ export const makeSocket = (config: SocketConfig) => {
let helloMsg: proto.IHandshakeMessage = { let helloMsg: proto.IHandshakeMessage = {
clientHello: { ephemeral: ephemeralKeyPair.public } clientHello: { ephemeral: ephemeralKeyPair.public }
} }
helloMsg = proto.HandshakeMessage.create(helloMsg) helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
logger.info({ browser, helloMsg }, 'connected to WA') logger.info({ browser, helloMsg }, 'connected to WA')
const init = proto.HandshakeMessage.encode(helloMsg).finish() const init = proto.HandshakeMessage.encode(helloMsg).finish()
const result = await awaitNextMessage<Uint8Array>(init) const result = await awaitNextMessage<Uint8Array>(init)
const handshake = decodeAndHydrate(proto.HandshakeMessage, result) const handshake = proto.HandshakeMessage.decode(result)
logger.trace({ handshake }, 'handshake recv from WA') logger.trace({ handshake }, 'handshake recv from WA')
+1 -1
View File
@@ -23,7 +23,7 @@ export type BaileysEventMap = {
messages: WAMessage[] messages: WAMessage[]
isLatest?: boolean isLatest?: boolean
progress?: number | null progress?: number | null
syncType?: proto.HistorySync.HistorySyncType syncType?: proto.HistorySync.HistorySyncType | null
peerDataRequestSessionId?: string | null peerDataRequestSessionId?: string | null
} }
/** upsert chats */ /** upsert chats */
+3 -3
View File
@@ -357,11 +357,11 @@ export type MessageUpsertType = 'append' | 'notify'
export type MessageUserReceipt = proto.IUserReceipt export type MessageUserReceipt = proto.IUserReceipt
export type WAMessageUpdate = { update: Partial<WAMessage>; key: proto.IMessageKey } export type WAMessageUpdate = { update: Partial<WAMessage>; key: WAMessageKey }
export type WAMessageCursor = { before: WAMessageKey | undefined } | { after: WAMessageKey | undefined } export type WAMessageCursor = { before: WAMessageKey | undefined } | { after: WAMessageKey | undefined }
export type MessageUserReceiptUpdate = { key: proto.IMessageKey; receipt: MessageUserReceipt } export type MessageUserReceiptUpdate = { key: WAMessageKey; receipt: MessageUserReceipt }
export type MediaDecryptionKeyInfo = { export type MediaDecryptionKeyInfo = {
iv: Buffer iv: Buffer
@@ -369,4 +369,4 @@ export type MediaDecryptionKeyInfo = {
macKey?: Buffer macKey?: Buffer
} }
export type MinimalMessage = Pick<proto.IWebMessageInfo, 'key' | 'messageTimestamp'> export type MinimalMessage = Pick<WAMessage, 'key' | 'messageTimestamp'>
+2 -2
View File
@@ -4,7 +4,7 @@ import { proto } from '../../WAProto/index.js'
import type { ILogger } from '../Utils/logger' import type { ILogger } from '../Utils/logger'
import type { AuthenticationState, LIDMapping, SignalAuthState, TransactionCapabilityOptions } from './Auth' import type { AuthenticationState, LIDMapping, SignalAuthState, TransactionCapabilityOptions } from './Auth'
import type { GroupMetadata } from './GroupMetadata' import type { GroupMetadata } from './GroupMetadata'
import { type MediaConnInfo } from './Message' import { type MediaConnInfo, type WAMessageKey } from './Message'
import type { SignalRepositoryWithLIDStore } from './Signal' import type { SignalRepositoryWithLIDStore } from './Signal'
export type WAVersion = [number, number, number] export type WAVersion = [number, number, number]
@@ -137,7 +137,7 @@ export type SocketConfig = {
* implement this so that messages failed to send * implement this so that messages failed to send
* (solves the "this message can take a while" issue) can be retried * (solves the "this message can take a while" issue) can be retried
* */ * */
getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined> getMessage: (key: WAMessageKey) => Promise<proto.IMessage | undefined>
/** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */ /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined> cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>
+8 -9
View File
@@ -24,7 +24,6 @@ import { toNumber } from './generics'
import type { ILogger } from './logger' import type { ILogger } from './logger'
import { LT_HASH_ANTI_TAMPERING } from './lt-hash' import { LT_HASH_ANTI_TAMPERING } from './lt-hash'
import { downloadContentFromMessage } from './messages-media' import { downloadContentFromMessage } from './messages-media'
import { decodeAndHydrate } from './proto-utils'
type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined> type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>
@@ -154,7 +153,7 @@ export const encodeSyncdPatch = async (
state = { ...state, indexValueMap: { ...state.indexValueMap } } state = { ...state, indexValueMap: { ...state.indexValueMap } }
const indexBuffer = Buffer.from(JSON.stringify(index)) const indexBuffer = Buffer.from(JSON.stringify(index))
const dataProto = proto.SyncActionData.create({ const dataProto = proto.SyncActionData.fromObject({
index: indexBuffer, index: indexBuffer,
value: syncAction, value: syncAction,
padding: new Uint8Array(0), padding: new Uint8Array(0),
@@ -233,16 +232,16 @@ export const decodeSyncdMutations = async (
} }
const result = aesDecrypt(encContent, key.valueEncryptionKey) const result = aesDecrypt(encContent, key.valueEncryptionKey)
const syncAction = decodeAndHydrate(proto.SyncActionData, result) const syncAction = proto.SyncActionData.decode(result)
if (validateMacs) { if (validateMacs) {
const hmac = hmacSign(syncAction.index, key.indexKey) const hmac = hmacSign(syncAction.index!, key.indexKey)
if (Buffer.compare(hmac, record.index!.blob!) !== 0) { if (Buffer.compare(hmac, record.index!.blob!) !== 0) {
throw new Boom('HMAC index verification failed') throw new Boom('HMAC index verification failed')
} }
} }
const indexStr = Buffer.from(syncAction.index).toString() const indexStr = Buffer.from(syncAction.index!).toString()
onMutation({ syncAction, index: JSON.parse(indexStr) }) onMutation({ syncAction, index: JSON.parse(indexStr) })
ltGenerator.mix({ ltGenerator.mix({
@@ -327,9 +326,9 @@ export const extractSyncdPatches = async (result: BinaryNode, options: RequestIn
snapshotNode.content = Buffer.from(Object.values(snapshotNode.content)) snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
} }
const blobRef = decodeAndHydrate(proto.ExternalBlobReference, snapshotNode.content as Buffer) const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content as Buffer)
const data = await downloadExternalBlob(blobRef, options) const data = await downloadExternalBlob(blobRef, options)
snapshot = decodeAndHydrate(proto.SyncdSnapshot, data) snapshot = proto.SyncdSnapshot.decode(data)
} }
for (let { content } of patches) { for (let { content } of patches) {
@@ -338,7 +337,7 @@ export const extractSyncdPatches = async (result: BinaryNode, options: RequestIn
content = Buffer.from(Object.values(content)) content = Buffer.from(Object.values(content))
} }
const syncd = decodeAndHydrate(proto.SyncdPatch, content as Uint8Array) const syncd = proto.SyncdPatch.decode(content as Uint8Array)
if (!syncd.version) { if (!syncd.version) {
syncd.version = { version: +collectionNode.attrs.version! + 1 } syncd.version = { version: +collectionNode.attrs.version! + 1 }
} }
@@ -366,7 +365,7 @@ export const downloadExternalBlob = async (blob: proto.IExternalBlobReference, o
export const downloadExternalPatch = async (blob: proto.IExternalBlobReference, options: RequestInit) => { export const downloadExternalPatch = async (blob: proto.IExternalBlobReference, options: RequestInit) => {
const buffer = await downloadExternalBlob(blob, options) const buffer = await downloadExternalBlob(blob, options)
const syncData = decodeAndHydrate(proto.SyncdMutations, buffer) const syncData = proto.SyncdMutations.decode(buffer)
return syncData return syncData
} }
+3 -5
View File
@@ -18,7 +18,6 @@ import {
} from '../WABinary' } from '../WABinary'
import { unpadRandomMax16 } from './generics' import { unpadRandomMax16 } from './generics'
import type { ILogger } from './logger' import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
const getDecryptionJid = async (sender: string, repository: SignalRepositoryWithLIDStore): Promise<string> => { const getDecryptionJid = async (sender: string, repository: SignalRepositoryWithLIDStore): Promise<string> => {
if (sender.includes('@lid')) { if (sender.includes('@lid')) {
@@ -239,8 +238,8 @@ export const decryptMessageNode = (
if (Array.isArray(stanza.content)) { if (Array.isArray(stanza.content)) {
for (const { tag, attrs, content } of stanza.content) { for (const { tag, attrs, content } of stanza.content) {
if (tag === 'verified_name' && content instanceof Uint8Array) { if (tag === 'verified_name' && content instanceof Uint8Array) {
const cert = decodeAndHydrate(proto.VerifiedNameCertificate, content) const cert = proto.VerifiedNameCertificate.decode(content)
const details = proto.VerifiedNameCertificate.Details.decode(cert.details) const details = proto.VerifiedNameCertificate.Details.decode(cert.details!)
fullMessage.verifiedBizName = details.verifiedName fullMessage.verifiedBizName = details.verifiedName
} }
@@ -294,8 +293,7 @@ export const decryptMessageNode = (
throw new Error(`Unknown e2e type: ${e2eType}`) throw new Error(`Unknown e2e type: ${e2eType}`)
} }
let msg: proto.IMessage = decodeAndHydrate( let msg: proto.IMessage = proto.Message.decode(
proto.Message,
e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer
) )
msg = msg.deviceSentMessage?.message || msg msg = msg.deviceSentMessage?.message || msg
+17 -15
View File
@@ -1,5 +1,4 @@
import EventEmitter from 'events' import EventEmitter from 'events'
import { proto } from '../../WAProto/index.js'
import type { import type {
BaileysEvent, BaileysEvent,
BaileysEventEmitter, BaileysEventEmitter,
@@ -8,7 +7,8 @@ import type {
Chat, Chat,
ChatUpdate, ChatUpdate,
Contact, Contact,
WAMessage WAMessage,
WAMessageKey
} from '../Types' } from '../Types'
import { WAMessageStatus } from '../Types' import { WAMessageStatus } from '../Types'
import { trimUndefined } from './generics' import { trimUndefined } from './generics'
@@ -241,14 +241,15 @@ function append<E extends BufferableEvent>(
switch (event) { switch (event) {
case 'messaging-history.set': case 'messaging-history.set':
for (const chat of eventData.chats as Chat[]) { for (const chat of eventData.chats as Chat[]) {
const existingChat = data.historySets.chats[chat.id] const id = chat.id || ''
const existingChat = data.historySets.chats[id]
if (existingChat) { if (existingChat) {
existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
} }
if (!existingChat && !historyCache.has(chat.id)) { if (!existingChat && !historyCache.has(id)) {
data.historySets.chats[chat.id] = chat data.historySets.chats[id] = chat
historyCache.add(chat.id) historyCache.add(id)
absorbingChatUpdate(chat) absorbingChatUpdate(chat)
} }
@@ -286,11 +287,12 @@ function append<E extends BufferableEvent>(
break break
case 'chats.upsert': case 'chats.upsert':
for (const chat of eventData as Chat[]) { for (const chat of eventData as Chat[]) {
let upsert = data.chatUpserts[chat.id] const id = chat.id || ''
if (!upsert) { let upsert = data.chatUpserts[id]
upsert = data.historySets.chats[chat.id] if (id && !upsert) {
upsert = data.historySets.chats[id]
if (upsert) { if (upsert) {
logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set') logger.debug({ chatId: id }, 'absorbed chat upsert in chat set')
} }
} }
@@ -298,13 +300,13 @@ function append<E extends BufferableEvent>(
upsert = concatChats(upsert, chat) upsert = concatChats(upsert, chat)
} else { } else {
upsert = chat upsert = chat
data.chatUpserts[chat.id] = upsert data.chatUpserts[id] = upsert
} }
absorbingChatUpdate(upsert) absorbingChatUpdate(upsert)
if (data.chatDeletes.has(chat.id)) { if (data.chatDeletes.has(id)) {
data.chatDeletes.delete(chat.id) data.chatDeletes.delete(id)
} }
} }
@@ -521,7 +523,7 @@ function append<E extends BufferableEvent>(
} }
function absorbingChatUpdate(existing: Chat) { function absorbingChatUpdate(existing: Chat) {
const chatId = existing.id const chatId = existing.id || ''
const update = data.chatUpdates[chatId] const update = data.chatUpdates[chatId]
if (update) { if (update) {
const conditionMatches = update.conditional ? update.conditional(data) : true const conditionMatches = update.conditional ? update.conditional(data) : true
@@ -657,4 +659,4 @@ function concatChats<C extends Partial<Chat>>(a: C, b: Partial<Chat>) {
return Object.assign(a, b) return Object.assign(a, b)
} }
const stringifyMessageKey = (key: proto.IMessageKey) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}` const stringifyMessageKey = (key: WAMessageKey) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`
+9 -2
View File
@@ -2,7 +2,14 @@ import { Boom } from '@hapi/boom'
import { createHash, randomBytes } from 'crypto' import { createHash, randomBytes } from 'crypto'
import { proto } from '../../WAProto/index.js' import { proto } from '../../WAProto/index.js'
const baileysVersion = [2, 3000, 1023223821] const baileysVersion = [2, 3000, 1023223821]
import type { BaileysEventEmitter, BaileysEventMap, ConnectionState, WACallUpdateType, WAVersion } from '../Types' import type {
BaileysEventEmitter,
BaileysEventMap,
ConnectionState,
WACallUpdateType,
WAMessageKey,
WAVersion
} from '../Types'
import { DisconnectReason } from '../Types' import { DisconnectReason } from '../Types'
import { type BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary' import { type BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary'
import { sha256 } from './crypto' import { sha256 } from './crypto'
@@ -37,7 +44,7 @@ export const BufferJSON = {
} }
} }
export const getKeyAuthor = (key: proto.IMessageKey | undefined | null, meId = 'me') => export const getKeyAuthor = (key: WAMessageKey | undefined | null, meId = 'me') =>
(key?.fromMe ? meId : key?.participant || key?.remoteJid) || '' (key?.fromMe ? meId : key?.participant || key?.remoteJid) || ''
export const writeRandomPadMax16 = (msg: Uint8Array) => { export const writeRandomPadMax16 = (msg: Uint8Array) => {
+6 -7
View File
@@ -1,12 +1,11 @@
import { promisify } from 'util' import { promisify } from 'util'
import { inflate } from 'zlib' import { inflate } from 'zlib'
import { proto } from '../../WAProto/index.js' import { proto } from '../../WAProto/index.js'
import type { Chat, Contact } from '../Types' import type { Chat, Contact, WAMessage } from '../Types'
import { WAMessageStubType } from '../Types' import { WAMessageStubType } from '../Types'
import { toNumber } from './generics' import { toNumber } from './generics'
import { normalizeMessageContent } from './messages' import { normalizeMessageContent } from './messages'
import { downloadContentFromMessage } from './messages-media' import { downloadContentFromMessage } from './messages-media'
import { decodeAndHydrate } from './proto-utils'
const inflatePromise = promisify(inflate) const inflatePromise = promisify(inflate)
@@ -22,12 +21,12 @@ export const downloadHistory = async (msg: proto.Message.IHistorySyncNotificatio
// decompress buffer // decompress buffer
buffer = await inflatePromise(buffer) buffer = await inflatePromise(buffer)
const syncData = decodeAndHydrate(proto.HistorySync, buffer) const syncData = proto.HistorySync.decode(buffer)
return syncData return syncData
} }
export const processHistoryMessage = (item: proto.IHistorySync) => { export const processHistoryMessage = (item: proto.IHistorySync) => {
const messages: proto.IWebMessageInfo[] = [] const messages: WAMessage[] = []
const contacts: Contact[] = [] const contacts: Contact[] = []
const chats: Chat[] = [] const chats: Chat[] = []
@@ -38,7 +37,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
case proto.HistorySync.HistorySyncType.ON_DEMAND: case proto.HistorySync.HistorySyncType.ON_DEMAND:
for (const chat of item.conversations! as Chat[]) { for (const chat of item.conversations! as Chat[]) {
contacts.push({ contacts.push({
id: chat.id, id: chat.id!,
name: chat.name || undefined, name: chat.name || undefined,
lid: chat.lidJid || undefined, lid: chat.lidJid || undefined,
phoneNumber: chat.pnJid || undefined phoneNumber: chat.pnJid || undefined
@@ -48,7 +47,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
delete chat.messages delete chat.messages
for (const item of msgs) { for (const item of msgs) {
const message = item.message! const message = item.message! as WAMessage
messages.push(message) messages.push(message)
if (!chat.messages?.length) { if (!chat.messages?.length) {
@@ -103,7 +102,7 @@ export const downloadAndProcessHistorySyncNotification = async (
export const getHistoryMsg = (message: proto.IMessage) => { export const getHistoryMsg = (message: proto.IMessage) => {
const normalizedContent = !!message ? normalizeMessageContent(message) : undefined const normalizedContent = !!message ? normalizeMessageContent(message) : undefined
const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification!
return anyHistoryMsg return anyHistoryMsg
} }
-1
View File
@@ -17,4 +17,3 @@ export * from './event-buffer'
export * from './process-message' export * from './process-message'
export * from './message-retry-manager' export * from './message-retry-manager'
export * from './browser-utils' export * from './browser-utils'
export * from './proto-utils'
+4 -4
View File
@@ -20,13 +20,13 @@ import type {
WAGenericMediaMessage, WAGenericMediaMessage,
WAMediaUpload, WAMediaUpload,
WAMediaUploadFunction, WAMediaUploadFunction,
WAMessageContent WAMessageContent,
WAMessageKey
} from '../Types' } from '../Types'
import { type BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary' import { type BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto' import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
import { generateMessageIDV2 } from './generics' import { generateMessageIDV2 } from './generics'
import type { ILogger } from './logger' import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
const getTmpFilesDirectory = () => tmpdir() const getTmpFilesDirectory = () => tmpdir()
@@ -724,7 +724,7 @@ const getMediaRetryKey = (mediaKey: Buffer | Uint8Array) => {
/** /**
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
*/ */
export const encryptMediaRetryRequest = async (key: proto.IMessageKey, mediaKey: Buffer | Uint8Array, meId: string) => { export const encryptMediaRetryRequest = async (key: WAMessageKey, mediaKey: Buffer | Uint8Array, meId: string) => {
const recp: proto.IServerErrorReceipt = { stanzaId: key.id } const recp: proto.IServerErrorReceipt = { stanzaId: key.id }
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish() const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
@@ -806,7 +806,7 @@ export const decryptMediaRetryData = async (
) => { ) => {
const retryKey = await getMediaRetryKey(mediaKey) const retryKey = await getMediaRetryKey(mediaKey)
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId)) const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
return decodeAndHydrate(proto.MediaRetryNotification, plaintext) return proto.MediaRetryNotification.decode(plaintext)
} }
export const getStatusCodeForMediaRetry = (code: number) => export const getStatusCodeForMediaRetry = (code: number) =>
+10 -10
View File
@@ -23,6 +23,7 @@ import type {
WAMediaUpload, WAMediaUpload,
WAMessage, WAMessage,
WAMessageContent, WAMessageContent,
WAMessageKey,
WATextMessage WATextMessage
} from '../Types' } from '../Types'
import { WAMessageStatus, WAProto } from '../Types' import { WAMessageStatus, WAProto } from '../Types'
@@ -39,7 +40,6 @@ import {
getRawMediaUploadData, getRawMediaUploadData,
type MediaDownloadOptions type MediaDownloadOptions
} from './messages-media' } from './messages-media'
import { decodeAndHydrate } from './proto-utils'
type MediaUploadData = { type MediaUploadData = {
media: WAMediaUpload media: WAMediaUpload
@@ -156,7 +156,7 @@ export const prepareWAMessageMedia = async (
if (mediaBuff) { if (mediaBuff) {
logger?.debug({ cacheableKey }, 'got media cache hit') logger?.debug({ cacheableKey }, 'got media cache hit')
const obj = decodeAndHydrate(proto.Message, mediaBuff) const obj = proto.Message.decode(mediaBuff)
const key = `${mediaType}Message` const key = `${mediaType}Message`
Object.assign(obj[key as keyof proto.Message]!, { ...uploadData, media: undefined }) Object.assign(obj[key as keyof proto.Message]!, { ...uploadData, media: undefined })
@@ -183,9 +183,9 @@ export const prepareWAMessageMedia = async (
await fs.unlink(filePath) await fs.unlink(filePath)
const obj = WAProto.Message.create({ const obj = WAProto.Message.fromObject({
// todo: add more support here // todo: add more support here
[`${mediaType}Message`]: (MessageTypeProto as any)[mediaType].create({ [`${mediaType}Message`]: (MessageTypeProto as any)[mediaType].fromObject({
url: mediaUrl, url: mediaUrl,
directPath, directPath,
fileSha256, fileSha256,
@@ -288,8 +288,8 @@ export const prepareWAMessageMedia = async (
} }
}) })
const obj = WAProto.Message.create({ const obj = WAProto.Message.fromObject({
[`${mediaType}Message`]: MessageTypeProto[mediaType as keyof typeof MessageTypeProto].create({ [`${mediaType}Message`]: MessageTypeProto[mediaType as keyof typeof MessageTypeProto].fromObject({
url: mediaUrl, url: mediaUrl,
directPath, directPath,
mediaKey, mediaKey,
@@ -327,7 +327,7 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration?: n
} }
} }
} }
return WAProto.Message.create(content) return WAProto.Message.fromObject(content)
} }
/** /**
@@ -343,7 +343,7 @@ export const generateForwardMessageContent = (message: WAMessage, forceForward?:
// hacky copy // hacky copy
content = normalizeMessageContent(content) content = normalizeMessageContent(content)
content = decodeAndHydrate(proto.Message, proto.Message.encode(content!).finish()) content = proto.Message.decode(proto.Message.encode(content!).finish())
let key = Object.keys(content)[0] as keyof proto.IMessage let key = Object.keys(content)[0] as keyof proto.IMessage
@@ -691,7 +691,7 @@ export const generateWAMessageFromContent = (
participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
status: WAMessageStatus.PENDING status: WAMessageStatus.PENDING
} }
return WAProto.WebMessageInfo.create(messageJSON) return WAProto.WebMessageInfo.fromObject(messageJSON) as WAMessage
} }
export const generateWAMessage = async (jid: string, content: AnyMessageContent, options: MessageGenerationOptions) => { export const generateWAMessage = async (jid: string, content: AnyMessageContent, options: MessageGenerationOptions) => {
@@ -894,7 +894,7 @@ export function getAggregateVotesInPollMessage(
} }
/** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
export const aggregateMessageKeysNotFromMe = (keys: proto.IMessageKey[]) => { export const aggregateMessageKeysNotFromMe = (keys: WAMessageKey[]) => {
const keyMap: { [id: string]: { jid: string; participant: string | undefined; messageIds: string[] } } = {} const keyMap: { [id: string]: { jid: string; participant: string | undefined; messageIds: string[] } } = {}
for (const { remoteJid, id, participant, fromMe } of keys) { for (const { remoteJid, id, participant, fromMe } of keys) {
if (!fromMe) { if (!fromMe) {
+1 -2
View File
@@ -6,7 +6,6 @@ import type { BinaryNode } from '../WABinary'
import { decodeBinaryNode } from '../WABinary' import { decodeBinaryNode } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto' import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto'
import type { ILogger } from './logger' import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
const generateIV = (counter: number) => { const generateIV = (counter: number) => {
const iv = new ArrayBuffer(12) const iv = new ArrayBuffer(12)
@@ -113,7 +112,7 @@ export const makeNoiseHandler = ({
const certDecoded = decrypt(serverHello!.payload!) const certDecoded = decrypt(serverHello!.payload!)
const { intermediate: certIntermediate } = decodeAndHydrate(proto.CertChain, certDecoded) const { intermediate: certIntermediate } = proto.CertChain.decode(certDecoded)
const { issuerSerial } = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate!.details!) const { issuerSerial } = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate!.details!)
+15 -16
View File
@@ -9,7 +9,9 @@ import type {
RequestJoinAction, RequestJoinAction,
RequestJoinMethod, RequestJoinMethod,
SignalKeyStoreWithTransaction, SignalKeyStoreWithTransaction,
SignalRepositoryWithLIDStore SignalRepositoryWithLIDStore,
WAMessage,
WAMessageKey
} from '../Types' } from '../Types'
import { WAMessageStubType } from '../Types' import { WAMessageStubType } from '../Types'
import { getContentType, normalizeMessageContent } from '../Utils/messages' import { getContentType, normalizeMessageContent } from '../Utils/messages'
@@ -27,7 +29,6 @@ import { aesDecryptGCM, hmacSign } from './crypto'
import { toNumber } from './generics' import { toNumber } from './generics'
import { downloadAndProcessHistorySyncNotification } from './history' import { downloadAndProcessHistorySyncNotification } from './history'
import type { ILogger } from './logger' import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
type ProcessMessageContext = { type ProcessMessageContext = {
shouldProcessHistoryMsg: boolean shouldProcessHistoryMsg: boolean
@@ -50,11 +51,11 @@ const REAL_MSG_STUB_TYPES = new Set([
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]) const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
/** Cleans a received message to further processing */ /** Cleans a received message to further processing */
export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => { export const cleanMessage = (message: WAMessage, meId: string) => {
// ensure remoteJid and participant doesn't have device or agent in it // ensure remoteJid and participant doesn't have device or agent in it
if (isJidHostedPnUser(message.key.remoteJid!) || isJidHostedLidUser(message.key.remoteJid!)) { if (isJidHostedPnUser(message.key.remoteJid!) || isJidHostedLidUser(message.key.remoteJid!)) {
message.key.remoteJid = jidEncode( message.key.remoteJid = jidEncode(
jidDecode(message.key.remoteJid!)?.user!, jidDecode(message.key?.remoteJid!)?.user!,
isJidHostedPnUser(message.key.remoteJid!) ? 's.whatsapp.net' : 'lid' isJidHostedPnUser(message.key.remoteJid!) ? 's.whatsapp.net' : 'lid'
) )
} else { } else {
@@ -80,7 +81,7 @@ export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!) normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!)
} }
function normaliseKey(msgKey: proto.IMessageKey) { function normaliseKey(msgKey: WAMessageKey) {
// if the reaction is from another user // if the reaction is from another user
// we've to correctly map the key to this user's perspective // we've to correctly map the key to this user's perspective
if (!message.key.fromMe) { if (!message.key.fromMe) {
@@ -100,7 +101,7 @@ export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
} }
} }
export const isRealMessage = (message: proto.IWebMessageInfo, meId: string) => { export const isRealMessage = (message: WAMessage, meId: string) => {
const normalizedContent = normalizeMessageContent(message.message) const normalizedContent = normalizeMessageContent(message.message)
const hasSomeContent = !!getContentType(normalizedContent) const hasSomeContent = !!getContentType(normalizedContent)
return ( return (
@@ -115,14 +116,13 @@ export const isRealMessage = (message: proto.IWebMessageInfo, meId: string) => {
) )
} }
export const shouldIncrementChatUnread = (message: proto.IWebMessageInfo) => export const shouldIncrementChatUnread = (message: WAMessage) => !message.key.fromMe && !message.messageStubType
!message.key.fromMe && !message.messageStubType
/** /**
* Get the ID of the chat from the given key. * Get the ID of the chat from the given key.
* Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
*/ */
export const getChatId = ({ remoteJid, participant, fromMe }: proto.IMessageKey) => { export const getChatId = ({ remoteJid, participant, fromMe }: WAMessageKey) => {
if (isJidBroadcast(remoteJid!) && !isJidStatusBroadcast(remoteJid!) && !fromMe) { if (isJidBroadcast(remoteJid!) && !isJidStatusBroadcast(remoteJid!) && !fromMe) {
return participant! return participant!
} }
@@ -172,7 +172,7 @@ export function decryptPollVote(
} }
const processMessage = async ( const processMessage = async (
message: proto.IWebMessageInfo, message: WAMessage,
{ {
shouldProcessHistoryMsg, shouldProcessHistoryMsg,
placeholderResendCache, placeholderResendCache,
@@ -297,11 +297,12 @@ const processMessage = async (
const { placeholderMessageResendResponse: retryResponse } = result const { placeholderMessageResendResponse: retryResponse } = result
//eslint-disable-next-line max-depth //eslint-disable-next-line max-depth
if (retryResponse) { if (retryResponse) {
const webMessageInfo = decodeAndHydrate(proto.WebMessageInfo, retryResponse.webMessageInfoBytes!) const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes!)
// wait till another upsert event is available, don't want it to be part of the PDO response message // wait till another upsert event is available, don't want it to be part of the PDO response message
// TODO: parse through proper message handling utilities (to add relevant key fields)
setTimeout(() => { setTimeout(() => {
ev.emit('messages.upsert', { ev.emit('messages.upsert', {
messages: [webMessageInfo], messages: [webMessageInfo as WAMessage],
type: 'notify', type: 'notify',
requestId: response.stanzaId! requestId: response.stanzaId!
}) })
@@ -331,10 +332,8 @@ const processMessage = async (
break break
case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC: case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload! const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload!
const { pnToLidMappings, chatDbMigrationTimestamp } = decodeAndHydrate( const { pnToLidMappings, chatDbMigrationTimestamp } =
proto.LIDMigrationMappingSyncPayload, proto.LIDMigrationMappingSyncPayload.decode(encodedPayload)
encodedPayload
)
logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp') logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp')
const pairs = [] const pairs = []
for (const { pn, latestLid, assignedLid } of pnToLidMappings) { for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
-12
View File
@@ -1,12 +0,0 @@
import { BufferJSON } from './generics'
type ProtoMessageClass<T> = {
new (...args: any[]): T
decode(buffer: Uint8Array | Buffer): T
}
export function decodeAndHydrate<T>(MessageType: ProtoMessageClass<T>, buffer: Uint8Array | Buffer): T {
const decoded = MessageType.decode(buffer)
const hydrated = JSON.parse(JSON.stringify(decoded, BufferJSON.replacer), BufferJSON.reviver)
return hydrated as T
}
+1 -1
View File
@@ -106,7 +106,7 @@ export const useMultiFileAuthState = async (
ids.map(async id => { ids.map(async id => {
let value = await readData(`${type}-${id}.json`) let value = await readData(`${type}-${id}.json`)
if (type === 'app-state-sync-key' && value) { if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.create(value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
} }
data[id] = value data[id] = value
+13 -17
View File
@@ -11,7 +11,6 @@ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types'
import { type BinaryNode, getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary' import { type BinaryNode, getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary'
import { Curve, hmacSign } from './crypto' import { Curve, hmacSign } from './crypto'
import { encodeBigEndian } from './generics' import { encodeBigEndian } from './generics'
import { decodeAndHydrate } from './proto-utils'
import { createSignalIdentity } from './signal' import { createSignalIdentity } from './signal'
const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => { const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
@@ -68,7 +67,7 @@ export const generateLoginNode = (userJid: string, config: SocketConfig): proto.
username: +user, username: +user,
device: device device: device
} }
return proto.ClientPayload.create(payload) return proto.ClientPayload.fromObject(payload)
} }
const getPlatformType = (platform: string): proto.DeviceProps.PlatformType => { const getPlatformType = (platform: string): proto.DeviceProps.PlatformType => {
@@ -113,7 +112,7 @@ export const generateRegistrationNode = (
} }
} }
return proto.ClientPayload.create(registerPayload) return proto.ClientPayload.fromObject(registerPayload)
} }
export const configureSuccessfulPairing = ( export const configureSuccessfulPairing = (
@@ -141,44 +140,41 @@ export const configureSuccessfulPairing = (
const jid = deviceNode.attrs.jid const jid = deviceNode.attrs.jid
const lid = deviceNode.attrs.lid const lid = deviceNode.attrs.lid
const { details, hmac, accountType } = decodeAndHydrate( const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
proto.ADVSignedDeviceIdentityHMAC,
deviceIdentityNode.content as Buffer
)
let hmacPrefix = Buffer.from([]) let hmacPrefix = Buffer.from([])
if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) { if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
} }
const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64')) const advSign = hmacSign(Buffer.concat([hmacPrefix, details!]), Buffer.from(advSecretKey, 'base64'))
if (Buffer.compare(hmac, advSign) !== 0) { if (Buffer.compare(hmac!, advSign) !== 0) {
throw new Boom('Invalid account signature') throw new Boom('Invalid account signature')
} }
const account = decodeAndHydrate(proto.ADVSignedDeviceIdentity, details) const account = proto.ADVSignedDeviceIdentity.decode(details!)
const { accountSignatureKey, accountSignature, details: deviceDetails } = account const { accountSignatureKey, accountSignature, details: deviceDetails } = account
const deviceIdentity = decodeAndHydrate(proto.ADVDeviceIdentity, deviceDetails) const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails!)
const accountSignaturePrefix = const accountSignaturePrefix =
deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
: WA_ADV_ACCOUNT_SIG_PREFIX : WA_ADV_ACCOUNT_SIG_PREFIX
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]) const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails!, signedIdentityKey.public])
if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) { if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
throw new Boom('Failed to verify account signature') throw new Boom('Failed to verify account signature')
} }
const deviceMsg = Buffer.concat([ const deviceMsg = Buffer.concat([
WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX,
deviceDetails, deviceDetails!,
signedIdentityKey.public, signedIdentityKey.public,
accountSignatureKey accountSignatureKey!
]) ])
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg) account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
const identity = createSignalIdentity(lid!, accountSignatureKey) const identity = createSignalIdentity(lid!, accountSignatureKey!)
const accountEnc = encodeSignedDeviceIdentity(account, false) const accountEnc = encodeSignedDeviceIdentity(account, false)
const reply: BinaryNode = { const reply: BinaryNode = {
@@ -195,7 +191,7 @@ export const configureSuccessfulPairing = (
content: [ content: [
{ {
tag: 'device-identity', tag: 'device-identity',
attrs: { 'key-index': deviceIdentity.keyIndex.toString() }, attrs: { 'key-index': deviceIdentity.keyIndex!.toString() },
content: accountEnc content: accountEnc
} }
] ]
+1 -2
View File
@@ -1,6 +1,5 @@
import { Boom } from '@hapi/boom' import { Boom } from '@hapi/boom'
import { proto } from '../../WAProto/index.js' import { proto } from '../../WAProto/index.js'
import { decodeAndHydrate } from '../Utils/proto-utils'
import { type BinaryNode } from './types' import { type BinaryNode } from './types'
// some extra useful utilities // some extra useful utilities
@@ -79,7 +78,7 @@ export const getBinaryNodeMessages = ({ content }: BinaryNode) => {
if (Array.isArray(content)) { if (Array.isArray(content)) {
for (const item of content) { for (const item of content) {
if (item.tag === 'message') { if (item.tag === 'message') {
msgs.push(decodeAndHydrate(proto.WebMessageInfo, item.content as Buffer)) msgs.push(proto.WebMessageInfo.decode(item.content as Buffer).toJSON() as proto.WebMessageInfo)
} }
} }
} }
@@ -1,5 +1,5 @@
import { jest } from '@jest/globals' import { jest } from '@jest/globals'
import { proto } from '../..' import { proto, type WAMessage } from '../..'
import { DEFAULT_CONNECTION_CONFIG } from '../../Defaults' import { DEFAULT_CONNECTION_CONFIG } from '../../Defaults'
import makeWASocket from '../../Socket' import makeWASocket from '../../Socket'
import { makeSession, mockWebSocket } from '../TestUtils/session' import { makeSession, mockWebSocket } from '../TestUtils/session'
@@ -26,11 +26,11 @@ describe('Connection Deadlock Test', () => {
// 2. Now, emit a regular message. Because the previous step should have // 2. Now, emit a regular message. Because the previous step should have
// flushed the buffer, this message should be processed immediately. // flushed the buffer, this message should be processed immediately.
const regularMessage = proto.WebMessageInfo.create({ const regularMessage = proto.WebMessageInfo.fromObject({
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'REGULAR_MSG_1' }, key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'REGULAR_MSG_1' },
messageTimestamp: Date.now() / 1000, messageTimestamp: Date.now() / 1000,
message: { conversation: 'Hello, world!' } message: { conversation: 'Hello, world!' }
}) }) as WAMessage
sock.ev.emit('messages.upsert', { messages: [regularMessage], type: 'notify' }) sock.ev.emit('messages.upsert', { messages: [regularMessage], type: 'notify' })
// Wait for the event loop to process any final events. // Wait for the event loop to process any final events.
await new Promise(resolve => setTimeout(resolve, 50)) await new Promise(resolve => setTimeout(resolve, 50))