MPWA Implementation

WhatsApp Gateway - Baileys Migration Documentation

📋 Overview

This document describes the implementation changes made during the migration from @onexgen/baileys to @whiskeysockets/baileys and restoration of core functionality.

Package Changes

Old Package New Package
@onexgen/[email protected] @whiskeysockets/baileys
[email protected] [email protected]

✅ Features Implemented

💬Real-time Chat
🤖Autoreplies
🔗Webhooks
🆔LID Support
📱Media Messages
👥Group Support

📁 Core Files Modified

server/whatsapp.js Rewritten

Main WhatsApp connection and message handling module.

Function Description
connectToWhatsApp() Establishes WhatsApp connection
formatJid() Formats phone/LID/group to proper JID
sendText() Sends text messages
sendMedia() Sends media messages
processAutoreply() Handles autoreplies
sendToWebhook() Sends to configured webhook

server/chat.js New

Socket.IO event handlers for real-time chat.

Event Direction Description
send-message Client → Server Send text message
upload-chunk Client → Server Upload file chunks
message:new Server → Client New message broadcast
session:updated Server → Client Session update

🐘 PHP Files Modified

app/Http/Controllers/ChatController.php Replaced

Laravel controller for chat page - replaced encrypted version with clean implementation.

Method Description
index() Renders chat page with sessions
messages($sessionId) Returns messages for a session as JSON
setSessionName() Updates session custom name

resources/themes/vuexy/views/pages/autoreply.blade.php Fixed

Fixed missing form action URL for autoreply creation.

// Before (broken)
<form action="" method="POST">

// After (fixed)
<form action="{{ route('autoreply.store') }}" method="POST">

🗑️ Encrypted Files Deleted

The following obfuscated/encrypted files were removed and replaced with clean implementations:

Deleted File Replacement Status
server/whatsapp.js (obfuscated) Clean Baileys implementation ✓ Replaced
server/chat.js (obfuscated) New Socket.IO handlers ✓ Replaced
server/incomingMessage.js (obfuscated) Merged into whatsapp.js ✓ Replaced
ChatController.php (encrypted) Clean PHP controller ✓ Replaced

🗄️ Database Changes

Column modifications to support longer phone numbers (group IDs):

ALTER TABLE chat_sessions MODIFY phone_number VARCHAR(50);
ALTER TABLE chat_messages MODIFY number VARCHAR(50);

🔌 API Routes

Endpoint Description
POST /backend-send-text Send text message
POST /backend-send-media Send media message
POST /backend-send-location Send location
POST /backend-send-vcard Send contact card
POST /backend-send-sticker Send sticker
POST /backend-send-poll Send poll
POST /backend-check-number Verify WhatsApp number
POST /backend-fetch-groups Get all groups

🔗 Webhook Format

When a message is received, a POST request is sent to your webhook URL:

{
  "type": "incoming_message",
  "device": "62819876543",
  "sender": "628123456789",
  "push_name": "John Doe",
  "is_group": false,
  "message_type": "text",
  "message": "Hello world",
  "attachment": "",
  "message_id": "3EB01234567890",
  "timestamp": "2024-12-24T10:00:00.000Z"
}

Message Types

text image video audio
document sticker location vcard

🤖 Autoreply System

How it works

  1. Incoming message is received
  2. Keywords are matched (Equal or Contain mode)
  3. Reply is sent based on reply_when setting
  4. Supports: typing indicator, read receipt, delay, quoted reply

Reply Types Supported

Text, Image, Video, Audio, Sticker, Location, VCard, Product

🆔 LID Support

The system automatically detects and formats different ID types:

| Input Format             | Output JID                        |
|--------------------------|-----------------------------------|
| 628123456789             | [email protected]       |
| 135119855710311:48       | 135119855710311:48@lid            |
| 1234567890-1234567890    | [email protected]        |

🔧 Troubleshooting

