-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
355 lines (314 loc) · 13.6 KB
/
Copy pathserver.js
File metadata and controls
355 lines (314 loc) · 13.6 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env node
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { URL } = require('url');
const PORT = 3000;
// MIME types for different file extensions
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
// Create HTTP server
const server = http.createServer((req, res) => {
console.log(`${req.method} ${req.url}`);
// Enable CORS for all requests
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
// Handle preflight requests
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// Proxy API requests to Decision Center
if (req.url.startsWith('/api/')) {
proxyRequest(req, res);
return;
}
// Serve static files
let requestedFile = req.url === '/' ? 'deploy-ui.html' : req.url.substring(1);
const extname = String(path.extname(requestedFile)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
// Detect if running as pkg bundled executable
const isPkg = typeof process.pkg !== 'undefined';
// Try multiple paths for cross-platform compatibility
const possiblePaths = [];
if (isPkg) {
// When bundled with pkg, files are in the snapshot filesystem
// pkg puts assets in the same directory as __dirname
possiblePaths.push(
path.join(__dirname, requestedFile),
path.join(__dirname, 'deploy-ui.html'),
// Also try relative to the executable location
path.join(path.dirname(process.execPath), requestedFile),
path.join(path.dirname(process.execPath), 'deploy-ui.html')
);
} else {
// Development mode - use normal file paths
possiblePaths.push(
path.resolve(process.cwd(), requestedFile),
path.resolve(__dirname, requestedFile),
path.resolve(process.cwd(), 'deploy-ui.html'),
path.resolve(__dirname, 'deploy-ui.html')
);
}
let fileFound = false;
let foundPath = '';
for (const tryPath of possiblePaths) {
try {
if (fs.existsSync(tryPath)) {
const stats = fs.statSync(tryPath);
if (stats.isFile()) {
const content = fs.readFileSync(tryPath);
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
fileFound = true;
foundPath = tryPath;
console.log(`Served file from: ${foundPath}`);
break;
}
}
} catch (err) {
// Continue to next path
console.log(`Failed to read: ${tryPath} - ${err.message}`);
continue;
}
}
if (!fileFound) {
console.error('\nFile not found!');
console.error('Requested:', requestedFile);
console.error('Running as pkg:', isPkg);
console.error('Tried paths:');
possiblePaths.forEach(p => {
console.error(` - ${p} (exists: ${fs.existsSync(p)})`);
});
console.error('__dirname:', __dirname);
console.error('process.cwd():', process.cwd());
console.error('process.execPath:', process.execPath);
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(`
<h1>404 - File Not Found</h1>
<p><strong>Requested:</strong> ${requestedFile}</p>
<p><strong>Running as pkg:</strong> ${isPkg}</p>
<p><strong>Tried paths:</strong></p>
<ul>
${possiblePaths.map(p => `<li>${p} <span style="color: ${fs.existsSync(p) ? 'green' : 'red'}">(exists: ${fs.existsSync(p)})</span></li>`).join('')}
</ul>
<hr>
<p><strong>Debug Info:</strong></p>
<ul>
<li>__dirname: ${__dirname}</li>
<li>process.cwd(): ${process.cwd()}</li>
<li>process.execPath: ${process.execPath}</li>
</ul>
`, 'utf-8');
}
});
// Proxy function to forward requests to Decision Center
function proxyRequest(req, res) {
// Extract target URL from query parameter
const urlParams = new URL(req.url, `http://localhost:${PORT}`);
const targetUrl = urlParams.searchParams.get('url');
const username = urlParams.searchParams.get('username') || 'rtsAdmin';
const password = urlParams.searchParams.get('password') || 'rtsAdmin';
if (!targetUrl) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Missing target URL',
errorType: 'MISSING_URL',
userMessage: 'The request is missing the target URL parameter.'
}));
return;
}
console.log(`Proxying to: ${targetUrl}`);
const parsedUrl = new URL(targetUrl);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
const options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: `${parsedUrl.pathname}${parsedUrl.search}`,
method: req.method,
headers: {
'Authorization': 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64'),
'Content-Type': 'application/json'
},
rejectUnauthorized: false
};
const proxyReq = protocol.request(options, (proxyRes) => {
let responseBody = '';
// Collect response data
proxyRes.on('data', (chunk) => {
responseBody += chunk.toString();
});
proxyRes.on('end', () => {
// For error status codes, enhance the error message
if (proxyRes.statusCode >= 400) {
let errorDetails = {
statusCode: proxyRes.statusCode,
error: `Request failed with status ${proxyRes.statusCode}`,
errorType: getErrorType(proxyRes.statusCode),
userMessage: getUserFriendlyMessage(proxyRes.statusCode, parsedUrl),
serverResponse: responseBody,
targetUrl: `${parsedUrl.hostname}:${parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80)}`
};
// Try to parse server response for additional details
try {
const parsedResponse = JSON.parse(responseBody);
if (parsedResponse.message) {
errorDetails.serverMessage = parsedResponse.message;
}
if (parsedResponse.error) {
errorDetails.serverError = parsedResponse.error;
}
} catch (e) {
// Response is not JSON, keep as is
}
res.writeHead(proxyRes.statusCode, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(JSON.stringify(errorDetails));
} else {
// Success response - forward as is
res.writeHead(proxyRes.statusCode, {
'Content-Type': proxyRes.headers['content-type'] || 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(responseBody);
}
});
});
proxyReq.on('error', (error) => {
console.error('Proxy error:', error);
console.error('Error code:', error.code);
console.error('Error message:', error.message);
let errorDetails = {
error: error.message,
errorType: getNetworkErrorType(error),
userMessage: getNetworkErrorMessage(error, parsedUrl),
targetUrl: `${parsedUrl.hostname}:${parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80)}`,
errorCode: error.code
};
console.error('Sending error details:', JSON.stringify(errorDetails, null, 2));
res.writeHead(500, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(JSON.stringify(errorDetails));
});
// Forward request body if present
if (req.method === 'POST' || req.method === 'PUT') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
proxyReq.write(body);
proxyReq.end();
});
} else {
proxyReq.end();
}
}
// Helper function to categorize HTTP error types
function getErrorType(statusCode) {
if (statusCode === 401) return 'AUTHENTICATION_FAILED';
if (statusCode === 403) return 'AUTHORIZATION_FAILED';
if (statusCode === 404) return 'RESOURCE_NOT_FOUND';
if (statusCode === 500) return 'SERVER_ERROR';
if (statusCode === 502) return 'BAD_GATEWAY';
if (statusCode === 503) return 'SERVICE_UNAVAILABLE';
if (statusCode === 504) return 'GATEWAY_TIMEOUT';
if (statusCode >= 400 && statusCode < 500) return 'CLIENT_ERROR';
if (statusCode >= 500) return 'SERVER_ERROR';
return 'UNKNOWN_ERROR';
}
// Helper function to provide user-friendly error messages
function getUserFriendlyMessage(statusCode, parsedUrl) {
const serverAddress = `${parsedUrl.hostname}:${parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80)}`;
switch (statusCode) {
case 401:
return `Authentication failed. Please check your username and password for the Decision Center server at ${serverAddress}.`;
case 403:
return `Access denied. Your account does not have permission to access this resource on ${serverAddress}.`;
case 404:
return `The requested resource was not found on the Decision Center server at ${serverAddress}. The server may be misconfigured or the resource may have been deleted.`;
case 500:
return `The Decision Center server at ${serverAddress} encountered an internal error. Please check the server logs or contact your administrator.`;
case 502:
return `Bad Gateway: Unable to get a valid response from the Decision Center server at ${serverAddress}. The server may be down or unreachable.`;
case 503:
return `The Decision Center server at ${serverAddress} is currently unavailable. It may be down for maintenance or overloaded. Please try again later.`;
case 504:
return `Gateway Timeout: The Decision Center server at ${serverAddress} took too long to respond. The server may be slow or unresponsive.`;
default:
if (statusCode >= 400 && statusCode < 500) {
return `The request to ${serverAddress} was invalid (HTTP ${statusCode}). Please check your input and try again.`;
}
if (statusCode >= 500) {
return `The Decision Center server at ${serverAddress} encountered an error (HTTP ${statusCode}). Please contact your administrator.`;
}
return `Request failed with status code ${statusCode}.`;
}
}
// Helper function to categorize network error types
function getNetworkErrorType(error) {
if (error.code === 'ECONNREFUSED') return 'CONNECTION_REFUSED';
if (error.code === 'ENOTFOUND') return 'HOST_NOT_FOUND';
if (error.code === 'ETIMEDOUT') return 'CONNECTION_TIMEOUT';
if (error.code === 'ECONNRESET') return 'CONNECTION_RESET';
if (error.code === 'EHOSTUNREACH') return 'HOST_UNREACHABLE';
if (error.code === 'ENETUNREACH') return 'NETWORK_UNREACHABLE';
return 'NETWORK_ERROR';
}
// Helper function to provide user-friendly network error messages
function getNetworkErrorMessage(error, parsedUrl) {
const serverAddress = `${parsedUrl.hostname}:${parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80)}`;
const protocol = parsedUrl.protocol.replace(':', '').toUpperCase();
switch (error.code) {
case 'ECONNREFUSED':
return `Unable to connect to the Decision Center server at ${serverAddress}. The server may be down or not running.`;
case 'ENOTFOUND':
return `Cannot find the Decision Center server at ${serverAddress}. Check hostname spelling and network connection.`;
case 'ETIMEDOUT':
return `Connection to the Decision Center server at ${serverAddress} timed out. Server may be slow or unreachable.`;
case 'ECONNRESET':
// ECONNRESET often happens when using wrong protocol (HTTP vs HTTPS)
const isLikelyHttps = parsedUrl.port === 443 || parsedUrl.port === '443' ||
serverAddress.includes(':443') || serverAddress.includes(':9443') ||
serverAddress.includes(':41443');
const isUsingHttp = parsedUrl.protocol === 'http:';
if (isUsingHttp && isLikelyHttps) {
return `Connection reset by the Decision Center server at ${serverAddress}. PROTOCOL MISMATCH DETECTED: You are using ${protocol} but the server requires HTTPS. Change the Protocol dropdown to "HTTPS" and try again.`;
}
return `Connection reset by the Decision Center server at ${serverAddress}. Check protocol (HTTP vs HTTPS) or verify server is accepting connections.`;
case 'EHOSTUNREACH':
return `The Decision Center server at ${serverAddress} is unreachable. Please check your network connection and verify the server address.`;
case 'ENETUNREACH':
return `Network is unreachable. Please check your internet connection and try again.`;
default:
return `Failed to connect to the Decision Center server at ${serverAddress}. Error: ${error.message}`;
}
}
server.listen(PORT, () => {
console.log(`\n========================================`);
console.log(`IBM Decision Center Deployment UI`);
console.log(`========================================`);
console.log(`Server running at http://localhost:${PORT}/`);
console.log(`\nOpen your browser and navigate to:`);
console.log(` http://localhost:${PORT}/`);
console.log(`\nPress Ctrl+C to stop the server`);
console.log(`========================================\n`);
});
// Made with Bob