arabdullah commited on
Commit
77dfcf8
·
verified ·
1 Parent(s): f18d924

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +84 -28
index.js CHANGED
@@ -1,70 +1,64 @@
1
  const express = require('express');
2
  const fs = require('fs');
3
  const path = require('path');
4
- const app = express();
 
 
5
 
 
6
  app.use(express.json());
7
 
 
 
 
8
  function generateApiKey() {
9
  return Math.random().toString(36).substr(2, 16);
10
  }
11
 
12
  // Function to validate IP address format and ensure it's not a private or reserved IP
13
  function isValidIp(ip) {
14
- // Regular expression to validate IPv4 format
15
  const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
 
16
 
17
- if (!ipv4Regex.test(ip)) {
18
- return false; // Invalid IP format
19
- }
20
-
21
- // Split the IP into octets
22
  const octets = ip.split('.').map(Number);
23
-
24
- // Check for private IP ranges
25
- const isPrivateIp =
26
  (octets[0] === 10) ||
27
  (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
28
  (octets[0] === 192 && octets[1] === 168) ||
29
- (ip === '127.0.0.1'); // localhost
30
-
31
- return !isPrivateIp; // Return true if IP is not private
32
  }
33
 
34
- app.get('/checkState', (req, res) => {
 
35
  const { ip } = req.query;
36
 
37
  if (ip && isValidIp(ip)) {
38
- const sessionDir = path.join(__dirname, 'db', ip);
39
- const sessionFile = path.join(sessionDir, 'info.json');
40
 
41
  let apiKey;
42
 
43
- // Check if the session file exists
44
  if (fs.existsSync(sessionFile)) {
45
- // Read existing API key from file
46
  const sessionData = JSON.parse(fs.readFileSync(sessionFile, 'utf8'));
47
  apiKey = sessionData.apiKey;
48
  } else {
49
- // Generate a new API key
50
  apiKey = generateApiKey();
51
 
52
- // Create directory for user session
53
  if (!fs.existsSync(sessionDir)) {
54
  fs.mkdirSync(sessionDir, { recursive: true });
55
  }
56
 
57
- // Save API key and IP in info.json
58
  const sessionData = { ip, apiKey };
59
  fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2));
 
 
60
  }
61
 
62
- // Set cookie and respond with API key
63
  res.cookie('apiKey', apiKey, {
64
- maxAge: 365 * 24 * 60 * 60 * 1000,
65
- httpOnly: false,
66
- sameSite: 'None',
67
- secure: true // Ensure this is set for HTTPS
68
  });
69
 
70
  res.status(200).json({
@@ -77,10 +71,72 @@ app.get('/checkState', (req, res) => {
77
  }
78
  });
79
 
80
- app.get('/', (req, res) => {
81
- res.send('Hello World');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  });
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  const PORT = 7860;
85
  app.listen(PORT, () => {
86
  console.log(`Server is running on port ${PORT}`);
 
1
  const express = require('express');
2
  const fs = require('fs');
3
  const path = require('path');
4
+ const qr = require('qr-image');
5
+ const makeWASocket = require('@whiskeysockets/baileys').default;
6
+ const Boom = require('@hapi/boom');
7
 
8
+ const app = express();
9
  app.use(express.json());
10
 
11
+ const sessionDir = path.join(__dirname, 'sessions');
12
+
13
+ // Function to generate API key
14
  function generateApiKey() {
15
  return Math.random().toString(36).substr(2, 16);
16
  }
17
 
18
  // Function to validate IP address format and ensure it's not a private or reserved IP
19
  function isValidIp(ip) {
 
20
  const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
21
+ if (!ipv4Regex.test(ip)) return false;
22
 
 
 
 
 
 
23
  const octets = ip.split('.').map(Number);
24
+ return !(
 
 
25
  (octets[0] === 10) ||
26
  (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
27
  (octets[0] === 192 && octets[1] === 168) ||
28
+ (ip === '127.0.0.1')
29
+ );
 
30
  }
31
 
32
+ // Handle checkState request
33
+ app.get('/checkState', async (req, res) => {
34
  const { ip } = req.query;
35
 
36
  if (ip && isValidIp(ip)) {
37
+ const sessionFile = path.join(sessionDir, `${ip}.json`);
 
38
 
39
  let apiKey;
40
 
 
41
  if (fs.existsSync(sessionFile)) {
 
42
  const sessionData = JSON.parse(fs.readFileSync(sessionFile, 'utf8'));
43
  apiKey = sessionData.apiKey;
44
  } else {
 
45
  apiKey = generateApiKey();
46
 
 
47
  if (!fs.existsSync(sessionDir)) {
48
  fs.mkdirSync(sessionDir, { recursive: true });
49
  }
50
 
 
51
  const sessionData = { ip, apiKey };
52
  fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2));
53
+
54
+ connectToWhatsApp(apiKey, ip); // Start WhatsApp connection
55
  }
56
 
 
57
  res.cookie('apiKey', apiKey, {
58
+ maxAge: 365 * 24 * 60 * 60 * 1000,
59
+ httpOnly: false,
60
+ sameSite: 'None',
61
+ secure: true
62
  });
63
 
64
  res.status(200).json({
 
71
  }
72
  });
73
 
74
+ // Serve QR code for login
75
+ app.get('/qrCode', (req, res) => {
76
+ const { apiKey } = req.query;
77
+
78
+ if (apiKey) {
79
+ const qrData = `https://example.com/login?apiKey=${apiKey}`; // Replace with your actual URL
80
+ const qrImage = qr.imageSync(qrData, { type: 'svg' });
81
+ res.setHeader('Content-Type', 'image/svg+xml');
82
+ res.send(qrImage);
83
+ } else {
84
+ res.status(400).send('API key is required');
85
+ }
86
+ });
87
+
88
+ // Handle user credentials storage
89
+ app.post('/storeCredentials', (req, res) => {
90
+ const { apiKey, credentials } = req.body;
91
+
92
+ if (!apiKey || !credentials) {
93
+ return res.status(400).json({ message: 'API key and credentials are required' });
94
+ }
95
+
96
+ const credentialsDir = path.join(sessionDir, apiKey);
97
+ const credentialsFile = path.join(credentialsDir, 'creds.json');
98
+
99
+ if (!fs.existsSync(credentialsDir)) {
100
+ fs.mkdirSync(credentialsDir, { recursive: true });
101
+ }
102
+
103
+ fs.writeFileSync(credentialsFile, JSON.stringify(credentials, null, 2));
104
+
105
+ res.status(200).json({ message: 'Credentials stored successfully' });
106
  });
107
 
108
+ // Serve login page
109
+ app.use(express.static(path.join(__dirname, 'public')));
110
+
111
+ async function connectToWhatsApp(apiKey, ip) {
112
+ const sock = makeWASocket({
113
+ printQRInTerminal: true
114
+ });
115
+
116
+ sock.ev.on('connection.update', (update) => {
117
+ const { connection, lastDisconnect } = update;
118
+ if (connection === 'close') {
119
+ const shouldReconnect = (lastDisconnect.error instanceof Boom) ? lastDisconnect.error.output.statusCode !== DisconnectReason.loggedOut : true;
120
+ console.log('Connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect);
121
+ if (shouldReconnect) {
122
+ connectToWhatsApp(apiKey, ip);
123
+ }
124
+ } else if (connection === 'open') {
125
+ console.log('Opened connection');
126
+ }
127
+ });
128
+
129
+ sock.ev.on('messages.upsert', async m => {
130
+ console.log(JSON.stringify(m, undefined, 2));
131
+ console.log('Replying to', m.messages[0].key.remoteJid);
132
+ await sock.sendMessage(m.messages[0].key.remoteJid, { text: 'Hello there!' });
133
+ });
134
+
135
+ // Save session to file
136
+ const sessionFile = path.join(sessionDir, `${ip}.json`);
137
+ fs.writeFileSync(sessionFile, JSON.stringify({ apiKey, ip, session: sock.state }, null, 2));
138
+ }
139
+
140
  const PORT = 7860;
141
  app.listen(PORT, () => {
142
  console.log(`Server is running on port ${PORT}`);