-
-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathserve-proxy.js
More file actions
405 lines (348 loc) · 13.8 KB
/
serve-proxy.js
File metadata and controls
405 lines (348 loc) · 13.8 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env node
/* eslint-env node */
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const httpProxy = require('http-proxy');
const ACCOUNT_PROD = 'https://account.phcode.dev';
const ACCOUNT_STAGING = 'https://account-stage.phcode.dev';
const ACCOUNT_DEV = 'http://localhost:5000';
// Account server configuration - switch between local and production
let accountServer = ACCOUNT_PROD; // Production
// Set to local development server if --localAccount flag is provided
// Default configuration
let config = {
port: 8000,
host: '0.0.0.0',
root: process.cwd(),
cache: false,
cors: true,
silent: false
};
// Parse command line arguments
function parseArgs() {
const args = process.argv.slice(2);
let hasLocalAccount = false;
let hasStagingAccount = false;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-p' && args[i + 1]) {
config.port = parseInt(args[i + 1]);
i++;
} else if (arg === '-a' && args[i + 1]) {
config.host = args[i + 1];
i++;
} else if (arg === '-c-1') {
config.cache = false;
} else if (arg === '-c' && args[i + 1]) {
config.cache = parseInt(args[i + 1]) > 0;
i++;
} else if (arg === '--cors') {
config.cors = true;
} else if (arg === '-S' || arg === '--silent') {
config.silent = true;
} else if (arg === '--log-ip') {
config.logIp = true;
} else if (arg === '--localAccount') {
hasLocalAccount = true;
accountServer = ACCOUNT_DEV;
} else if (arg === '--stagingAccount') {
hasStagingAccount = true;
accountServer = ACCOUNT_STAGING;
} else if (!arg.startsWith('-')) {
config.root = path.resolve(arg);
}
}
// Check for mutually exclusive flags
if (hasLocalAccount && hasStagingAccount) {
console.error('Error: --localAccount and --stagingAccount cannot be used together');
process.exit(1);
}
}
// Create proxy server
const proxy = httpProxy.createProxyServer({
changeOrigin: true,
secure: true,
followRedirects: true
});
// Handle proxy errors
proxy.on('error', (err, req, res) => {
console.error('Proxy Error:', err.message);
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Proxy Error', message: err.message }));
}
});
// Modify proxy request headers
proxy.on('proxyReq', (proxyReq, req) => {
// Transform localhost:8000 to appear as phcode.dev domain
const originalReferer = req.headers.referer;
const originalOrigin = req.headers.origin;
// Set target host
const accountHost = new URL(accountServer).hostname;
proxyReq.setHeader('Host', accountHost);
// Transform referer from localhost:8000 to phcode.dev
if (originalReferer && originalReferer.includes('localhost:8000')) {
const newReferer = originalReferer.replace(/http:\/\/localhost:8000/g, 'https://phcode.dev');
proxyReq.setHeader('Referer', newReferer);
} else if (!originalReferer) {
proxyReq.setHeader('Referer', 'https://phcode.dev/');
}
// Transform origin from localhost:8000 to phcode.dev
if (originalOrigin && originalOrigin.includes('localhost:8000')) {
const newOrigin = originalOrigin.replace(/http:\/\/localhost:8000/g, 'https://phcode.dev');
proxyReq.setHeader('Origin', newOrigin);
}
// Ensure HTTPS scheme
proxyReq.setHeader('X-Forwarded-Proto', 'https');
proxyReq.setHeader('X-Forwarded-For', req.connection.remoteAddress);
});
// Modify proxy response headers
proxy.on('proxyRes', (proxyRes, req, res) => {
// Pass through cache control and other security headers
// But translate any domain references back to localhost for the browser
const setCookieHeader = proxyRes.headers['set-cookie'];
if (setCookieHeader) {
// Transform any phcode.dev domain cookies back to localhost
const modifiedCookies = setCookieHeader.map(cookie => {
return cookie.replace(/domain=\.?phcode\.dev/gi, 'domain=localhost');
});
proxyRes.headers['set-cookie'] = modifiedCookies;
}
// Ensure CORS headers if needed
if (config.cors) {
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
proxyRes.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control';
}
});
// Get MIME type based on file extension
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.htm': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.eot': 'application/vnd.ms-fontobject'
};
return mimeTypes[ext] || 'application/octet-stream';
}
// Serve static files
function serveStaticFile(req, res, filePath) {
fs.stat(filePath, (err, stats) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');
return;
}
if (stats.isDirectory()) {
// Try to serve index.html from directory
const indexPath = path.join(filePath, 'index.html');
fs.stat(indexPath, (err, indexStats) => {
if (!err && indexStats.isFile()) {
serveStaticFile(req, res, indexPath);
} else {
// List directory contents
fs.readdir(filePath, (err, files) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading directory');
return;
}
const html = `
<!DOCTYPE html>
<html>
<head><title>Directory listing</title></head>
<body>
<h1>Directory listing for ${req.url}</h1>
<ul>
${files.map(file =>
`<li><a href="${path.join(req.url, file)}">${file}</a></li>`
).join('')}
</ul>
</body>
</html>
`;
const headers = {
'Content-Type': 'text/html',
'Content-Length': Buffer.byteLength(html)
};
if (!config.cache) {
headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
headers['Pragma'] = 'no-cache';
headers['Expires'] = '0';
}
if (config.cors) {
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control';
}
res.writeHead(200, headers);
res.end(html);
});
}
});
return;
}
// Serve file
const mimeType = getMimeType(filePath);
const headers = {
'Content-Type': mimeType,
'Content-Length': stats.size
};
if (!config.cache) {
headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
headers['Pragma'] = 'no-cache';
headers['Expires'] = '0';
}
if (config.cors) {
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control';
}
res.writeHead(200, headers);
const stream = fs.createReadStream(filePath);
stream.pipe(res);
stream.on('error', (err) => {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading file');
});
});
}
// Create HTTP server
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
// Handle CORS preflight
if (req.method === 'OPTIONS' && config.cors) {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control'
});
res.end();
return;
}
// Handle getPhoenixPath API for Tauri dev mode
if (parsedUrl.pathname === '/api/getPhoenixPath') {
const response = {
phoenixPath: config.root
};
if (!config.silent) {
console.log(`[API] ${req.method} ${parsedUrl.pathname} -> ${JSON.stringify(response)}`);
}
const headers = {
'Content-Type': 'application/json'
};
if (config.cors) {
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control';
}
res.writeHead(200, headers);
res.end(JSON.stringify(response));
return;
}
// Handle proxy config request
if (parsedUrl.pathname === '/proxy/config') {
const configResponse = {
accountURL: accountServer + '/'
};
if (!config.silent) {
console.log(`[CONFIG] ${req.method} ${parsedUrl.pathname} -> ${JSON.stringify(configResponse)}`);
}
const headers = {
'Content-Type': 'application/json'
};
if (config.cors) {
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control';
}
res.writeHead(200, headers);
res.end(JSON.stringify(configResponse));
return;
}
// Check if this is a proxy request
if (parsedUrl.pathname.startsWith('/proxy/accounts')) {
// Extract the path after /proxy/accounts
const targetPath = parsedUrl.pathname.replace('/proxy/accounts', '');
const originalUrl = req.url;
// Modify the request URL for the proxy
req.url = targetPath + (parsedUrl.search || '');
if (!config.silent) {
console.log(`[PROXY] ${req.method} ${originalUrl} -> ${accountServer}${req.url}`);
}
// Proxy the request
proxy.web(req, res, {
target: accountServer,
changeOrigin: true,
secure: true
});
return;
}
// Serve static files
let filePath = path.join(config.root, parsedUrl.pathname);
// Security: prevent directory traversal
const normalizedPath = path.normalize(filePath);
if (!normalizedPath.startsWith(config.root)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
if (!config.silent) {
// Skip logging PWA asset requests to reduce noise. chrome somehoe sends this every second to dev server.
if (!parsedUrl.pathname.includes('/assets/pwa/')) {
const clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}${config.logIp ? ` (${clientIp})` : ''}`);
}
}
// Handle directory requests without trailing slash
fs.stat(filePath, (err, stats) => {
if (err) {
serveStaticFile(req, res, filePath);
} else if (stats.isDirectory() && !parsedUrl.pathname.endsWith('/')) {
// Redirect to URL with trailing slash for directories
res.writeHead(301, { 'Location': req.url + '/' });
res.end();
} else {
serveStaticFile(req, res, filePath);
}
});
});
// Parse arguments and start server
parseArgs();
server.listen(config.port, config.host, () => {
if (!config.silent) {
console.log(`Starting up http-server, serving ${config.root}`);
console.log(`Available on:`);
console.log(` http://${config.host === '0.0.0.0' ? 'localhost' : config.host}:${config.port}`);
console.log(`Proxy routes:`);
console.log(` /proxy/accounts/* -> ${accountServer}/*`);
console.log('Hit CTRL-C to stop the server');
}
});
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\nShutting down the server...');
server.close(() => {
process.exit(0);
});
});
process.on('SIGTERM', () => {
console.log('\nShutting down the server...');
server.close(() => {
process.exit(0);
});
});