-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
180 lines (164 loc) · 5.66 KB
/
Copy pathproxy.js
File metadata and controls
180 lines (164 loc) · 5.66 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
/**
* Local dev proxy for the cycling app (Node.js — no dependencies).
* - Serves static files from this directory at http://localhost:8080/
* - Proxies /icu-internal/* -> https://intervals.icu/api/*
* - Proxies /strava-internal/* -> https://www.strava.com/api/v3/*
* - Proxies /strava-auth/* -> https://www.strava.com/oauth/* (POST)
*
* Usage: node proxy.js
* Then open: http://localhost:8080
*/
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 8080;
const ROOT = __dirname;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.ico': 'image/x-icon',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2':'font/woff2',
};
const CORS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Authorization, Accept, Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
};
/** Forward a request to an upstream HTTPS server and pipe the response back. */
function proxyRequest(method, targetUrl, headers, body, res) {
const url = new URL(targetUrl);
const opts = {
hostname: url.hostname,
port: 443,
path: url.pathname + url.search,
method: method,
headers: headers,
timeout: 30000,
};
const upstream = https.request(opts, (upRes) => {
const chunks = [];
upRes.on('data', c => chunks.push(c));
upRes.on('end', () => {
const buf = Buffer.concat(chunks);
res.writeHead(upRes.statusCode, Object.assign({
'Content-Type': upRes.headers['content-type'] || 'application/json',
'Content-Length': buf.length,
}, CORS));
res.end(buf);
});
});
upstream.on('error', (err) => {
console.error('Proxy error:', err.message);
if (!res.headersSent) {
res.writeHead(502, CORS);
res.end();
}
});
upstream.on('timeout', () => { upstream.destroy(); });
if (body) upstream.write(body);
upstream.end();
}
/** Collect the full request body as a Buffer. */
function readBody(req) {
return new Promise((resolve) => {
const chunks = [];
req.on('data', c => chunks.push(c));
req.on('end', () => resolve(Buffer.concat(chunks)));
});
}
const server = http.createServer(async (req, res) => {
const urlPath = req.url.split('?')[0];
const fullUrl = req.url;
// --- CORS preflight ---
if (req.method === 'OPTIONS') {
res.writeHead(204, CORS);
return res.end();
}
// --- Proxy: /icu-internal/* -> intervals.icu ---
if (fullUrl.startsWith('/icu-internal/')) {
const tail = fullUrl.slice('/icu-internal/'.length);
const target = 'https://intervals.icu/api/' + tail;
if (req.method === 'POST' || req.method === 'PUT') {
const body = await readBody(req);
proxyRequest(req.method, target, {
'Authorization': req.headers['authorization'] || '',
'Content-Type': req.headers['content-type'] || 'application/json',
'Accept': 'application/json',
'Content-Length': body.length,
}, body, res);
} else {
proxyRequest('GET', target, {
'Authorization': req.headers['authorization'] || '',
'Accept': 'application/json',
}, null, res);
}
return;
}
// --- Proxy: /strava-internal/* -> Strava API (GET) ---
if (fullUrl.startsWith('/strava-internal/')) {
const tail = fullUrl.slice('/strava-internal/'.length);
const target = 'https://www.strava.com/api/v3/' + tail;
proxyRequest('GET', target, {
'Authorization': req.headers['authorization'] || '',
'Accept': 'application/json',
}, null, res);
return;
}
// --- Strava Auth: POST /strava-auth/* -> Strava OAuth ---
if (fullUrl.startsWith('/strava-auth/') && req.method === 'POST') {
const tail = fullUrl.slice('/strava-auth/'.length);
const target = 'https://www.strava.com/oauth/' + tail;
const body = await readBody(req);
proxyRequest('POST', target, {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Content-Length': body.length,
}, body, res);
return;
}
// --- Static file serving ---
let filePath = urlPath === '/' ? path.join(ROOT, 'index.html')
: path.join(ROOT, urlPath.replace(/^\//, ''));
// Security: prevent directory traversal
if (!filePath.startsWith(ROOT)) {
res.writeHead(403);
return res.end();
}
fs.stat(filePath, (err, stat) => {
if (err || !stat.isFile()) {
res.writeHead(404);
return res.end('Not found');
}
const ext = path.extname(filePath).toLowerCase();
const ct = MIME[ext] || 'application/octet-stream';
// Dev server: no-cache so edits take effect immediately
const cache = 'no-cache, no-store, must-revalidate';
res.writeHead(200, {
'Content-Type': ct,
'Content-Length': stat.size,
'Cache-Control': cache,
'X-Content-Type-Options': 'nosniff',
});
fs.createReadStream(filePath).pipe(res);
});
});
// Prevent server crash on unhandled errors
process.on('uncaughtException', (err) => {
console.error('Uncaught:', err.message);
});
server.listen(PORT, () => {
console.log(`Cycling app running at http://localhost:${PORT}/`);
console.log(`Proxying /icu-internal/* -> https://intervals.icu/api/*`);
console.log(`Proxying /strava-internal/* -> https://www.strava.com/api/v3/*`);
console.log(`Proxying /strava-auth/* -> https://www.strava.com/oauth/*`);
console.log('Press Ctrl+C to stop.\n');
});