fix: revert remaining ?? '' patterns across Utils, WABinary, Signal, and WAUSync files

Completes the comprehensive revert of defensive null coalescing patterns
introduced in PRs 124-129. These patterns (e.g. `value ?? ''`) silently
produced empty strings instead of failing fast, causing subtle bugs like
malformed JIDs and broken Signal session lookups.

Files: libsignal.ts, messages-recv.ts, chat-utils.ts, generics.ts,
history.ts, messages-media.ts, messages.ts, process-message.ts,
validate-connection.ts, jid-utils.ts, UsyncBotProfileProtocol.ts

https://claude.ai/code/session_01XaA7GwNaB6azTHFYQ8WEpB
This commit is contained in:
Claude
2026-02-09 13:56:33 +00:00
parent 48b63565b6
commit 2a9d9a0a52
11 changed files with 61 additions and 64 deletions
+1 -1
View File
@@ -708,7 +708,7 @@ function signalStorage(
if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID) return id if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID) return id
const pnJid = `${user ?? ''}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}` const pnJid = `${user!}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`
const lidForPN = await lidMapping.getLIDForPN(pnJid) const lidForPN = await lidMapping.getLIDForPN(pnJid)
if (lidForPN) { if (lidForPN) {
+9 -9
View File
@@ -324,7 +324,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
fromMe: false // TODO: is this really true though fromMe: false // TODO: is this really true though
}, },
message: messageProto, message: messageProto,
messageTimestamp: +(child.attrs.t ?? 0) messageTimestamp: +child.attrs.t!
}).toJSON() as WAMessage }).toJSON() as WAMessage
await upsertMessage(fullMessage, 'append') await upsertMessage(fullMessage, 'append')
logger.info('Processed plaintext newsletter message') logger.info('Processed plaintext newsletter message')
@@ -601,8 +601,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
const actingParticipantLid = fullNode.attrs.participant const actingParticipantLid = fullNode.attrs.participant
const actingParticipantPn = fullNode.attrs.participant_pn const actingParticipantPn = fullNode.attrs.participant_pn
const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid || '' const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid!
const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn || '' const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn!
switch (child?.tag) { switch (child?.tag) {
case 'create': case 'create':
@@ -663,8 +663,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
participants.length === 1 && participants.length === 1 &&
// if recv. "remove" message and sender removed themselves // if recv. "remove" message and sender removed themselves
// mark as left // mark as left
(areJidsSameUser(participants[0]?.id, actingParticipantLid) || (areJidsSameUser(participants[0]!.id, actingParticipantLid) ||
areJidsSameUser(participants[0]?.id, actingParticipantPn)) && areJidsSameUser(participants[0]!.id, actingParticipantPn)) &&
child.tag === 'remove' child.tag === 'remove'
) { ) {
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE
@@ -805,9 +805,9 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
break break
case 'account_sync': case 'account_sync':
if (child?.tag === 'disappearing_mode') { if (child!.tag === 'disappearing_mode') {
const newDuration = +(child.attrs.duration ?? '0') const newDuration = +child!.attrs.duration!
const timestamp = +(child.attrs.t ?? '0') const timestamp = +child!.attrs.t!
logger.info({ newDuration }, 'updated account disappearing mode') logger.info({ newDuration }, 'updated account disappearing mode')
@@ -820,7 +820,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
} }
} }
}) })
} else if (child?.tag === 'blocklist') { } else if (child!.tag === 'blocklist') {
const blocklists = getBinaryNodeChildren(child, 'item') const blocklists = getBinaryNodeChildren(child, 'item')
for (const { attrs } of blocklists) { for (const { attrs } of blocklists) {
+8 -8
View File
@@ -470,7 +470,7 @@ export const decodeSyncdSnapshot = async (
areMutationsRequired areMutationsRequired
? mutation => { ? mutation => {
const index = mutation.syncAction.index?.toString() const index = mutation.syncAction.index?.toString()
mutationMap[index ?? ''] = mutation mutationMap[index!] = mutation
} }
: () => {}, : () => {},
validateMacs validateMacs
@@ -558,7 +558,7 @@ export const decodePatches = async (
shouldMutate shouldMutate
? mutation => { ? mutation => {
const index = mutation.syncAction.index?.toString() const index = mutation.syncAction.index?.toString()
mutationMap[index ?? ''] = mutation mutationMap[index!] = mutation
} }
: () => {}, : () => {},
true true
@@ -689,7 +689,7 @@ export const chatModificationToAppPatch = (mod: ChatModification, jid: string) =
messageTimestamp: timestamp messageTimestamp: timestamp
} }
}, },
index: ['deleteMessageForMe', jid, key.id ?? '', key.fromMe ? '1' : '0', '0'], index: ['deleteMessageForMe', jid, key.id!, key.fromMe ? '1' : '0', '0'],
type: 'regular_high', type: 'regular_high',
apiVersion: 3, apiVersion: 3,
operation: OP.SET operation: OP.SET
@@ -896,7 +896,7 @@ export const processSyncAction = (
{ {
id, id,
muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null, muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
conditional: getChatUpdateConditional(id ?? '', undefined) conditional: getChatUpdateConditional(id!, undefined)
} }
]) ])
} else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') { } else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
@@ -925,7 +925,7 @@ export const processSyncAction = (
{ {
id, id,
archived: isArchived, archived: isArchived,
conditional: getChatUpdateConditional(id ?? '', msgRange) conditional: getChatUpdateConditional(id!, msgRange)
} }
]) ])
} else if (action?.markChatAsReadAction) { } else if (action?.markChatAsReadAction) {
@@ -939,7 +939,7 @@ export const processSyncAction = (
{ {
id, id,
unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1, unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
conditional: getChatUpdateConditional(id ?? '', markReadAction?.messageRange) conditional: getChatUpdateConditional(id!, markReadAction?.messageRange)
} }
]) ])
} else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') { } else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
@@ -965,7 +965,7 @@ export const processSyncAction = (
{ {
id, id,
pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null, pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
conditional: getChatUpdateConditional(id ?? '', undefined) conditional: getChatUpdateConditional(id!, undefined)
} }
]) ])
} else if (action?.unarchiveChatsSetting) { } else if (action?.unarchiveChatsSetting) {
@@ -990,7 +990,7 @@ export const processSyncAction = (
]) ])
} else if (action?.deleteChatAction || type === 'deleteChat') { } else if (action?.deleteChatAction || type === 'deleteChat') {
if (!isInitialSync) { if (!isInitialSync) {
ev.emit('chats.delete', [id ?? '']) ev.emit('chats.delete', [id!])
} }
} else if (action?.labelEditAction) { } else if (action?.labelEditAction) {
const { name, color, deleted, predefinedId } = action.labelEditAction const { name, color, deleted, predefinedId } = action.labelEditAction
+1 -1
View File
@@ -343,7 +343,7 @@ const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
* @param type type from receipt * @param type type from receipt
*/ */
export const getStatusFromReceiptType = (type: string | undefined) => { export const getStatusFromReceiptType = (type: string | undefined) => {
const status = STATUS_MAP[type ?? ''] const status = STATUS_MAP[type!]
if (typeof type === 'undefined') { if (typeof type === 'undefined') {
return proto.WebMessageInfo.Status.DELIVERY_ACK return proto.WebMessageInfo.Status.DELIVERY_ACK
} }
+2 -2
View File
@@ -294,7 +294,7 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
case proto.HistorySync.HistorySyncType.FULL: case proto.HistorySync.HistorySyncType.FULL:
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[]) {
const chatId = chat.id ?? '' const chatId = chat.id!
// Source 2: Extract LID-PN mapping from conversation object // Source 2: Extract LID-PN mapping from conversation object
// This handles cases where the mapping isn't in phoneNumberToLidMappings // This handles cases where the mapping isn't in phoneNumberToLidMappings
@@ -371,7 +371,7 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
break break
case proto.HistorySync.HistorySyncType.PUSH_NAME: case proto.HistorySync.HistorySyncType.PUSH_NAME:
for (const c of (item.pushnames ?? [])) { for (const c of (item.pushnames ?? [])) {
contacts.push({ id: c.id ?? '', notify: c.pushname ?? '' }) contacts.push({ id: c.id!, notify: c.pushname! })
} }
break break
+5 -5
View File
@@ -317,7 +317,7 @@ export const getStream = async (item: WAMediaUpload, opts?: RequestInit & { maxC
const urlStr = item.url.toString() const urlStr = item.url.toString()
if (urlStr.startsWith('data:')) { if (urlStr.startsWith('data:')) {
const buffer = Buffer.from(urlStr.split(',')[1] ?? '', 'base64') const buffer = Buffer.from(urlStr.split(',')[1]!, 'base64')
return { stream: toReadable(buffer), type: 'buffer' } as const return { stream: toReadable(buffer), type: 'buffer' } as const
} }
@@ -532,7 +532,7 @@ export const downloadContentFromMessage = async (
opts: MediaDownloadOptions = {} opts: MediaDownloadOptions = {}
) => { ) => {
const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/') const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/')
const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath ?? '') const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath!)
if (!downloadUrl) { if (!downloadUrl) {
throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 }) throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
} }
@@ -656,7 +656,7 @@ export function extensionForMediaMessage(message: WAMessageContent) {
extension = '.jpeg' extension = '.jpeg'
} else { } else {
const messageContent = message[type] as WAGenericMediaMessage const messageContent = message[type] as WAGenericMediaMessage
extension = getExtension(messageContent.mimetype ?? '') ?? '' extension = getExtension(messageContent.mimetype!)!
} }
return extension return extension
@@ -864,8 +864,8 @@ export const getWAUploadToServer = (
if (result?.url || result?.direct_path) { if (result?.url || result?.direct_path) {
urls = { urls = {
mediaUrl: result.url ?? '', mediaUrl: result.url!,
directPath: result.direct_path ?? '', directPath: result.direct_path!,
meta_hmac: result.meta_hmac, meta_hmac: result.meta_hmac,
fbid: result.fbid, fbid: result.fbid,
ts: result.ts ts: result.ts
+1 -1
View File
@@ -1770,7 +1770,7 @@ export const generateWAMessageFromContent = (
const innerContent = innerMessage[key as Exclude<keyof proto.IMessage, 'conversation'>] const innerContent = innerMessage[key as Exclude<keyof proto.IMessage, 'conversation'>]
const contextInfo: proto.IContextInfo = const contextInfo: proto.IContextInfo =
(innerContent && typeof innerContent === 'object' && 'contextInfo' in innerContent && (innerContent as Record<string, unknown>).contextInfo as proto.IContextInfo) || {} (innerContent && typeof innerContent === 'object' && 'contextInfo' in innerContent && (innerContent as Record<string, unknown>).contextInfo as proto.IContextInfo) || {}
contextInfo.participant = jidNormalizedUser(participant ?? '') contextInfo.participant = jidNormalizedUser(participant!)
contextInfo.stanzaId = quoted.key.id contextInfo.stanzaId = quoted.key.id
contextInfo.quotedMessage = quotedMsg contextInfo.quotedMessage = quotedMsg
+19 -22
View File
@@ -59,24 +59,22 @@ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_
/** Cleans a received message to further processing */ /** Cleans a received message to further processing */
export const cleanMessage = (message: WAMessage, meId: string, meLid: string) => { export const cleanMessage = (message: WAMessage, meId: string, meLid: 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
const remoteJid = message.key.remoteJid ?? '' if (isHostedPnUser(message.key.remoteJid!) || isHostedLidUser(message.key.remoteJid!)) {
if (isHostedPnUser(remoteJid) || isHostedLidUser(remoteJid)) {
message.key.remoteJid = jidEncode( message.key.remoteJid = jidEncode(
jidDecode(remoteJid)?.user ?? '', jidDecode(message.key?.remoteJid!)?.user!,
isHostedPnUser(remoteJid) ? 's.whatsapp.net' : 'lid' isHostedPnUser(message.key.remoteJid!) ? 's.whatsapp.net' : 'lid'
) )
} else { } else {
message.key.remoteJid = jidNormalizedUser(remoteJid) message.key.remoteJid = jidNormalizedUser(message.key.remoteJid!)
} }
const participantJid = message.key.participant ?? '' if (isHostedPnUser(message.key.participant!) || isHostedLidUser(message.key.participant!)) {
if (isHostedPnUser(participantJid) || isHostedLidUser(participantJid)) {
message.key.participant = jidEncode( message.key.participant = jidEncode(
jidDecode(participantJid)?.user ?? '', jidDecode(message.key.participant!)?.user!,
isHostedPnUser(participantJid) ? 's.whatsapp.net' : 'lid' isHostedPnUser(message.key.participant!) ? 's.whatsapp.net' : 'lid'
) )
} else { } else {
message.key.participant = jidNormalizedUser(participantJid) message.key.participant = jidNormalizedUser(message.key.participant!)
} }
const content = normalizeMessageContent(message.message) const content = normalizeMessageContent(message.message)
@@ -102,8 +100,8 @@ export const cleanMessage = (message: WAMessage, meId: string, meLid: string) =>
// if the sender believed the message being reacted to is not from them // if the sender believed the message being reacted to is not from them
// we've to correct the key to be from them, or some other participant // we've to correct the key to be from them, or some other participant
msgKey.fromMe = !msgKey.fromMe msgKey.fromMe = !msgKey.fromMe
? areJidsSameUser(msgKey.participant || (msgKey.remoteJid ?? ''), meId) || ? areJidsSameUser(msgKey.participant || (msgKey.remoteJid!), meId) ||
areJidsSameUser(msgKey.participant || (msgKey.remoteJid ?? ''), meLid) areJidsSameUser(msgKey.participant || (msgKey.remoteJid!), meLid)
: // if the message being reacted to, was from them : // if the message being reacted to, was from them
// fromMe automatically becomes false // fromMe automatically becomes false
false false
@@ -177,12 +175,11 @@ export const shouldIncrementChatUnread = (message: WAMessage) => !message.key.fr
* 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 }: WAMessageKey) => { export const getChatId = ({ remoteJid, participant, fromMe }: WAMessageKey) => {
const jid = remoteJid ?? '' if (isJidBroadcast(remoteJid!) && !isJidStatusBroadcast(remoteJid!) && !fromMe) {
if (isJidBroadcast(jid) && !isJidStatusBroadcast(jid) && !fromMe) { return participant!
return participant ?? ''
} }
return jid return remoteJid!
} }
type PollContext = { type PollContext = {
@@ -478,7 +475,7 @@ const processMessage = async (
ev.emit('messages.upsert', { ev.emit('messages.upsert', {
messages: [webMessageInfo as WAMessage], messages: [webMessageInfo as WAMessage],
type: 'notify', type: 'notify',
requestId: response.stanzaId ?? '' requestId: response.stanzaId!
}) })
} }
} }
@@ -517,10 +514,10 @@ const processMessage = async (
const labelAssociationMsg = protocolMsg.memberLabel const labelAssociationMsg = protocolMsg.memberLabel
if (labelAssociationMsg?.label) { if (labelAssociationMsg?.label) {
ev.emit('group.member-tag.update', { ev.emit('group.member-tag.update', {
groupId: chat.id ?? '', groupId: chat.id!,
label: labelAssociationMsg.label, label: labelAssociationMsg.label,
participant: message.key.participant ?? '', participant: message.key.participant!,
participantAlt: message.key.participantAlt ?? '', participantAlt: message.key.participantAlt!,
messageTimestamp: Number(message.messageTimestamp) messageTimestamp: Number(message.messageTimestamp)
}) })
} }
@@ -578,7 +575,7 @@ const processMessage = async (
const meIdNormalised = jidNormalizedUser(meId) const meIdNormalised = jidNormalizedUser(meId)
// all jids need to be PN // all jids need to be PN
const eventCreatorKey = creationMsgKey.participant || (creationMsgKey.remoteJid ?? '') const eventCreatorKey = creationMsgKey.participant || (creationMsgKey.remoteJid!)
const eventCreatorPn = isLidUser(eventCreatorKey) const eventCreatorPn = isLidUser(eventCreatorKey)
? await signalRepository.lidMapping.getPNForLID(eventCreatorKey) ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
: eventCreatorKey : eventCreatorKey
@@ -600,7 +597,7 @@ const processMessage = async (
const responseMsg = decryptEventResponse(encEventResponse, { const responseMsg = decryptEventResponse(encEventResponse, {
eventEncKey, eventEncKey,
eventCreatorJid, eventCreatorJid,
eventMsgId: creationMsgKey.id ?? '', eventMsgId: creationMsgKey.id!,
responderJid responderJid
}) })
+1 -1
View File
@@ -237,7 +237,7 @@ export const configureSuccessfulPairing = (
content: [ content: [
{ {
tag: 'device-identity', tag: 'device-identity',
attrs: { 'key-index': String(deviceIdentity.keyIndex ?? '') }, attrs: { 'key-index': deviceIdentity.keyIndex!.toString() },
content: accountEnc content: accountEnc
} }
] ]
+3 -3
View File
@@ -63,7 +63,7 @@ export const jidDecode = (jid: string | undefined): FullJid | undefined => {
const userCombined = jid.slice(0, sepIdx) const userCombined = jid.slice(0, sepIdx)
const [userAgent, device] = userCombined.split(':') const [userAgent, device] = userCombined.split(':')
const [user, agent] = (userAgent ?? '').split('_') const [user, agent] = userAgent!.split('_')
let domainType = WAJIDDomains.WHATSAPP let domainType = WAJIDDomains.WHATSAPP
if (server === 'lid') { if (server === 'lid') {
@@ -78,7 +78,7 @@ export const jidDecode = (jid: string | undefined): FullJid | undefined => {
return { return {
server: server as JidServer, server: server as JidServer,
user: user ?? '', user: user!,
domainType, domainType,
device: device ? +device : undefined device: device ? +device : undefined
} }
@@ -114,7 +114,7 @@ export const isAnyPnUser = (jid: string | undefined) =>
const botRegexp = /^1313555\d{4}$|^131655500\d{2}$/ const botRegexp = /^1313555\d{4}$|^131655500\d{2}$/
export const isJidBot = (jid: string | undefined) => jid && botRegexp.test(jid.split('@')[0] ?? '') && jid.endsWith('@c.us') export const isJidBot = (jid: string | undefined) => jid && botRegexp.test(jid.split('@')[0]!) && jid.endsWith('@c.us')
export const jidNormalizedUser = (jid: string | undefined) => { export const jidNormalizedUser = (jid: string | undefined) => {
const result = jidDecode(jid) const result = jidDecode(jid)
@@ -35,7 +35,7 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
return { return {
tag: 'bot', tag: 'bot',
attrs: {}, attrs: {},
content: [{ tag: 'profile', attrs: { persona_id: user.personaId ?? '' } }] content: [{ tag: 'profile', attrs: { persona_id: user.personaId! } }]
} }
} }
@@ -51,24 +51,24 @@ export class USyncBotProfileProtocol implements USyncQueryProtocol {
for (const command of getBinaryNodeChildren(commandsNode, 'command')) { for (const command of getBinaryNodeChildren(commandsNode, 'command')) {
commands.push({ commands.push({
name: getBinaryNodeChildString(command, 'name') ?? '', name: getBinaryNodeChildString(command, 'name')!,
description: getBinaryNodeChildString(command, 'description') ?? '' description: getBinaryNodeChildString(command, 'description')!
}) })
} }
for (const prompt of getBinaryNodeChildren(promptsNode, 'prompt')) { for (const prompt of getBinaryNodeChildren(promptsNode, 'prompt')) {
prompts.push(`${getBinaryNodeChildString(prompt, 'emoji') ?? ''} ${getBinaryNodeChildString(prompt, 'text') ?? ''}`) prompts.push(`${getBinaryNodeChildString(prompt, 'emoji')!} ${getBinaryNodeChildString(prompt, 'text')!}`)
} }
return { return {
isDefault: !!getBinaryNodeChild(profile, 'default'), isDefault: !!getBinaryNodeChild(profile, 'default'),
jid: node.attrs.jid ?? '', jid: node.attrs.jid!,
name: getBinaryNodeChildString(profile, 'name') ?? '', name: getBinaryNodeChildString(profile, 'name')!,
attributes: getBinaryNodeChildString(profile, 'attributes') ?? '', attributes: getBinaryNodeChildString(profile, 'attributes')!,
description: getBinaryNodeChildString(profile, 'description') ?? '', description: getBinaryNodeChildString(profile, 'description')!,
category: getBinaryNodeChildString(profile, 'category') ?? '', category: getBinaryNodeChildString(profile, 'category')!,
personaId: profile?.attrs['persona_id'] ?? '', personaId: profile!.attrs['persona_id']!,
commandsDescription: getBinaryNodeChildString(commandsNode, 'description') ?? '', commandsDescription: getBinaryNodeChildString(commandsNode, 'description')!,
commands, commands,
prompts prompts
} }