-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathimage-proxy-server.js
More file actions
216 lines (181 loc) · 6.02 KB
/
Copy pathimage-proxy-server.js
File metadata and controls
216 lines (181 loc) · 6.02 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
const express = require('express');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const app = express();
const PORT = process.env.PORT || 5000;
// Security validation - only allow Google Drive and common image domains
const ALLOWED_DOMAINS = [
'drive.google.com',
'drive.usercontent.google.com',
'docs.google.com',
'lh3.googleusercontent.com',
'lh4.googleusercontent.com',
'lh5.googleusercontent.com',
'lh6.googleusercontent.com'
];
// CORS middleware
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:5173');
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
return;
}
next();
});
// Validate URL security
function isValidUrl(url) {
try {
const urlObj = new URL(url);
return ALLOWED_DOMAINS.includes(urlObj.hostname);
} catch {
return false;
}
}
// Get content type from response headers and url
function getContentType(headers, targetUrl) {
const contentType = headers.get('content-type');
if (contentType) return contentType;
// Fallback to common image types based on URL
const url = (targetUrl || '').toLowerCase();
if (url.includes('.jpg') || url.includes('.jpeg')) return 'image/jpeg';
if (url.includes('.png')) return 'image/png';
if (url.includes('.gif')) return 'image/gif';
if (url.includes('.webp')) return 'image/webp';
return 'image/jpeg'; // Default fallback
}
// Safe fetch function that validates redirect locations to prevent SSRF
async function safeFetch(url, options, depth = 0) {
if (depth > 5) {
throw new Error('Too many redirects');
}
const response = await fetch(url, {
...options,
redirect: 'manual'
});
if (response.status >= 300 && response.status < 400) {
const location = response.headers.get('location');
if (!location) {
return response;
}
// Resolve relative redirects against the current URL
const resolvedUrl = new URL(location, url).toString();
if (!isValidUrl(resolvedUrl)) {
throw new Error('Redirect to non-permitted domain is blocked');
}
return safeFetch(resolvedUrl, options, depth + 1);
}
return response;
}
// Main image proxy endpoint
app.get('/image', async (req, res) => {
const { url } = req.query;
// Validate input
if (!url) {
return res.status(400).json({
error: 'Missing required parameter: url'
});
}
// Decode URL
let decodedUrl;
try {
decodedUrl = decodeURIComponent(url);
} catch {
return res.status(400).json({
error: 'Invalid URL encoding'
});
}
// Security validation
if (!isValidUrl(decodedUrl)) {
return res.status(403).json({
error: 'URL not allowed. Only Google Drive domains are permitted.',
allowedDomains: ALLOWED_DOMAINS
});
}
// Create timeout controller (15s timeout limit)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
try {
// Fetch the image safely
const response = await safeFetch(decodedUrl, {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'image/*',
'Accept-Encoding': 'gzip, deflate, br'
},
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
return res.status(response.status).json({
error: `Failed to fetch image: ${response.statusText}`,
status: response.status
});
}
// Size check from headers
const contentLength = response.headers.get('content-length');
const MAX_BYTES = 50 * 1024 * 1024; // 50MB
if (contentLength && parseInt(contentLength, 10) > MAX_BYTES) {
return res.status(413).json({ error: 'File size exceeds 50MB limit' });
}
// Set appropriate response headers
const contentType = getContentType(response.headers, decodedUrl);
res.setHeader('Content-Type', contentType);
if (contentLength) {
res.setHeader('Content-Length', contentLength);
}
res.setHeader('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173');
// Stream response body directly with byte limit check to prevent memory exhaustion
let bytesRead = 0;
response.body.on('data', (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_BYTES) {
response.body.destroy();
if (!res.headersSent) {
res.status(413).json({ error: 'File size limit exceeded' });
}
}
});
response.body.pipe(res);
} catch (error) {
clearTimeout(timeoutId);
console.error('Proxy error:', error);
if (error.name === 'AbortError') {
return res.status(504).json({ error: 'Gateway timeout: Request took longer than 15s' });
}
res.status(500).json({
error: 'Internal server error while fetching image',
details: error.message
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
version: '1.0.0'
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Server error:', err);
res.status(500).json({
error: 'Internal server error'
});
});
// 404 handler
app.use((req, res) => {
res.status(404).json({
error: 'Endpoint not found',
availableEndpoints: ['/image', '/health']
});
});
// Start server
app.listen(PORT, () => {
console.log(`Image proxy server running on http://localhost:${PORT}`);
});
module.exports = app;