Skip to content

fix: ignore empty link code companion reg#2608

Open
frndchagas wants to merge 1 commit into
WhiskeySockets:masterfrom
frndchagas:fix/ignore-empty-link-code-companion-reg
Open

fix: ignore empty link code companion reg#2608
frndchagas wants to merge 1 commit into
WhiskeySockets:masterfrom
frndchagas:fix/ignore-empty-link-code-companion-reg

Conversation

@frndchagas

@frndchagas frndchagas commented May 30, 2026

Copy link
Copy Markdown

Summary

  • Guard link_code_companion_reg handling when the notification is missing the pairing buffers Baileys currently needs.
  • Skip the incomplete notification instead of throwing while processing incoming nodes.
  • Keep the debug log scoped to safe structured fields (id and type) instead of logging the full node.
  • Add unit coverage for incomplete notifications and valid companion registration payloads.

Protocol / behavior context

WhatsApp can deliver a link_code_companion_reg notification without the fields used by Baileys's current companion-registration path. That malformed or partial stanza should not crash the receive path. This PR is intentionally defensive: it preserves the existing handling for complete payloads and prevents crashes when the required buffers are absent.

WA Web captured JS sanity

Ran:

./tools/wa-web-sanity.sh 'link_code_companion_reg|companion_reg_refresh|DeviceLinkingHandleNotification'

Relevant matches from the captured WA Web bundle:

  • WAWeb/Comms/HandleLoggedInStanza.js
  • WAWeb/Alt/DeviceLinkingHandleNotification.js
  • WA/Smax/InMdRefreshCodeNotifyCompanionRequest.js

Relevant excerpt:

if (!Array.isArray(t) || !t.length) return makeDeliverResponseBadStanza({ ackError: 487 }, e)

The captured handler also branches by stage, including primary_hello and refresh_code. This PR does not claim to fully mirror that stage-specific flow; it only fixes the crash surface reported in #2600 by making Baileys tolerate incomplete pairing data safely.

Tests

  • yarn lint (0 errors; existing warnings remain)
  • yarn test

Fixes #2600

Drafted with Codex, reviewed and tested by me.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced device linking stability through improved handling of incomplete or missing pairing data during companion registration. The system now logs debug information instead of failing.
  • Tests

    • Added comprehensive tests for device pairing buffer extraction, covering successful extractions, missing data scenarios, and validation edge cases.

Review Change Stack

@whiskeysockets-bot

whiskeysockets-bot commented May 30, 2026

Copy link
Copy Markdown
Contributor

Thanks for opening this pull request and contributing to the project!

The next step is for the maintainers to review your changes. If everything looks good, it will be approved and merged into the main branch.

In the meantime, anyone in the community is encouraged to test this pull request and provide feedback.

✅ How to confirm it works

If you’ve tested this PR, please comment below with:

Tested and working ✅

This helps us speed up the review and merge process.

📦 To test this PR locally:

# NPM
npm install @whiskeysockets/baileys@frndchagas/Baileys#fix/ignore-empty-link-code-companion-reg

# Yarn (v2+)
yarn add @whiskeysockets/baileys@frndchagas/Baileys#fix/ignore-empty-link-code-companion-reg

# PNPM
pnpm add @whiskeysockets/baileys@frndchagas/Baileys#fix/ignore-empty-link-code-companion-reg

If you encounter any issues or have feedback, feel free to comment as well.

@coderabbitai

coderabbitai Bot commented May 30, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c18197d5-2fe0-4274-95ae-6b1356752847

📥 Commits

Reviewing files that changed from the base of the PR and between e574378 and 3bdfaf0.

📒 Files selected for processing (2)
  • src/Socket/messages-recv.ts
  • src/__tests__/Socket/messages-recv.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/tests/Socket/messages-recv.test.ts
  • src/Socket/messages-recv.ts

📝 Walkthrough

Walkthrough

Adds an exported helper that extracts and normalizes pairing buffers from link_code_companion_reg nodes; updates the notification handler to call the helper and log-and-skip when required fields are missing. Tests validate missing-field and successful-extraction behaviors.

Changes

Link Code Companion Registration Robustness

