Blame Raw
Cohee · 51ad27fb · · 46 lines (1.6 KB)
2 contributors
1import fetch from 'node-fetch';
2import { forwardFetchResponse } from '../util.js';
3
4/**
5 * Middleware to proxy requests to a different domain
6 * @param {import('express').Request} req Express request object
7 * @param {import('express').Response} res Express response object
8 */
9export default async function corsProxyMiddleware(req, res) {
10 const url = req.params.url; // get the url from the request path
11
12 // Disallow circular requests
13 const serverUrl = req.protocol + '://' + req.get('host');
14 if (url.startsWith(serverUrl)) {
15 return res.status(400).send('Circular requests are not allowed');
16 }
17
18 try {
19 const headers = JSON.parse(JSON.stringify(req.headers));
20 const headersToRemove = [
21 'x-csrf-token', 'host', 'referer', 'origin', 'cookie',
22 'x-forwarded-for', 'x-forwarded-protocol', 'x-forwarded-proto',
23 'x-forwarded-host', 'x-real-ip', 'sec-fetch-mode',
24 'sec-fetch-site', 'sec-fetch-dest',
25 ];
26
27 headersToRemove.forEach(header => delete headers[header]);
28
29 const bodyMethods = ['POST', 'PUT', 'PATCH'];
30
31 const response = await fetch(url, {
32 method: req.method,
33 headers: headers,
34 body: bodyMethods.includes(req.method) ? JSON.stringify(req.body) : undefined,
35 });
36
37 // Copy over relevant response params to the proxy response
38 await forwardFetchResponse(response, res);
39 } catch (error) {
40 console.error('Error in CORS proxy middleware:', error);
41 if (!res.headersSent) {
42 return res.sendStatus(500);
43 }
44 return res.end();
45 }
46}