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-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 --no-comments -o ./index.js ./WAProto.proto;
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
+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 { decodeAndHydrate } from '../../Utils/proto-utils'
import { CiphertextMessage } from './ciphertext-message'
interface SenderKeyDistributionMessageStructure {
id: number
iteration: number
chainKey: Uint8Array
signingKey: Uint8Array
}
export class SenderKeyDistributionMessage extends CiphertextMessage {
private readonly id: number
private readonly iteration: number
@@ -21,7 +27,9 @@ export class SenderKeyDistributionMessage extends CiphertextMessage {
if (serialized) {
try {
const message = serialized.slice(1)
const distributionMessage = decodeAndHydrate(proto.SenderKeyDistributionMessage, message)
const distributionMessage = proto.SenderKeyDistributionMessage.decode(
message
).toJSON() as SenderKeyDistributionMessageStructure
this.serialized = serialized
this.id = distributionMessage.id
+7 -2
View File
@@ -1,8 +1,13 @@
import { calculateSignature, verifySignature } from 'libsignal/src/curve'
import { proto } from '../../../WAProto/index.js'
import { decodeAndHydrate } from '../../Utils/proto-utils'
import { CiphertextMessage } from './ciphertext-message'
interface SenderKeyMessageStructure {
id: number
iteration: number
ciphertext: Buffer
}
export class SenderKeyMessage extends CiphertextMessage {
private readonly SIGNATURE_LENGTH = 64
private readonly messageVersion: number
@@ -25,7 +30,7 @@ export class SenderKeyMessage extends CiphertextMessage {
const version = serialized[0]!
const message = serialized.slice(1, serialized.length - 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.messageVersion = (version & 0xff) >> 4
+1 -1
View File
@@ -368,7 +368,7 @@ export const makeCommunitiesSocket = (config: SocketConfig) => {
// update the invite message to be expired
if (key.id) {
// create new invite message that is expired
inviteMessage = proto.Message.GroupInviteMessage.create(inviteMessage)
inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
inviteMessage.inviteExpiration = 0
inviteMessage.inviteCode = ''
ev.emit('messages.update', [
+1 -1
View File
@@ -239,7 +239,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
// update the invite message to be expired
if (key.id) {
// create new invite message that is expired
inviteMessage = proto.Message.GroupInviteMessage.create(inviteMessage)
inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage)
inviteMessage.inviteExpiration = 0
inviteMessage.inviteCode = ''
ev.emit('messages.update', [
+10 -10
View File
@@ -11,6 +11,7 @@ import type {
SocketConfig,
WACallEvent,
WACallUpdateType,
WAMessage,
WAMessageKey,
WAPatchName
} from '../Types'
@@ -39,7 +40,6 @@ import {
xmppSignedPreKey
} from '../Utils'
import { makeMutex } from '../Utils/make-mutex'
import { decodeAndHydrate } from '../Utils/proto-utils'
import {
areJidsSameUser,
type BinaryNode,
@@ -294,8 +294,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
typeof plaintextNode.content === 'string'
? Buffer.from(plaintextNode.content, 'binary')
: Buffer.from(plaintextNode.content as Uint8Array)
const messageProto = decodeAndHydrate(proto.Message, contentBuf)
const fullMessage = proto.WebMessageInfo.create({
const messageProto = proto.Message.decode(contentBuf).toJSON()
const fullMessage = proto.WebMessageInfo.fromObject({
key: {
remoteJid: from,
id: child.attrs.message_id || child.attrs.server_id,
@@ -303,7 +303,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
},
message: messageProto,
messageTimestamp: +child.attrs.t!
})
}).toJSON() as WAMessage
await upsertMessage(fullMessage, 'append')
logger.info('Processed plaintext newsletter message')
} 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
// TODO: Add participant LID
switch (child?.tag) {
@@ -658,7 +658,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}
const processNotification = async (node: BinaryNode) => {
const result: Partial<proto.IWebMessageInfo> = {}
const result: Partial<WAMessage> = {}
const [child] = getAllBinaryNodeChildren(node)
const nodeType = node.attrs.type
const from = jidNormalizedUser(node.attrs.from)
@@ -874,7 +874,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
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 participant = key.participant || remoteJid
@@ -1089,7 +1089,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
msg.participant ??= node.attrs.participant
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')
}
})
@@ -1445,7 +1445,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
// missed call + group call notification message generation
if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
const msg: proto.IWebMessageInfo = {
const msg: WAMessage = {
key: {
remoteJid: call.chatId,
id: call.id,
@@ -1465,7 +1465,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
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')
}
})
+5 -4
View File
@@ -9,6 +9,7 @@ import type {
MessageRelayOptions,
MiscMessageGenerationOptions,
SocketConfig,
WAMessage,
WAMessageKey
} from '../Types'
import {
@@ -1018,7 +1019,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
createParticipantNodes,
getUSyncDevices,
messageRetryManager,
updateMediaMessage: async (message: proto.IWebMessageInfo) => {
updateMediaMessage: async (message: WAMessage) => {
const content = assertMediaContent(message.message)
const mediaKey = content.mediaKey!
const meId = authState.creds.me!.id
@@ -1036,15 +1037,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
try {
const media = await decryptMediaRetryData(result.media!, mediaKey, result.key.id!)
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})`, {
data: media,
statusCode: getStatusCodeForMediaRetry(media.result) || 404
statusCode: getStatusCodeForMediaRetry(media.result!) || 404
})
}
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')
} catch (err: any) {
+2 -3
View File
@@ -33,7 +33,6 @@ import {
promiseTimeout
} from '../Utils'
import { getPlatformId } from '../Utils/browser-utils'
import { decodeAndHydrate } from '../Utils/proto-utils'
import {
assertNodeErrorFree,
type BinaryNode,
@@ -366,14 +365,14 @@ export const makeSocket = (config: SocketConfig) => {
let helloMsg: proto.IHandshakeMessage = {
clientHello: { ephemeral: ephemeralKeyPair.public }
}
helloMsg = proto.HandshakeMessage.create(helloMsg)
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
logger.info({ browser, helloMsg }, 'connected to WA')
const init = proto.HandshakeMessage.encode(helloMsg).finish()
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')
+1 -1
View File
@@ -23,7 +23,7 @@ export type BaileysEventMap = {
messages: WAMessage[]
isLatest?: boolean
progress?: number | null
syncType?: proto.HistorySync.HistorySyncType
syncType?: proto.HistorySync.HistorySyncType | null
peerDataRequestSessionId?: string | null
}
/** upsert chats */
+3 -3
View File
@@ -357,11 +357,11 @@ export type MessageUpsertType = 'append' | 'notify'
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 MessageUserReceiptUpdate = { key: proto.IMessageKey; receipt: MessageUserReceipt }
export type MessageUserReceiptUpdate = { key: WAMessageKey; receipt: MessageUserReceipt }
export type MediaDecryptionKeyInfo = {
iv: Buffer
@@ -369,4 +369,4 @@ export type MediaDecryptionKeyInfo = {
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 { AuthenticationState, LIDMapping, SignalAuthState, TransactionCapabilityOptions } from './Auth'
import type { GroupMetadata } from './GroupMetadata'
import { type MediaConnInfo } from './Message'
import { type MediaConnInfo, type WAMessageKey } from './Message'
import type { SignalRepositoryWithLIDStore } from './Signal'
export type WAVersion = [number, number, number]
@@ -137,7 +137,7 @@ export type SocketConfig = {
* implement this so that messages failed to send
* (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 */
cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>
+8 -9
View File
@@ -24,7 +24,6 @@ import { toNumber } from './generics'
import type { ILogger } from './logger'
import { LT_HASH_ANTI_TAMPERING } from './lt-hash'
import { downloadContentFromMessage } from './messages-media'
import { decodeAndHydrate } from './proto-utils'
type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>
@@ -154,7 +153,7 @@ export const encodeSyncdPatch = async (
state = { ...state, indexValueMap: { ...state.indexValueMap } }
const indexBuffer = Buffer.from(JSON.stringify(index))
const dataProto = proto.SyncActionData.create({
const dataProto = proto.SyncActionData.fromObject({
index: indexBuffer,
value: syncAction,
padding: new Uint8Array(0),
@@ -233,16 +232,16 @@ export const decodeSyncdMutations = async (
}
const result = aesDecrypt(encContent, key.valueEncryptionKey)
const syncAction = decodeAndHydrate(proto.SyncActionData, result)
const syncAction = proto.SyncActionData.decode(result)
if (validateMacs) {
const hmac = hmacSign(syncAction.index, key.indexKey)
const hmac = hmacSign(syncAction.index!, key.indexKey)
if (Buffer.compare(hmac, record.index!.blob!) !== 0) {
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) })
ltGenerator.mix({
@@ -327,9 +326,9 @@ export const extractSyncdPatches = async (result: BinaryNode, options: RequestIn
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)
snapshot = decodeAndHydrate(proto.SyncdSnapshot, data)
snapshot = proto.SyncdSnapshot.decode(data)
}
for (let { content } of patches) {
@@ -338,7 +337,7 @@ export const extractSyncdPatches = async (result: BinaryNode, options: RequestIn
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) {
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) => {
const buffer = await downloadExternalBlob(blob, options)
const syncData = decodeAndHydrate(proto.SyncdMutations, buffer)
const syncData = proto.SyncdMutations.decode(buffer)
return syncData
}
+3 -5
View File
@@ -18,7 +18,6 @@ import {
} from '../WABinary'
import { unpadRandomMax16 } from './generics'
import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
const getDecryptionJid = async (sender: string, repository: SignalRepositoryWithLIDStore): Promise<string> => {
if (sender.includes('@lid')) {
@@ -239,8 +238,8 @@ export const decryptMessageNode = (
if (Array.isArray(stanza.content)) {
for (const { tag, attrs, content } of stanza.content) {
if (tag === 'verified_name' && content instanceof Uint8Array) {
const cert = decodeAndHydrate(proto.VerifiedNameCertificate, content)
const details = proto.VerifiedNameCertificate.Details.decode(cert.details)
const cert = proto.VerifiedNameCertificate.decode(content)
const details = proto.VerifiedNameCertificate.Details.decode(cert.details!)
fullMessage.verifiedBizName = details.verifiedName
}
@@ -294,8 +293,7 @@ export const decryptMessageNode = (
throw new Error(`Unknown e2e type: ${e2eType}`)
}
let msg: proto.IMessage = decodeAndHydrate(
proto.Message,
let msg: proto.IMessage = proto.Message.decode(
e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer
)
msg = msg.deviceSentMessage?.message || msg
+17 -15
View File
@@ -1,5 +1,4 @@
import EventEmitter from 'events'
import { proto } from '../../WAProto/index.js'
import type {
BaileysEvent,
BaileysEventEmitter,
@@ -8,7 +7,8 @@ import type {
Chat,
ChatUpdate,
Contact,
WAMessage
WAMessage,
WAMessageKey
} from '../Types'
import { WAMessageStatus } from '../Types'
import { trimUndefined } from './generics'
@@ -241,14 +241,15 @@ function append<E extends BufferableEvent>(
switch (event) {
case 'messaging-history.set':
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) {
existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
}
if (!existingChat && !historyCache.has(chat.id)) {
data.historySets.chats[chat.id] = chat
historyCache.add(chat.id)
if (!existingChat && !historyCache.has(id)) {
data.historySets.chats[id] = chat
historyCache.add(id)
absorbingChatUpdate(chat)
}
@@ -286,11 +287,12 @@ function append<E extends BufferableEvent>(
break
case 'chats.upsert':
for (const chat of eventData as Chat[]) {
let upsert = data.chatUpserts[chat.id]
if (!upsert) {
upsert = data.historySets.chats[chat.id]
const id = chat.id || ''
let upsert = data.chatUpserts[id]
if (id && !upsert) {
upsert = data.historySets.chats[id]
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)
} else {
upsert = chat
data.chatUpserts[chat.id] = upsert
data.chatUpserts[id] = upsert
}
absorbingChatUpdate(upsert)
if (data.chatDeletes.has(chat.id)) {
data.chatDeletes.delete(chat.id)
if (data.chatDeletes.has(id)) {
data.chatDeletes.delete(id)
}
}
@@ -521,7 +523,7 @@ function append<E extends BufferableEvent>(
}
function absorbingChatUpdate(existing: Chat) {
const chatId = existing.id
const chatId = existing.id || ''
const update = data.chatUpdates[chatId]
if (update) {
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)
}
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 { proto } from '../../WAProto/index.js'
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 { type BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary'
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) || ''
export const writeRandomPadMax16 = (msg: Uint8Array) => {
+6 -7
View File
@@ -1,12 +1,11 @@
import { promisify } from 'util'
import { inflate } from 'zlib'
import { proto } from '../../WAProto/index.js'
import type { Chat, Contact } from '../Types'
import type { Chat, Contact, WAMessage } from '../Types'
import { WAMessageStubType } from '../Types'
import { toNumber } from './generics'
import { normalizeMessageContent } from './messages'
import { downloadContentFromMessage } from './messages-media'
import { decodeAndHydrate } from './proto-utils'
const inflatePromise = promisify(inflate)
@@ -22,12 +21,12 @@ export const downloadHistory = async (msg: proto.Message.IHistorySyncNotificatio
// decompress buffer
buffer = await inflatePromise(buffer)
const syncData = decodeAndHydrate(proto.HistorySync, buffer)
const syncData = proto.HistorySync.decode(buffer)
return syncData
}
export const processHistoryMessage = (item: proto.IHistorySync) => {
const messages: proto.IWebMessageInfo[] = []
const messages: WAMessage[] = []
const contacts: Contact[] = []
const chats: Chat[] = []
@@ -38,7 +37,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
case proto.HistorySync.HistorySyncType.ON_DEMAND:
for (const chat of item.conversations! as Chat[]) {
contacts.push({
id: chat.id,
id: chat.id!,
name: chat.name || undefined,
lid: chat.lidJid || undefined,
phoneNumber: chat.pnJid || undefined
@@ -48,7 +47,7 @@ export const processHistoryMessage = (item: proto.IHistorySync) => {
delete chat.messages
for (const item of msgs) {
const message = item.message!
const message = item.message! as WAMessage
messages.push(message)
if (!chat.messages?.length) {
@@ -103,7 +102,7 @@ export const downloadAndProcessHistorySyncNotification = async (
export const getHistoryMsg = (message: proto.IMessage) => {
const normalizedContent = !!message ? normalizeMessageContent(message) : undefined
const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification
const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification!
return anyHistoryMsg
}
-1
View File
@@ -17,4 +17,3 @@ export * from './event-buffer'
export * from './process-message'
export * from './message-retry-manager'
export * from './browser-utils'
export * from './proto-utils'
+4 -4
View File
@@ -20,13 +20,13 @@ import type {
WAGenericMediaMessage,
WAMediaUpload,
WAMediaUploadFunction,
WAMessageContent
WAMessageContent,
WAMessageKey
} from '../Types'
import { type BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
import { generateMessageIDV2 } from './generics'
import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
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
*/
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 recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
@@ -806,7 +806,7 @@ export const decryptMediaRetryData = async (
) => {
const retryKey = await getMediaRetryKey(mediaKey)
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId))
return decodeAndHydrate(proto.MediaRetryNotification, plaintext)
return proto.MediaRetryNotification.decode(plaintext)
}
export const getStatusCodeForMediaRetry = (code: number) =>
+10 -10
View File
@@ -23,6 +23,7 @@ import type {
WAMediaUpload,
WAMessage,
WAMessageContent,
WAMessageKey,
WATextMessage
} from '../Types'
import { WAMessageStatus, WAProto } from '../Types'
@@ -39,7 +40,6 @@ import {
getRawMediaUploadData,
type MediaDownloadOptions
} from './messages-media'
import { decodeAndHydrate } from './proto-utils'
type MediaUploadData = {
media: WAMediaUpload
@@ -156,7 +156,7 @@ export const prepareWAMessageMedia = async (
if (mediaBuff) {
logger?.debug({ cacheableKey }, 'got media cache hit')
const obj = decodeAndHydrate(proto.Message, mediaBuff)
const obj = proto.Message.decode(mediaBuff)
const key = `${mediaType}Message`
Object.assign(obj[key as keyof proto.Message]!, { ...uploadData, media: undefined })
@@ -183,9 +183,9 @@ export const prepareWAMessageMedia = async (
await fs.unlink(filePath)
const obj = WAProto.Message.create({
const obj = WAProto.Message.fromObject({
// todo: add more support here
[`${mediaType}Message`]: (MessageTypeProto as any)[mediaType].create({
[`${mediaType}Message`]: (MessageTypeProto as any)[mediaType].fromObject({
url: mediaUrl,
directPath,
fileSha256,
@@ -288,8 +288,8 @@ export const prepareWAMessageMedia = async (
}
})
const obj = WAProto.Message.create({
[`${mediaType}Message`]: MessageTypeProto[mediaType as keyof typeof MessageTypeProto].create({
const obj = WAProto.Message.fromObject({
[`${mediaType}Message`]: MessageTypeProto[mediaType as keyof typeof MessageTypeProto].fromObject({
url: mediaUrl,
directPath,
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
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
@@ -691,7 +691,7 @@ export const generateWAMessageFromContent = (
participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
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) => {
@@ -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 */
export const aggregateMessageKeysNotFromMe = (keys: proto.IMessageKey[]) => {
export const aggregateMessageKeysNotFromMe = (keys: WAMessageKey[]) => {
const keyMap: { [id: string]: { jid: string; participant: string | undefined; messageIds: string[] } } = {}
for (const { remoteJid, id, participant, fromMe } of keys) {
if (!fromMe) {
+1 -2
View File
@@ -6,7 +6,6 @@ import type { BinaryNode } from '../WABinary'
import { decodeBinaryNode } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto'
import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
const generateIV = (counter: number) => {
const iv = new ArrayBuffer(12)
@@ -113,7 +112,7 @@ export const makeNoiseHandler = ({
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!)
+15 -16
View File
@@ -9,7 +9,9 @@ import type {
RequestJoinAction,
RequestJoinMethod,
SignalKeyStoreWithTransaction,
SignalRepositoryWithLIDStore
SignalRepositoryWithLIDStore,
WAMessage,
WAMessageKey
} from '../Types'
import { WAMessageStubType } from '../Types'
import { getContentType, normalizeMessageContent } from '../Utils/messages'
@@ -27,7 +29,6 @@ import { aesDecryptGCM, hmacSign } from './crypto'
import { toNumber } from './generics'
import { downloadAndProcessHistorySyncNotification } from './history'
import type { ILogger } from './logger'
import { decodeAndHydrate } from './proto-utils'
type ProcessMessageContext = {
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])
/** 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
if (isJidHostedPnUser(message.key.remoteJid!) || isJidHostedLidUser(message.key.remoteJid!)) {
message.key.remoteJid = jidEncode(
jidDecode(message.key.remoteJid!)?.user!,
jidDecode(message.key?.remoteJid!)?.user!,
isJidHostedPnUser(message.key.remoteJid!) ? 's.whatsapp.net' : 'lid'
)
} else {
@@ -80,7 +81,7 @@ export const cleanMessage = (message: proto.IWebMessageInfo, meId: string) => {
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey!)
}
function normaliseKey(msgKey: proto.IMessageKey) {
function normaliseKey(msgKey: WAMessageKey) {
// if the reaction is from another user
// we've to correctly map the key to this user's perspective
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 hasSomeContent = !!getContentType(normalizedContent)
return (
@@ -115,14 +116,13 @@ export const isRealMessage = (message: proto.IWebMessageInfo, meId: string) => {
)
}
export const shouldIncrementChatUnread = (message: proto.IWebMessageInfo) =>
!message.key.fromMe && !message.messageStubType
export const shouldIncrementChatUnread = (message: WAMessage) => !message.key.fromMe && !message.messageStubType
/**
* Get the ID of the chat from the given key.
* 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) {
return participant!
}
@@ -172,7 +172,7 @@ export function decryptPollVote(
}
const processMessage = async (
message: proto.IWebMessageInfo,
message: WAMessage,
{
shouldProcessHistoryMsg,
placeholderResendCache,
@@ -297,11 +297,12 @@ const processMessage = async (
const { placeholderMessageResendResponse: retryResponse } = result
//eslint-disable-next-line max-depth
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
// TODO: parse through proper message handling utilities (to add relevant key fields)
setTimeout(() => {
ev.emit('messages.upsert', {
messages: [webMessageInfo],
messages: [webMessageInfo as WAMessage],
type: 'notify',
requestId: response.stanzaId!
})
@@ -331,10 +332,8 @@ const processMessage = async (
break
case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload!
const { pnToLidMappings, chatDbMigrationTimestamp } = decodeAndHydrate(
proto.LIDMigrationMappingSyncPayload,
encodedPayload
)
const { pnToLidMappings, chatDbMigrationTimestamp } =
proto.LIDMigrationMappingSyncPayload.decode(encodedPayload)
logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp')
const pairs = []
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 => {
let value = await readData(`${type}-${id}.json`)
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.create(value)
value = proto.Message.AppStateSyncKeyData.fromObject(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 { Curve, hmacSign } from './crypto'
import { encodeBigEndian } from './generics'
import { decodeAndHydrate } from './proto-utils'
import { createSignalIdentity } from './signal'
const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
@@ -68,7 +67,7 @@ export const generateLoginNode = (userJid: string, config: SocketConfig): proto.
username: +user,
device: device
}
return proto.ClientPayload.create(payload)
return proto.ClientPayload.fromObject(payload)
}
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 = (
@@ -141,44 +140,41 @@ export const configureSuccessfulPairing = (
const jid = deviceNode.attrs.jid
const lid = deviceNode.attrs.lid
const { details, hmac, accountType } = decodeAndHydrate(
proto.ADVSignedDeviceIdentityHMAC,
deviceIdentityNode.content as Buffer
)
const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
let hmacPrefix = Buffer.from([])
if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
}
const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'))
if (Buffer.compare(hmac, advSign) !== 0) {
const advSign = hmacSign(Buffer.concat([hmacPrefix, details!]), Buffer.from(advSecretKey, 'base64'))
if (Buffer.compare(hmac!, advSign) !== 0) {
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 deviceIdentity = decodeAndHydrate(proto.ADVDeviceIdentity, deviceDetails)
const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails!)
const accountSignaturePrefix =
deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
: WA_ADV_ACCOUNT_SIG_PREFIX
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public])
if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails!, signedIdentityKey.public])
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
throw new Boom('Failed to verify account signature')
}
const deviceMsg = Buffer.concat([
WA_ADV_DEVICE_SIG_PREFIX,
deviceDetails,
deviceDetails!,
signedIdentityKey.public,
accountSignatureKey
accountSignatureKey!
])
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
const identity = createSignalIdentity(lid!, accountSignatureKey)
const identity = createSignalIdentity(lid!, accountSignatureKey!)
const accountEnc = encodeSignedDeviceIdentity(account, false)
const reply: BinaryNode = {
@@ -195,7 +191,7 @@ export const configureSuccessfulPairing = (
content: [
{
tag: 'device-identity',
attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
attrs: { 'key-index': deviceIdentity.keyIndex!.toString() },
content: accountEnc
}
]
+1 -2
View File
@@ -1,6 +1,5 @@
import { Boom } from '@hapi/boom'
import { proto } from '../../WAProto/index.js'
import { decodeAndHydrate } from '../Utils/proto-utils'
import { type BinaryNode } from './types'
// some extra useful utilities
@@ -79,7 +78,7 @@ export const getBinaryNodeMessages = ({ content }: BinaryNode) => {
if (Array.isArray(content)) {
for (const item of content) {
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 { proto } from '../..'
import { proto, type WAMessage } from '../..'
import { DEFAULT_CONNECTION_CONFIG } from '../../Defaults'
import makeWASocket from '../../Socket'
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
// 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' },
messageTimestamp: Date.now() / 1000,
message: { conversation: 'Hello, world!' }
})
}) as WAMessage
sock.ev.emit('messages.upsert', { messages: [regularMessage], type: 'notify' })
// Wait for the event loop to process any final events.
await new Promise(resolve => setTimeout(resolve, 50))