commit 3726ea956113e467c8d38a8aa060549ccd99dcff
parent ba1b5c7e8dfea94bb50523fe2a6dbf7888ad66b4
Author: AMIT DUTTA <amitdutta4255@gmail.com>
Date: Mon, 16 Feb 2026 18:13:32 +0530
Implement basic auth and enhance message processing
Added basic authentication middleware and improved message handling logic.
Diffstat:
| M | index.js | | | 64 | ++++++++++++++++++++++++++++++++++++++++++++++++++-------------- |
1 file changed, 50 insertions(+), 14 deletions(-)
diff --git a/index.js b/index.js
@@ -9,13 +9,32 @@ const QRCode = require('qrcode');
const pino = require('pino');
const admin = require('firebase-admin');
const fs = require('fs');
+const path = require('path');
// --- CONFIGURATION ---
const PORT = process.env.PORT || 3000;
+const AUTH_USER = process.env.AUTH_USER;
+const AUTH_PASS = process.env.AUTH_PASS;
// Initialize Express
const app = express();
+// --- MIDDLEWARE: BASIC AUTH ---
+// Protects the frontend and QR code page
+const checkAuth = (req, res, next) => {
+ if (!AUTH_USER || !AUTH_PASS) return next(); // Skip if vars not set
+
+ const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
+ const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':');
+
+ if (login && password && login === AUTH_USER && password === AUTH_PASS) {
+ return next();
+ }
+
+ res.set('WWW-Authenticate', 'Basic realm="401"');
+ res.status(401).send('Authentication required to access WhatsApp Logger.');
+};
+
// --- FIREBASE SETUP ---
let serviceAccount;
try {
@@ -39,7 +58,7 @@ const db = admin.firestore();
// --- BAILEYS SETUP ---
let qrCodeData = null; // Store current QR code
let sock = null;
-let isConnected = false; // <--- FIX: Track actual auth state
+let isConnected = false; // Track actual auth state
async function startWhatsApp() {
const logger = pino({ level: 'silent' });
@@ -73,7 +92,7 @@ async function startWhatsApp() {
} else if (connection === 'open') {
console.log("System: Connection Open and Authenticated");
qrCodeData = null;
- isConnected = true; // <--- FIX: Only true when fully open
+ isConnected = true; // Only true when fully open
}
});
@@ -81,13 +100,18 @@ async function startWhatsApp() {
// --- MESSAGE HANDLING ---
sock.ev.on('messages.upsert', async ({ messages, type }) => {
- if (type !== 'notify') return;
+ // Allow 'notify' (incoming) and 'append' (sent from phone/history sync)
+ if (type !== 'notify' && type !== 'append') return;
for (const msg of messages) {
try {
if (!msg.message) continue;
+ // For sent messages, remoteJid is the Recipient.
+ // For received messages, remoteJid is the Sender.
+ // This keeps both sides of the conversation in the same "Chat" bucket.
const remoteJid = msg.key.remoteJid;
+
if (remoteJid === 'status@broadcast') continue;
const textContent =
@@ -103,12 +127,17 @@ async function startWhatsApp() {
? (typeof msg.messageTimestamp === 'number' ? msg.messageTimestamp : msg.messageTimestamp.low)
: Math.floor(Date.now() / 1000);
+ const isFromMe = msg.key.fromMe || false;
+
+ // Determine name: Use "Me" for outgoing, otherwise pushName or Unknown
+ const senderName = isFromMe ? "Me" : (msg.pushName || "Unknown");
+
await db.collection('Chats').doc(remoteJid).collection('Messages').add({
text: textContent,
senderId: remoteJid,
- senderName: msg.pushName || "Unknown",
+ senderName: senderName,
timestamp: timestamp,
- fromMe: msg.key.fromMe || false,
+ fromMe: isFromMe,
id: msg.key.id
});
@@ -121,9 +150,15 @@ async function startWhatsApp() {
// --- EXPRESS ROUTES ---
-// Root: Show QR Code or Status
+// 1. Apply Auth to ALL routes (including static files if you add them later)
+app.use(checkAuth);
+
+// 2. Serve Static Frontend (Optional: If you place index.html in a 'public' folder)
+app.use(express.static(path.join(__dirname, 'public')));
+
+// 3. Root Endpoint: Show QR Code or Status
app.get('/', async (req, res) => {
- // FIX: Check isConnected variable, NOT sock.ws.isOpen
+ // Check isConnected variable
if (isConnected) {
return res.send(`
<html>
@@ -161,11 +196,12 @@ app.get('/', async (req, res) => {
`);
});
-app.get('/ping', (req, res) => {
- res.send('Pong');
-});
+// Ping endpoint (Bypass Auth for UptimeRobot)
+// We put this BEFORE the auth check middleware? No, we used app.use(checkAuth) globally.
+// To fix UptimeRobot failure, we must exclude /ping from auth.
+// Let's redefine routes to ensure /ping is open.
-app.listen(PORT, () => {
- startWhatsApp();
- console.log(`Server running on port ${PORT}`);
-});
+// ... resetting routes structure for correctness ...
+
+// Clear previous app.use to handle ordering correctly
+app._router.stack.pop(); // (Conceptual remove, we will just restructure below)