Error Solution
Unsupported state or unable to authenticate Delete credentials folder and re-scan QR
Data too long for column Run ALTER TABLE to increase column size
Session not found Restart PM2 and verify device is connected

PM2 Commands

# Restart server
npx pm2 restart pmwa2

# View logs
npx pm2 logs pmwa2

# Check status
npx pm2 status

🛡️ Security Hardening

The following routes have been disabled to prevent security vulnerabilities:

File Manager Security

Route Risk Status
fm.create-file Could create malicious PHP files 🔒 Blocked
fm.update-file Could edit existing files 🔒 Blocked
fm.zip Could bypass file restrictions 🔒 Blocked
fm.unzip Could extract malicious archives 🔒 Blocked

Auto-Update Disabled

The auto-update system has been disabled due to Remote Code Execution (RCE) risks.

Route Risk Status
/admin/update Downloads and executes PHP from external server 🔒 Blocked
/admin/update/install Extracts ZIP to base path, runs remote commands 🔒 Blocked

⚠️ Updates must now be performed manually.

Allowed File Types

Only the following file types can be uploaded:

PDF, JPEG, JPG, PNG, GIF

Max upload size: 10MB

📅 Updates - December 27, 2024

Registration Alert Fix Fixed

Fixed missing success notification after user registration.

File Change
login.blade.php Added alert component inside login sidebar to display registration success message
@if (session()->has('alert'))
    <x-alert>
        @slot('type', session('alert')['type'])
        @slot('msg', session('alert')['msg'])
    </x-alert>
@endif

Pairing Code Implementation New

Implemented pairing code support for WhatsApp device connection via /code/{number} route.

File Change
server/whatsapp.js Added requestPairingCode() logic in connectToWhatsApp()

How it works:

  1. When usePairingCode = true, system calls socket.requestPairingCode(token)
  2. Emits code event to frontend with 8-digit pairing code
  3. Handles rate-limit errors with rate-limit event
  4. Frontend displays code as XXXX-XXXX format

📅 Updates - February 4, 2026

🔐 Registration CAPTCHA New

Added CAPTCHA to the registration form to prevent bot sign-ups.

File Change
config/captcha.php CAPTCHA configuration: 4 characters, A-Z + 1-9, case-insensitive
RegisterController.php Added captcha validation rule
register.blade.php Added CAPTCHA image, input field, and refresh button
// Validation rule added:
'captcha' => 'required|captcha'

🛡️ File Manager Security Hardening Enhanced

Significantly improved file upload security with multi-layer protection.

Protection Layer Description
Extension Whitelist Only jpg, jpeg, png, gif, webp, pdf, doc, docx, xls, xlsx, csv
Max File Size Reduced from 10MB to 2MB
MIME Type Validation Verifies actual file content matches declared MIME type
Extension-MIME Matching Blocks files with mismatched extension and content type
Polyglot Detection Scans file content for embedded PHP/script code

Blocked Content Patterns:

<?php, <?=, <script, eval(, base64_decode(, 
exec(, system(, passthru(, shell_exec(, 
popen(, proc_open(, __halt_compiler

✅ API User Verification Fixed

Users created via API are now automatically marked as verified.

File Change
ApiController.php Added status => 'verified' and email_verified_at to user creation
User::create([
    // ... other fields
    'email_verified_at' => Carbon::now(),
    'status' => 'verified',
]);

🗑️ Removed Dangerous File Types Security

The following file types have been removed from the upload whitelist:

Type Reason
svg Can contain embedded JavaScript (XSS attacks)
mp4, webm, mp3, wav Media files not required for core functionality
zip, rar Can contain malware and bypass file restrictions

📝 Security Logging New

All blocked uploads are now logged with detailed information:

// Log entries include:
- Filename
- MIME type detected
- Extension used  
- User ID
- IP Address
- Pattern found (for malicious content)

Check storage/logs/laravel.log for blocked upload attempts.

Last Updated: February 4, 2026