topnic-https 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "topnic-https",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
4
4
  "main": "./src/main/index.js",
5
5
  "type": "commonjs",
6
6
  "scripts": {
@@ -96,6 +96,7 @@
96
96
  "https": "^1.0.0",
97
97
  "localtunnel": "^2.0.2",
98
98
  "nanoid": "^5.0.8",
99
+ "net": "^1.0.2",
99
100
  "ngrok": "^5.0.0-beta.2",
100
101
  "os": "^0.1.2",
101
102
  "path": "^0.12.7",
package/readme CHANGED
@@ -25,7 +25,7 @@ $ npm install -g topnic-https
25
25
 
26
26
  ## أمثلة
27
27
  ```bash
28
- $ httpst share -p 3000 -d 60 # مشاركة لمدة 60 دقيقة
28
+ $ httpst share -p 3000 # مشاركة لمدة 60 دقيقة
29
29
  $ httpst run #تشغيل الخادم
30
30
  $ httpst stop #إيقاف الخادم
31
31
  $ httpst restart #إعادة تشغيل الخادم
@@ -2,7 +2,7 @@ const http = require('http');
2
2
  const WebSocket = require('ws');
3
3
  const { nanoid } = require('nanoid/non-secure');
4
4
  const os = require('os');
5
- const crypto = require('crypto');
5
+ const net = require('net');
6
6
 
7
7
  class DirectServer {
8
8
  constructor() {
@@ -21,165 +21,154 @@ class DirectServer {
21
21
  return 'localhost';
22
22
  }
23
23
 
24
+ async isPortAvailable(port) {
25
+ return new Promise((resolve) => {
26
+ const tester = net.createServer()
27
+ .once('error', () => resolve(false))
28
+ .once('listening', () => {
29
+ tester.once('close', () => resolve(true)).close();
30
+ })
31
+ .listen(port);
32
+ });
33
+ }
34
+
24
35
  async start(port = 3500) {
36
+ if (!(await this.isPortAvailable(port))) {
37
+ console.log(`المنفذ ${port} مشغول، جاري المحاولة على منفذ آخر...`);
38
+ port = await this.findAvailablePort(3501);
39
+ }
40
+
25
41
  return new Promise((resolve) => {
26
42
  this.server.listen(port, '0.0.0.0', () => {
27
43
  console.log(`🚀 خادم المشاركة يعمل على المنفذ ${port}`);
28
44
  console.log(`📡 عنوان IP: ${this.publicIp}:${port}`);
29
- resolve();
45
+ resolve(port);
30
46
  });
31
47
  });
32
48
  }
33
49
 
34
- generateAccessCode() {
35
- // إنشاء كود وصول من 6 أرقام
36
- return Math.floor(100000 + Math.random() * 900000).toString();
50
+ async findAvailablePort(startPort) {
51
+ let port = startPort;
52
+ while (!(await this.isPortAvailable(port))) {
53
+ port++;
54
+ }
55
+ return port;
56
+ }
57
+
58
+ async verifyTargetPort(port) {
59
+ try {
60
+ const response = await new Promise((resolve, reject) => {
61
+ const req = http.request({
62
+ hostname: 'localhost',
63
+ port: port,
64
+ path: '/',
65
+ method: 'GET',
66
+ timeout: 2000
67
+ }, resolve);
68
+
69
+ req.on('error', reject);
70
+ req.end();
71
+ });
72
+ return true;
73
+ } catch (error) {
74
+ return false;
75
+ }
37
76
  }
38
77
 
39
78
  createConnection(targetPort) {
40
79
  const id = nanoid(6);
41
- const accessCode = this.generateAccessCode();
42
-
43
80
  this.connections.set(id, {
44
81
  port: targetPort,
45
82
  createdAt: Date.now(),
46
- visitors: 0,
47
- accessCode
83
+ visitors: 0
48
84
  });
49
-
50
- return {
51
- id,
52
- accessCode
53
- };
85
+ return id;
54
86
  }
55
87
 
56
88
  async handleRequest(req, res) {
57
- res.setHeader('Access-Control-Allow-Origin', '*');
58
-
59
- const connectionId = req.url.split('/')[1];
60
- const connection = this.connections.get(connectionId);
61
-
62
- if (!connection) {
63
- res.writeHead(404);
64
- res.end('رابط المشاركة غير صالح');
65
- return;
66
- }
67
-
68
- // التحقق من صفحة تسجيل الدخول
69
- if (req.url === `/${connectionId}/login`) {
70
- const loginPage = this.generateLoginPage(connectionId);
71
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
72
- res.end(loginPage);
73
- return;
74
- }
75
-
76
- // التحقق من كود الوصول
77
- const providedCode = req.headers['x-access-code'];
78
- if (providedCode !== connection.accessCode) {
79
- res.writeHead(401);
80
- res.end(JSON.stringify({ error: 'كود الوصول غير صحيح' }));
81
- return;
82
- }
89
+ try {
90
+ const urlParts = req.url.split('/');
91
+ const connectionId = urlParts[1];
92
+ const connection = this.connections.get(connectionId);
93
+
94
+ // إضافة CORS headers
95
+ res.setHeader('Access-Control-Allow-Origin', '*');
96
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
97
+ res.setHeader('Access-Control-Allow-Headers', '*');
98
+
99
+ // معالجة طلبات OPTIONS
100
+ if (req.method === 'OPTIONS') {
101
+ res.writeHead(200);
102
+ res.end();
103
+ return;
104
+ }
83
105
 
84
- // إعادة توجيه الطلب إلى المنفذ المحلي
85
- const options = {
86
- hostname: 'localhost',
87
- port: connection.port,
88
- path: req.url.replace(`/${connectionId}`, '') || '/',
89
- method: req.method,
90
- headers: {
91
- ...req.headers,
92
- host: `localhost:${connection.port}`
106
+ if (!connection) {
107
+ res.writeHead(404);
108
+ res.end('رابط المشاركة غير صالح');
109
+ return;
93
110
  }
94
- };
95
111
 
96
- connection.visitors++;
112
+ // التحقق من أن الخدمة المحلية تعمل
113
+ if (!(await this.verifyTargetPort(connection.port))) {
114
+ res.writeHead(502);
115
+ res.end('الخدمة المحلية غير متاحة');
116
+ return;
117
+ }
97
118
 
98
- const proxyReq = http.request(options, (proxyRes) => {
99
- res.writeHead(proxyRes.statusCode, proxyRes.headers);
100
- proxyRes.pipe(res);
101
- });
119
+ // إعادة بناء المسار الأصلي
120
+ const originalPath = urlParts.length > 2 ? '/' + urlParts.slice(2).join('/') : '/';
121
+
122
+ // إضافة معلومات التوجيه
123
+ const options = {
124
+ hostname: 'localhost',
125
+ port: connection.port,
126
+ path: originalPath,
127
+ method: req.method,
128
+ headers: {
129
+ ...req.headers,
130
+ 'X-Forwarded-Host': req.headers.host,
131
+ 'X-Forwarded-Proto': 'http',
132
+ 'X-Forwarded-For': req.socket.remoteAddress,
133
+ host: `localhost:${connection.port}`
134
+ }
135
+ };
136
+
137
+ // إنشاء طلب التوجيه
138
+ const proxyReq = http.request(options, (proxyRes) => {
139
+ // نسخ headers الاستجابة
140
+ Object.keys(proxyRes.headers).forEach(key => {
141
+ res.setHeader(key, proxyRes.headers[key]);
142
+ });
143
+
144
+ res.writeHead(proxyRes.statusCode);
145
+ proxyRes.pipe(res);
146
+ });
102
147
 
103
- proxyReq.on('error', (error) => {
104
- console.error('خطأ في التوجيه:', error);
105
- res.writeHead(502);
106
- res.end('خطأ في الاتصال بالتطبيق المحلي');
107
- });
148
+ // معالجة أخطاء التوجيه
149
+ proxyReq.on('error', (error) => {
150
+ console.error('خطأ في التوجيه:', error);
151
+ if (!res.headersSent) {
152
+ res.writeHead(502);
153
+ res.end('خطأ في الاتصال بالتطبيق المحلي');
154
+ }
155
+ });
108
156
 
109
- req.pipe(proxyReq);
110
- }
157
+ // إرسال البيانات إلى التطبيق المحلي
158
+ if (!req.readableEnded) {
159
+ req.pipe(proxyReq);
160
+ } else {
161
+ proxyReq.end();
162
+ }
111
163
 
112
- generateLoginPage(connectionId) {
113
- return `
114
- <!DOCTYPE html>
115
- <html dir="rtl">
116
- <head>
117
- <meta charset="UTF-8">
118
- <title>صفحة الدخول</title>
119
- <style>
120
- body {
121
- font-family: Arial, sans-serif;
122
- display: flex;
123
- justify-content: center;
124
- align-items: center;
125
- height: 100vh;
126
- margin: 0;
127
- background-color: #f5f5f5;
128
- }
129
- .login-container {
130
- background: white;
131
- padding: 2rem;
132
- border-radius: 8px;
133
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
134
- text-align: center;
135
- }
136
- input {
137
- padding: 8px;
138
- margin: 10px 0;
139
- width: 200px;
140
- text-align: center;
141
- font-size: 1.2rem;
142
- }
143
- button {
144
- padding: 10px 20px;
145
- background-color: #007bff;
146
- color: white;
147
- border: none;
148
- border-radius: 4px;
149
- cursor: pointer;
150
- }
151
- button:hover {
152
- background-color: #0056b3;
153
- }
154
- </style>
155
- </head>
156
- <body>
157
- <div class="login-container">
158
- <h2>أدخل كود الوصول</h2>
159
- <input type="text" id="accessCode" placeholder="######" maxlength="6">
160
- <br>
161
- <button onclick="submitCode()">دخول</button>
162
- </div>
163
- <script>
164
- async function submitCode() {
165
- const code = document.getElementById('accessCode').value;
166
- const response = await fetch('/${connectionId}', {
167
- headers: {
168
- 'X-Access-Code': code
169
- }
170
- });
171
-
172
- if (response.ok) {
173
- localStorage.setItem('accessCode', code);
174
- window.location.href = '/${connectionId}';
175
- } else {
176
- alert('كود الوصول غير صحيح');
177
- }
178
- }
179
- </script>
180
- </body>
181
- </html>
182
- `;
164
+ connection.visitors++;
165
+ } catch (error) {
166
+ console.error('خطأ في معالجة الطلب:', error);
167
+ if (!res.headersSent) {
168
+ res.writeHead(500);
169
+ res.end('خطأ داخلي في الخادم');
170
+ }
171
+ }
183
172
  }
184
173
 
185
174
  removeConnection(id) {