-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
167 lines (153 loc) · 5.4 KB
/
Copy pathserver.js
File metadata and controls
167 lines (153 loc) · 5.4 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
};
const server = http.createServer((req, res) => {
// Normalize URL path to prevent path traversal vulnerability
let safePath = req.url.split('?')[0];
// Intercept API routes and proxy to the deployed Vercel instance to bypass local browser CORS policy
if (safePath === '/api/health' && req.method === 'GET') {
if (process.env.GOOGLE_API_KEY) {
try {
const handler = require('./api/health.js');
const mockReq = { headers: req.headers };
const mockRes = {
statusCode: 200,
setHeader: function(name, val) {
res.setHeader(name, val);
},
status: function(code) {
this.statusCode = code;
return this;
},
json: function(data) {
res.writeHead(this.statusCode, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
return this;
}
};
handler(mockReq, mockRes);
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Local health check failed', details: err.message }));
}
} else {
fetch('https://portfolio-five-theta-ftdhmviqc3.vercel.app/api/health')
.then(proxyRes => proxyRes.json())
.then(data => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
})
.catch(err => {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Proxy unreachable', details: err.message }));
});
}
return;
}
if (safePath === '/api/chat' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
if (process.env.GOOGLE_API_KEY) {
console.log('Running api/chat.js locally since GOOGLE_API_KEY is set.');
try {
delete require.cache[require.resolve('./api/chat.js')];
const handler = require('./api/chat.js');
const parsedBody = body ? JSON.parse(body) : {};
const mockReq = {
method: 'POST',
body: parsedBody,
headers: req.headers,
};
const mockRes = {
statusCode: 200,
setHeader: function(name, val) {
res.setHeader(name, val);
},
status: function(code) {
this.statusCode = code;
return this;
},
json: function(data) {
res.writeHead(this.statusCode, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
return this;
},
end: function() {
res.writeHead(this.statusCode);
res.end();
return this;
}
};
await handler(mockReq, mockRes);
} catch (err) {
console.error('Error executing local chat handler:', err);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Local execution failed', details: err.message }));
}
} else {
fetch('https://portfolio-five-theta-ftdhmviqc3.vercel.app/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body
})
.then(proxyRes => {
return proxyRes.json().then(data => ({ status: proxyRes.status, data }));
})
.then(({ status, data }) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
})
.catch(err => {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Proxy unreachable', details: err.message }));
});
}
});
return;
}
if (safePath === '/') {
safePath = '/index.html';
}
const filePath = path.join(__dirname, safePath);
// Basic security check to ensure we only serve files within this workspace
if (!filePath.startsWith(__dirname)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 File Not Found');
} else {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(`Internal Server Error: ${error.code}`);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, () => {
console.log(`Portfolio local server is running at http://localhost:${PORT}/`);
console.log('Press Ctrl+C to stop the server.');
});