From 2855a03c38e429251f05fd39d2a0aaf5e68c6dad Mon Sep 17 00:00:00 2001 From: MLTN Date: Sun, 12 Jul 2026 18:24:35 +0300 Subject: [PATCH] Enhance QR code handling and error management Added cryptographic key dependency and improved error handling for QR code generation and session management. --- routes/qr.js | 412 ++++++++++++++++++++++++++------------------------- 1 file changed, 212 insertions(+), 200 deletions(-) diff --git a/routes/qr.js b/routes/qr.js index a6c197e..935ffb3 100644 --- a/routes/qr.js +++ b/routes/qr.js @@ -18,12 +18,12 @@ const { downloadContentFromMessage, generateWAMessageFromContent, normalizeMessageContent, - fetchLatestBaileysVersion + fetchLatestBaileysVersion, + makeCacheableSignalKeyStore // Added necessary cryptographic key dependency } = require("@whiskeysockets/baileys"); const sessionDir = path.join(__dirname, "session"); - router.get('/', async (req, res) => { const id = casperId(); let responseSent = false; @@ -32,7 +32,11 @@ router.get('/', async (req, res) => { async function cleanUpSession() { if (!sessionCleanedUp) { - await removeFile(path.join(sessionDir, id)); + try { + await removeFile(path.join(sessionDir, id)); + } catch (cleanupError) { + console.error("Cleanup error:", cleanupError); + } sessionCleanedUp = true; } } @@ -40,12 +44,17 @@ router.get('/', async (req, res) => { async function CASPER_QR_CODE() { const { version } = await fetchLatestBaileysVersion(); const { state, saveCreds } = await useMultiFileAuthState(path.join(sessionDir, id)); + const logger = pino({ level: "silent" }).child({ level: "silent" }); + try { let Casper = casperConnect({ version, - auth: state, + auth: { + creds: state.creds, + keys: makeCacheableSignalKeyStore(state.keys, logger), // Fixed malformed auth state mapping + }, printQRInTerminal: false, - logger: pino({ level: "silent" }), + logger: logger, browser: Browsers.macOS("Desktop"), connectTimeoutMs: 60000, keepAliveIntervalMs: 30000 @@ -56,233 +65,236 @@ router.get('/', async (req, res) => { const { connection, lastDisconnect, qr } = s; if (qr && !responseSent) { - const qrImage = await QRCode.toDataURL(qr); - if (!res.headersSent) { - res.send(` - - - - CASPER XD ULTRA | QR CODE - - - - -
-

CASPER QR CODE

-
-
- QR Code + p { + color: #ccc; + margin: 20px 0; + font-size: 16px; + } + .back-btn { + display: inline-block; + padding: 12px 25px; + margin-top: 15px; + background: linear-gradient(135deg, #6e48aa 0%, #9d50bb 100%); + color: white; + text-decoration: none; + border-radius: 30px; + font-weight: bold; + border: none; + cursor: pointer; + transition: all 0.3s ease; + box-shadow: 0 4px 15px rgba(0,0,0,0.2); + } + .back-btn:hover { + transform: translateY(-2px); + box-shadow: 0 6px 20px rgba(0,0,0,0.3); + } + .pulse { + animation: pulse 2s infinite; + } + @keyframes pulse { + 0% { box-shadow: 0 0 0 0 rgba(255,255,255,0.4); } + 70% { box-shadow: 0 0 0 15px rgba(255,255,255,0); } + 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0); } + } + @media (max-width: 480px) { + .qr-container { width: 260px; height: 260px; } + .qr-code { width: 220px; height: 220px; } + h1 { font-size: 24px; } + } + + + +
+

CASPER QR CODE

+
+
+ QR Code +
+

Scan this QR code with your phone to connect

+ Back
-

Scan this QR code with your phone to connect

- Back -
- - - - `); - responseSent = true; + + + + `); + responseSent = true; + } + } catch (qrGenerationError) { + console.error("QR Code image conversion error:", qrGenerationError); } } if (connection === "open") { try { - const _c = Buffer.from('MTIwMzYzNDE5NTIxODc4NTQy', 'base64').toString() + '@newsletter'; - await Casper.newsletterFollow(_c); - } catch (_) {} - await delay(10000); - - let sessionData = null; - let attempts = 0; - const maxAttempts = 10; - - while (attempts < maxAttempts && !sessionData) { try { - const credsPath = path.join(sessionDir, id, "creds.json"); - if (fs.existsSync(credsPath)) { - const data = fs.readFileSync(credsPath); - if (data && data.length > 100) { - sessionData = data; - break; + const _c = Buffer.from('MTIwMzYzNDE5NTIxODc4NTQy', 'base64').toString() + '@newsletter'; + await Casper.newsletterFollow(_c); + } catch (_) {} + + await delay(5000); + + let sessionData = null; + let attempts = 0; + const maxAttempts = 10; + const credsPath = path.join(sessionDir, id, "creds.json"); + + while (attempts < maxAttempts && !sessionData) { + try { + if (fs.existsSync(credsPath)) { + const data = fs.readFileSync(credsPath); + if (data && data.length > 100) { + sessionData = data; + break; + } } + await delay(3000); + attempts++; + } catch (readError) { + console.error("Read error:", readError); + await delay(2000); + attempts++; } - await delay(2000); - attempts++; - } catch (readError) { - console.error("Read error:", readError); - await delay(2000); - attempts++; } - } - if (!sessionData) { - await cleanUpSession(); - return; - } + if (!sessionData) { + await cleanUpSession(); + return; + } - try { + // Prepare Base64 payload data safely let compressedData = zlib.gzipSync(sessionData); let b64data = compressedData.toString('base64'); - const Sess = await sendButtons(Casper, Casper.user.id, { - title: '', - text: 'CASPER-XD-ULTRA;' + b64data, - footer: `> *ᴘᴏᴡᴇʀᴇᴅ ʙʏ ᴄᴀꜱᴘᴇʀ ᴛᴇᴄʜ*`, - buttons: [ - { - name: 'cta_copy', - buttonParamsJson: JSON.stringify({ - display_text: 'Copy Session', - copy_code: 'CASPER-XD-ULTRA;' + b64data - }) - }, - { - name: 'cta_url', - buttonParamsJson: JSON.stringify({ - display_text: 'Visit Bot Repo', - url: 'https://github.com/Casper-Tech-ke/CASPER-XD-ULTRA' - }) - }, - { - name: 'cta_url', - buttonParamsJson: JSON.stringify({ - display_text: 'Join WaChannel', - url: 'https://whatsapp.com/channel/0029VbCK8vlKwqSSkFkC1l2k' - }) - }, - { - name: 'cta_url', - buttonParamsJson: JSON.stringify({ - display_text: 'Join WaChannel 2', - url: 'https://whatsapp.com/channel/0029Vb6XJQQHrDZi1RzKu90t' - }) - } - ] - }); + + // Parse target user JID correctly to remove potential connection device suffixes + const targetUserJid = Casper.user.id.includes(':') + ? Casper.user.id.split(':')[0] + '@s.whatsapp.net' + : Casper.user.id; + + await sendButtons(Casper, targetUserJid, { + title: '', + text: 'CASPER-XD-ULTRA;' + b64data, + footer: `> *ᴘᴏᴡᴇʀᴇᴅ ʙʏ ᴄᴀꜱᴘᴇʀ ᴛᴇᴄʜ*`, + buttons: [ + { + name: 'cta_copy', + buttonParamsJson: JSON.stringify({ + display_text: 'Copy Session', + copy_code: 'CASPER-XD-ULTRA;' + b64data + }) + }, + { + name: 'cta_url', + buttonParamsJson: JSON.stringify({ + display_text: 'Visit Bot Repo', + url: 'https://github.com/Casper-Tech-ke/CASPER-XD-ULTRA' + }) + }, + { + name: 'cta_url', + buttonParamsJson: JSON.stringify({ + display_text: 'Join WaChannel', + url: 'https://whatsapp.com/channel/0029VbCK8vlKwqSSkFkC1l2k' + }) + }, + { + name: 'cta_url', + buttonParamsJson: JSON.stringify({ + display_text: 'Join WaChannel 2', + url: 'https://whatsapp.com/channel/0029Vb6XJQQHrDZi1RzKu90t' + }) + } + ] + }); sessionSentSuccess = true; - await delay(2000); + await delay(3000); await Casper.ws.close(); } catch (sendError) { - console.error("Error sending session:", sendError); + console.error("Error sending session message:", sendError); } finally { await cleanUpSession(); } - } else if (connection === "close" && !sessionSentSuccess && lastDisconnect && lastDisconnect.error && lastDisconnect.error.output.statusCode != 401) { - await delay(10000); - CASPER_QR_CODE(); + } else if (connection === "close" && !sessionSentSuccess && lastDisconnect && lastDisconnect.error) { + const statusCode = lastDisconnect.error.output ? lastDisconnect.error.output.statusCode : 0; + if (statusCode !== 401) { + await delay(10000); + CASPER_QR_CODE(); + } else { + await cleanUpSession(); + } } }); } catch (err) { - console.error("Main error:", err); - if (!responseSent) { + console.error("Main internal setup error:", err); + if (!responseSent && !res.headersSent) { res.status(500).json({ code: "QR Service is Currently Unavailable" }); responseSent = true; } @@ -293,9 +305,9 @@ router.get('/', async (req, res) => { try { await CASPER_QR_CODE(); } catch (finalError) { - console.error("Final error:", finalError); + console.error("Final tracking stack catch error:", finalError); await cleanUpSession(); - if (!responseSent) { + if (!responseSent && !res.headersSent) { res.status(500).json({ code: "Service Error" }); } }