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
+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
}
]