-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi-proxy.js
More file actions
288 lines (241 loc) · 8.95 KB
/
Copy pathapi-proxy.js
File metadata and controls
288 lines (241 loc) · 8.95 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
// Minimal API proxy for Resend + Static file server
// This allows the browser app to securely call Resend without exposing API key
// The API key is passed by the client, then proxied to Resend
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');
const PORT = process.env.PORT || 3001;
const API_URL = process.env.API_URL || 'http://localhost:3001';
const server = http.createServer((req, res) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
// Enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Handle preflight
if (req.method === 'OPTIONS') {
console.log('[PREFLIGHT] Responding to OPTIONS request');
res.writeHead(200);
res.end();
return;
}
// Route API calls
if (req.method === 'POST' && req.url === '/api/send') {
res.setHeader('Content-Type', 'application/json');
handleSendEmail(req, res);
} else if (req.method === 'GET' && req.url === '/api/domains') {
res.setHeader('Content-Type', 'application/json');
handleGetDomains(req, res);
} else if (req.method === 'GET' && req.url.startsWith('/api/email/')) {
res.setHeader('Content-Type', 'application/json');
handleGetEmail(req, res);
} else if (req.method === 'GET' && req.url.startsWith('/api/sent')) {
res.setHeader('Content-Type', 'application/json');
handleGetSent(req, res);
} else {
// Serve static files (index.html for root)
let filePath = req.url === '/' ? '/index.html' : req.url;
filePath = path.join(__dirname, filePath);
// Security: prevent directory traversal
const realPath = path.resolve(filePath);
const baseDir = path.resolve(__dirname);
if (!realPath.startsWith(baseDir)) {
console.log('[SECURITY] Directory traversal attempt blocked:', req.url);
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
console.log('[404] File not found:', filePath);
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
return;
}
// Set content type based on file extension
let contentType = 'text/plain';
if (filePath.endsWith('.html')) contentType = 'text/html';
else if (filePath.endsWith('.css')) contentType = 'text/css';
else if (filePath.endsWith('.js')) contentType = 'application/javascript';
else if (filePath.endsWith('.json')) contentType = 'application/json';
else if (filePath.endsWith('.xml')) contentType = 'application/xml';
else if (filePath.endsWith('.txt')) contentType = 'text/plain';
else if (filePath.endsWith('.png')) contentType = 'image/png';
else if (filePath.endsWith('.svg')) contentType = 'image/svg+xml';
else if (filePath.endsWith('.ico')) contentType = 'image/x-icon';
else if (filePath.endsWith('.jpg') || filePath.endsWith('.jpeg')) contentType = 'image/jpeg';
else if (filePath.endsWith('.webmanifest')) contentType = 'application/manifest+json';
console.log('[SERVE] Serving file:', filePath, 'as', contentType);
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
});
}
});
function handleSendEmail(req, res) {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
const apiKey = req.headers.authorization?.replace('Bearer ', '');
console.log('[SEND] Request received');
console.log('[SEND] API Key present:', !!apiKey);
// Privacy: Do NOT log email content, recipients, or subjects
if (!apiKey) {
console.log('[SEND] ERROR: Missing API key');
res.writeHead(401);
res.end(JSON.stringify({ error: 'Missing API key' }));
return;
}
// Forward to Resend API
const options = {
hostname: 'api.resend.com',
path: '/emails',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'Content-Length': Buffer.byteLength(body)
}
};
console.log('[SEND] Forwarding to Resend API...');
const resendReq = https.request(options, (resendRes) => {
let responseBody = '';
console.log('[SEND] Resend response status:', resendRes.statusCode);
resendRes.on('data', chunk => {
responseBody += chunk;
});
resendRes.on('end', () => {
console.log('[SEND] Email sent successfully');
res.writeHead(resendRes.statusCode, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(responseBody);
});
});
resendReq.on('error', (error) => {
console.error('[SEND] ERROR: Resend request failed:', error.message);
res.writeHead(500);
res.end(JSON.stringify({ error: 'Failed to contact Resend API', details: error.message }));
});
resendReq.write(body);
resendReq.end();
} catch (error) {
console.error('[SEND] Parse error:', error.message);
res.writeHead(400);
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
}
function handleGetDomains(req, res) {
const apiKey = req.headers.authorization?.replace('Bearer ', '');
console.log('[DOMAINS] Request received');
console.log('[DOMAINS] API Key present:', !!apiKey);
if (!apiKey) {
console.log('[DOMAINS] ERROR: Missing API key');
res.writeHead(401);
res.end(JSON.stringify({ error: 'Missing API key' }));
return;
}
const options = {
hostname: 'api.resend.com',
path: '/domains',
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`
}
};
console.log('[DOMAINS] Forwarding to Resend API...');
const resendReq = https.request(options, (resendRes) => {
let body = '';
console.log('[DOMAINS] Resend response status:', resendRes.statusCode);
resendRes.on('data', chunk => {
body += chunk;
});
resendRes.on('end', () => {
console.log('[DOMAINS] Domains fetched successfully');
res.writeHead(resendRes.statusCode, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(body);
});
});
resendReq.on('error', (error) => {
console.error('[DOMAINS] ERROR: Resend request failed:', error.message);
res.writeHead(500);
res.end(JSON.stringify({ error: 'Failed to contact Resend API', details: error.message }));
});
resendReq.end();
}
function handleGetEmail(req, res) {
const apiKey = req.headers.authorization?.replace('Bearer ', '');
if (!apiKey) {
res.writeHead(401);
res.end(JSON.stringify({ error: 'Missing API key' }));
return;
}
const emailId = req.url.replace('/api/email/', '');
const resendReq = https.request({
hostname: 'api.resend.com',
path: `/emails/${emailId}`,
method: 'GET',
headers: { 'Authorization': `Bearer ${apiKey}` }
}, (resendRes) => {
let body = '';
resendRes.on('data', chunk => { body += chunk; });
resendRes.on('end', () => {
res.writeHead(resendRes.statusCode, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(body);
});
});
resendReq.on('error', (error) => {
res.writeHead(500);
res.end(JSON.stringify({ error: 'Failed to contact Resend API', details: error.message }));
});
resendReq.end();
}
function handleGetSent(req, res) {
const apiKey = req.headers.authorization?.replace('Bearer ', '');
if (!apiKey) {
res.writeHead(401);
res.end(JSON.stringify({ error: 'Missing API key' }));
return;
}
const parsedUrl = new URL(req.url, `http://localhost`);
const page = parsedUrl.searchParams.get('page') || '1';
const resendReq = https.request({
hostname: 'api.resend.com',
path: `/emails?page=${page}`,
method: 'GET',
headers: { 'Authorization': `Bearer ${apiKey}` }
}, (resendRes) => {
let body = '';
resendRes.on('data', chunk => { body += chunk; });
resendRes.on('end', () => {
res.writeHead(resendRes.statusCode, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(body);
});
});
resendReq.on('error', (error) => {
res.writeHead(500);
res.end(JSON.stringify({ error: 'Failed to contact Resend API', details: error.message }));
});
resendReq.end();
}
server.listen(PORT, () => {
console.log(`✓ API proxy running on ${API_URL}`);
console.log(` - POST /api/send (with Bearer token)`);
console.log(` - GET /api/domains (with Bearer token)`);
});