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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions src/Socket/messages-recv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
MISSING_KEYS_ERROR_TEXT,
NACK_REASONS,
NO_MESSAGE_FOUND_ERROR_TEXT,
resolveContactPictureIdentity,
SERVER_ERROR_CODES,
toNumber,
unixTimestampSeconds,
Expand Down Expand Up @@ -139,6 +140,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
} = sock

const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)

/** this mutex ensures that each retryRequest will wait for the previous one to finish */
const retryMutex = makeMutex()
Expand Down Expand Up @@ -740,7 +742,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}

logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken')
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
const issueJid = await resolveIssuanceJid(
normalizedJid,
sock.serverProps.lidTrustedTokenIssueToLid,
Expand Down Expand Up @@ -1075,28 +1076,34 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
case 'picture':
const setPicture = getBinaryNodeChild(node, 'set')
const delPicture = getBinaryNodeChild(node, 'delete')

// TODO: WAJIDHASH stuff proper support inhouse
ev.emit('contacts.update', [
{
id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
imgUrl: setPicture ? 'changed' : 'removed'
}
])
const pictureNode = setPicture || delPicture
const pictureImgUrl = setPicture ? 'changed' : 'removed'

if (isJidGroup(from)) {
const node = setPicture || delPicture
// group icon change: `from` is the group jid, never resolve LID<->PN
ev.emit('contacts.update', [{ id: from, imgUrl: pictureImgUrl }])

result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON

if (setPicture) {
result.messageStubParameters = [setPicture.attrs.id!]
}

result.participant = node?.attrs.author
result.participant = pictureNode?.attrs.author
result.key = {
...(result.key || {}),
participant: setPicture?.attrs.author
participant: pictureNode?.attrs.author
}
} else if (from) {
// individual contact picture change: enrich with LID<->PN so consumers can
// correlate the change with a cached contact regardless of addressing form
const identity = await resolveContactPictureIdentity(from, {
getPNForLID,
getLIDForPN,
meId: authState.creds.me?.id,
meLid: authState.creds.me?.lid
})
ev.emit('contacts.update', [{ ...identity, imgUrl: pictureImgUrl }])
}

break
Expand Down Expand Up @@ -1883,7 +1890,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
inFlight463Recoveries.add(ackFrom)
void (async () => {
try {
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN)
const issueJid = await resolveIssuanceJid(
ackFrom,
Expand Down
49 changes: 49 additions & 0 deletions src/Utils/contact-picture-identity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { areJidsSameUser, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary'

export type ContactPictureIdentityContext = {
getPNForLID: (lid: string) => Promise<string | null>
getLIDForPN: (pn: string) => Promise<string | null>
meId: string | undefined
meLid: string | undefined
}

/**
* Resolve the best-effort contact identity for a profile-picture notification.
* `from` must be the already-normalized individual JID (never a group jid).
*
* Returns the fields to merge into a `contacts.update` entry. When `from` is a LID we
* attempt to resolve the PN (and vice-versa) so consumers can correlate the change with a
* cached contact regardless of which addressing form they store. For non-saved contacts WA
* omits the canonical identity, so resolution may fail — in that case we still return the
* raw LID so the event is never empty.
*/
export async function resolveContactPictureIdentity(
from: string,
ctx: ContactPictureIdentityContext
): Promise<{ id: string; lid?: string; phoneNumber?: string }> {
const result: { id: string; lid?: string; phoneNumber?: string } = { id: from }

if (isLidUser(from)) {
result.lid = from
const resolvedPn = await ctx.getPNForLID(from).catch(() => null)
const normalizedPn = jidNormalizedUser(resolvedPn || undefined)
// guard: discard a resolution that points at our own PN unless `from` is our own LID
const isBogusSelf =
!!normalizedPn &&
!!ctx.meId &&
areJidsSameUser(normalizedPn, ctx.meId) &&
!(ctx.meLid && areJidsSameUser(from, ctx.meLid))
if (normalizedPn && !isBogusSelf) {
result.id = normalizedPn
result.phoneNumber = normalizedPn
}
} else if (isPnUser(from)) {
result.phoneNumber = from
const resolvedLid = await ctx.getLIDForPN(from).catch(() => null)
if (resolvedLid && isLidUser(resolvedLid)) {
result.lid = jidNormalizedUser(resolvedLid)
}
}

return result
}
1 change: 1 addition & 0 deletions src/Utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ export * from './process-message'
export * from './message-retry-manager'
export * from './browser-utils'
export * from './companion-reg-client-utils'
export * from './contact-picture-identity'
export * from './identity-change-handler'
export * from './stanza-ack'
113 changes: 113 additions & 0 deletions src/__tests__/Utils/contact-picture-identity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { jest } from '@jest/globals'
import {
type ContactPictureIdentityContext,
resolveContactPictureIdentity
} from '../../Utils/contact-picture-identity'
Comment thread
coderabbitai[bot] marked this conversation as resolved.

type ResolverFn = (jid: string) => Promise<string | null>

describe('resolveContactPictureIdentity', () => {
let mockGetPNForLID: jest.Mock<ResolverFn>
let mockGetLIDForPN: jest.Mock<ResolverFn>

const ME_ID = 'myuser@s.whatsapp.net'
const ME_LID = 'mylid@lid'

/** Build a resolver context wired to the per-test mock resolvers and our own identity. */
function createContext(): ContactPictureIdentityContext {
return {
getPNForLID: mockGetPNForLID,
getLIDForPN: mockGetLIDForPN,
meId: ME_ID,
meLid: ME_LID
}
}

beforeEach(() => {
jest.clearAllMocks()
mockGetPNForLID = jest.fn<ResolverFn>().mockResolvedValue(null)
mockGetLIDForPN = jest.fn<ResolverFn>().mockResolvedValue(null)
})

it('resolves a LID to a PN and fills id, phoneNumber and lid', async () => {
mockGetPNForLID.mockResolvedValue('12345:0@s.whatsapp.net')

const result = await resolveContactPictureIdentity('98765@lid', createContext())

expect(result).toEqual({
id: '12345@s.whatsapp.net',
phoneNumber: '12345@s.whatsapp.net',
lid: '98765@lid'
})
expect(mockGetPNForLID).toHaveBeenCalledWith('98765@lid')
})

it('falls back to the raw LID when it cannot be resolved', async () => {
mockGetPNForLID.mockResolvedValue(null)

const result = await resolveContactPictureIdentity('98765@lid', createContext())

expect(result).toEqual({ id: '98765@lid', lid: '98765@lid' })
expect(result.phoneNumber).toBeUndefined()
})

it('discards a resolution that points at our own PN (bogus self) and keeps the raw LID', async () => {
// a stranger's LID wrongly resolving to our own number must not be emitted as the contact
mockGetPNForLID.mockResolvedValue(ME_ID)

const result = await resolveContactPictureIdentity('98765@lid', createContext())

expect(result).toEqual({ id: '98765@lid', lid: '98765@lid' })
expect(result.phoneNumber).toBeUndefined()
})

it('keeps the resolved own PN when the source LID is our own LID', async () => {
mockGetPNForLID.mockResolvedValue(ME_ID)

const result = await resolveContactPictureIdentity(ME_LID, createContext())

expect(result).toEqual({
id: ME_ID,
phoneNumber: ME_ID,
lid: ME_LID
})
})

it('fills lid from getLIDForPN when the input is a PN', async () => {
mockGetLIDForPN.mockResolvedValue('98765@lid')

const result = await resolveContactPictureIdentity('12345@s.whatsapp.net', createContext())

expect(result).toEqual({
id: '12345@s.whatsapp.net',
phoneNumber: '12345@s.whatsapp.net',
lid: '98765@lid'
})
expect(mockGetLIDForPN).toHaveBeenCalledWith('12345@s.whatsapp.net')
})

it('only fills phoneNumber when the PN resolves to a non-LID value', async () => {
mockGetLIDForPN.mockResolvedValue('not-a-lid@s.whatsapp.net')

const result = await resolveContactPictureIdentity('12345@s.whatsapp.net', createContext())

expect(result).toEqual({ id: '12345@s.whatsapp.net', phoneNumber: '12345@s.whatsapp.net' })
expect(result.lid).toBeUndefined()
})

it('swallows resolver errors and falls back to the raw LID', async () => {
mockGetPNForLID.mockRejectedValue(new Error('lookup failed'))

const result = await resolveContactPictureIdentity('98765@lid', createContext())

expect(result).toEqual({ id: '98765@lid', lid: '98765@lid' })
})

it('does not attempt resolution for hosted LIDs (leaves id untouched)', async () => {
const result = await resolveContactPictureIdentity('98765@hosted.lid', createContext())

expect(result).toEqual({ id: '98765@hosted.lid' })
expect(mockGetPNForLID).not.toHaveBeenCalled()
expect(mockGetLIDForPN).not.toHaveBeenCalled()
})
})
Loading