-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebServerSecurity.js
More file actions
282 lines (257 loc) Β· 8.99 KB
/
Copy pathWebServerSecurity.js
File metadata and controls
282 lines (257 loc) Β· 8.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const crypto = require('crypto');
/**
* Generic Web Server Security System
* Provides token-based authentication middleware for any Express web server
* One-time setup, automatic protection for all routes
*/
class WebServerSecurity {
constructor(botInstance = 'bot1') {
this.botInstance = botInstance;
this.securityToken = this.generateSecurityToken();
this.excludedPaths = ['/static', '/assets', '/public']; // Static assets don't need tokens
console.log(`[${this.botInstance}] π WebServerSecurity initialized with token authentication`);
}
/**
* Generate a cryptographically secure token
*/
generateSecurityToken() {
const token = crypto.randomBytes(32).toString('hex');
console.log(`[${this.botInstance}] π Generated security token (${token.length} chars)`);
return token;
}
/**
* Express middleware for token validation
* Apply this to your Express app to protect all routes automatically
*/
getMiddleware() {
return (req, res, next) => {
// Skip token validation for excluded paths (static assets, etc.)
if (this.isPathExcluded(req.path)) {
return next();
}
// Check for token in URL parameter or cookie
const providedToken = req.query.token || this.getTokenFromCookies(req);
const isValidToken = providedToken === this.securityToken;
if (!isValidToken) {
console.log(`[${this.botInstance}] π« Unauthorized access: ${req.ip} -> ${req.path} (${providedToken ? 'invalid token' : 'missing token'})`);
return res.status(403).send(this.generateSecurityErrorPage());
}
console.log(`[${this.botInstance}] β
Authorized access: ${req.ip} -> ${req.path}`);
next();
};
}
/**
* Check if a path should be excluded from token validation
*/
isPathExcluded(path) {
return this.excludedPaths.some(excluded => path.startsWith(excluded));
}
/**
* Generate secure URL with token for any path
* Use this in your HTML templates to create secure links
*/
secureUrl(path, queryParams = {}) {
queryParams.token = this.securityToken;
const params = new URLSearchParams(queryParams).toString();
return `${path}?${params}`;
}
/**
* Generate secure external URL (for ngrok public URLs)
* Use this when providing URLs to Telegram bot buttons
*/
secureExternalUrl(baseUrl, path = '/', queryParams = {}) {
queryParams.token = this.securityToken;
const params = new URLSearchParams(queryParams).toString();
return `${baseUrl}${path}?${params}`;
}
/**
* Get current security token (for external systems)
*/
getToken() {
return this.securityToken;
}
/**
* Regenerate security token (invalidates all existing links)
*/
regenerateToken() {
const oldToken = this.securityToken;
this.securityToken = this.generateSecurityToken();
console.log(`[${this.botInstance}] π Security token regenerated (old: ${oldToken.slice(0, 8)}..., new: ${this.securityToken.slice(0, 8)}...)`);
return this.securityToken;
}
/**
* Extract auth_token from request cookies
* Simple cookie parser that doesn't require external dependencies
*/
getTokenFromCookies(req) {
const cookieHeader = req.headers.cookie;
if (!cookieHeader) return null;
const cookies = cookieHeader.split(';').reduce((acc, cookie) => {
const [name, value] = cookie.trim().split('=');
acc[name] = value;
return acc;
}, {});
return cookies.auth_token || null;
}
/**
* Add paths to exclude from token validation
*/
excludePaths(...paths) {
this.excludedPaths.push(...paths);
console.log(`[${this.botInstance}] β Added excluded paths: ${paths.join(', ')}`);
}
/**
* Generate professional security error page
*/
generateSecurityErrorPage() {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>π Access Denied - Secure Web Server</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
background: white;
border-radius: 16px;
padding: 40px;
text-align: center;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
max-width: 600px;
width: 100%;
}
.security-icon {
font-size: 5rem;
margin-bottom: 24px;
display: block;
}
.error-title {
color: #dc3545;
font-size: 2rem;
font-weight: 700;
margin-bottom: 16px;
}
.error-subtitle {
color: #6c757d;
font-size: 1.1rem;
margin-bottom: 32px;
}
.security-notice {
background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
padding: 24px;
border-radius: 12px;
border-left: 4px solid #ffc107;
text-align: left;
margin-bottom: 32px;
}
.security-notice h3 {
color: #856404;
font-size: 1.2rem;
margin-bottom: 12px;
}
.security-notice p {
color: #664d03;
line-height: 1.6;
margin-bottom: 8px;
}
.instructions {
color: #495057;
line-height: 1.6;
font-size: 1rem;
}
.code {
background: #f8f9fa;
padding: 4px 8px;
border-radius: 4px;
font-family: 'Monaco', 'Courier New', monospace;
color: #e83e8c;
}
.footer {
margin-top: 32px;
color: #6c757d;
font-size: 0.9rem;
}
@media (max-width: 768px) {
.container { padding: 24px; }
.error-title { font-size: 1.5rem; }
.security-icon { font-size: 3.5rem; }
}
</style>
</head>
<body>
<div class="container">
<span class="security-icon">π</span>
<h1 class="error-title">Access Denied</h1>
<p class="error-subtitle">This page requires secure authentication</p>
<div class="security-notice">
<h3>π‘οΈ Security Protection Active</h3>
<p>This web server uses token-based authentication to protect sensitive content.</p>
<p>All requests must include a valid security token to access protected resources.</p>
<p><strong>Unauthorized access attempts are logged and monitored.</strong></p>
</div>
<div class="instructions">
<p>If you have access authorization:</p>
<ol style="text-align: left; margin: 16px 0; padding-left: 20px;">
<li>Contact the system administrator for authorized access</li>
<li>Use official channels to obtain valid authentication tokens</li>
<li>Ensure you have proper credentials before accessing resources</li>
</ol>
</div>
<div class="footer">
<p>π Secure Web Application</p>
</div>
</div>
</body>
</html>`;
}
/**
* Generate a lightweight error response (for API endpoints)
*/
generateApiErrorResponse() {
return {
error: 'Access Denied',
message: 'Valid security token required',
code: 403,
timestamp: new Date().toISOString()
};
}
/**
* Utility method to create secure HTML links
* Use this in your templates: ${security.link('/path', 'Link Text', {param: 'value'})}
*/
link(path, text, queryParams = {}, className = '') {
const url = this.secureUrl(path, queryParams);
const classAttr = className ? ` class="${className}"` : '';
return `<a href="${url}"${classAttr}>${text}</a>`;
}
/**
* Utility method for secure form actions
*/
formAction(action, queryParams = {}) {
return this.secureUrl(action, queryParams);
}
/**
* Get security stats/info
*/
getSecurityInfo() {
return {
botInstance: this.botInstance,
tokenLength: this.securityToken.length,
tokenPreview: this.securityToken.slice(0, 8) + '...',
excludedPaths: [...this.excludedPaths],
active: true
};
}
}
module.exports = WebServerSecurity;