Layer / File(s) Summary
Safe buffer extraction helper and notification handler integration
src/Socket/messages-recv.ts, src/__tests__/Socket/messages-recv.test.ts
New exported extractLinkCodeCompanionRegBuffers validates and normalizes ref, primaryIdentityPublicKey, and primaryEphemeralPublicKeyWrapped from link_code_companion_reg nodes, returning undefined when any required field is missing. The link_code_companion_reg notification handler now calls this helper and logs-and-skips processing instead of performing unsafe buffer extraction. Tests cover missing pairing data, missing fields, and successful buffer extraction.

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels: testing needed

Suggested reviewers:

  • purpshell
  • vinikjkkj

🐰 I nibble on buffers with care,
If fields are gone, I skip the snare.
Keys wrapped tight, or absent, too —
I check and convert before I chew.
Now pairing hops along anew! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: ignore empty link code companion reg' directly addresses the main change—adding guard handling to skip incomplete link_code_companion_reg notifications instead of crashing.
Linked Issues check ✅ Passed The PR fully implements requirements from #2600: it extracts required pairing buffers into a helper, returns undefined when fields are missing, and skips processing with debug logging instead of throwing.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the link_code_companion_reg handler crash reported in #2600; no unrelated modifications are present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/Socket/messages-recv.ts (1)

1154-1225: ⚡ Quick win

Wrap link_code_companion_reg case in its own block
noSwitchDeclarations is enabled in this repo; enclosing the case body avoids TDZ/cross-case scope pitfalls from lexical declarations.

Proposed fix
-			case 'link_code_companion_reg':
+			case 'link_code_companion_reg': {
 				const linkCodeCompanionRegBuffers = extractLinkCodeCompanionRegBuffers(node)
 				if (!linkCodeCompanionRegBuffers) {
 					logger.debug(
 						{ id: node.attrs.id, type: node.attrs.type },
 						'link_code_companion_reg notification without pairing data, skipping'
 					)
 					break
 				}
 
 				const { ref, primaryIdentityPublicKey, primaryEphemeralPublicKeyWrapped } = linkCodeCompanionRegBuffers
 				const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped)
@@
 				authState.creds.registered = true
 				ev.emit('creds.update', authState.creds)
 				break
+			}
 			case 'privacy_token':
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Socket/messages-recv.ts` around lines 1154 - 1225, The case
'link_code_companion_reg' declares lexical bindings that can leak into other
switch cases due to noSwitchDeclarations; fix by wrapping the entire case body
in its own block (e.g., add { ... } after case 'link_code_companion_reg':) so
vars like linkCodeCompanionRegBuffers, codePairingPublicKey, companionSharedKey,
linkCodeSalt, linkCodePairingExpanded, encryptPayload, encryptIv,
encryptedPayload, identitySharedKey and modifications to authState.creds are
scoped to that case; ensure the existing await query(...) and
ev.emit('creds.update', ...) remain inside the new block and nothing else
changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/Socket/messages-recv.ts`:
- Around line 1154-1225: The case 'link_code_companion_reg' declares lexical
bindings that can leak into other switch cases due to noSwitchDeclarations; fix
by wrapping the entire case body in its own block (e.g., add { ... } after case
'link_code_companion_reg':) so vars like linkCodeCompanionRegBuffers,
codePairingPublicKey, companionSharedKey, linkCodeSalt, linkCodePairingExpanded,
encryptPayload, encryptIv, encryptedPayload, identitySharedKey and modifications
to authState.creds are scoped to that case; ensure the existing await query(...)
and ev.emit('creds.update', ...) remain inside the new block and nothing else
changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 84b12a58-ea62-4572-ae0b-3f5a2feaa06d

📥 Commits

Reviewing files that changed from the base of the PR and between 78e7e4e and e574378.

📒 Files selected for processing (2)
  • src/Socket/messages-recv.ts
  • src/__tests__/Socket/messages-recv.test.ts

@frndchagas frndchagas force-pushed the fix/ignore-empty-link-code-companion-reg branch from e574378 to 3bdfaf0 Compare May 30, 2026 02:55
@frndchagas frndchagas marked this pull request as ready for review May 30, 2026 02:56

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

You’re at about 99% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Re-trigger cubic

@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open for 14 days with no activity. Remove the stale label or comment or this will be closed in 14 days

@github-actions github-actions Bot added the Stale label Jun 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

[BUG] link_code_companion_reg notification crashes with 'Invalid buffer' during pairing

2 participants