Initial setup from simple-proxy

This commit is contained in:
William Oldham
2023-12-17 20:02:37 +00:00
parent 9bf6a12c3d
commit 040bf3b0bc
14 changed files with 4646 additions and 0 deletions

39
src/routes/index.ts Normal file
View File

@@ -0,0 +1,39 @@
import { getBodyBuffer } from '@/utils/body';
import {
getProxyHeaders,
getAfterResponseHeaders,
cleanupHeadersBeforeProxy,
} from '@/utils/headers';
export default defineEventHandler(async (event) => {
// handle cors, if applicable
if (isPreflightRequest(event)) return handleCors(event, {});
// parse destination URL
const destination = getQuery<{ destination?: string }>(event).destination;
if (!destination)
return await sendJson({
event,
status: 400,
data: {
error: 'destination query parameter invalid',
},
});
// read body
const body = await getBodyBuffer(event);
// proxy
cleanupHeadersBeforeProxy(event);
await proxyRequest(event, destination, {
fetchOptions: {
redirect: 'follow',
headers: getProxyHeaders(event.headers),
body,
},
onResponse(outputEvent, response) {
const headers = getAfterResponseHeaders(response.headers, response.url);
setResponseHeaders(outputEvent, headers);
},
});
});

13
src/utils/body.ts Normal file
View File

@@ -0,0 +1,13 @@
import { H3Event } from 'h3';
export function hasBody(event: H3Event) {
const method = event.method.toUpperCase();
return ['PUT', 'POST', 'PATCH', 'DELETE'].includes(method);
}
export async function getBodyBuffer(
event: H3Event,
): Promise<Buffer | undefined> {
if (!hasBody(event)) return;
return await readRawBody(event, false);
}

73
src/utils/headers.ts Normal file
View File

@@ -0,0 +1,73 @@
import { H3Event } from 'h3';
const blacklistedHeaders = [
'cf-connecting-ip',
'cf-worker',
'cf-ray',
'cf-visitor',
'cf-ew-via',
'x-forwarded-for',
'x-forwarded-host',
'x-forwarded-proto',
'forwarded',
'x-real-ip',
];
function copyHeader(
headers: Headers,
outputHeaders: Headers,
inputKey: string,
outputKey: string,
) {
if (headers.has(inputKey))
outputHeaders.set(outputKey, headers.get(inputKey) ?? '');
}
export function getProxyHeaders(headers: Headers): Headers {
const output = new Headers();
const headerMap: Record<string, string> = {
'X-Cookie': 'Cookie',
'X-Referer': 'Referer',
'X-Origin': 'Origin',
};
Object.entries(headerMap).forEach((entry) => {
copyHeader(headers, output, entry[0], entry[1]);
});
output.set(
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0',
);
return output;
}
export function getAfterResponseHeaders(
headers: Headers,
finalUrl: string,
): Record<string, string> {
const output: Record<string, string> = {};
if (headers.has('Set-Cookie'))
output['X-Set-Cookie'] = headers.get('Set-Cookie') ?? '';
return {
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': '*',
Vary: 'Origin',
'X-Final-Destination': finalUrl,
};
}
export function removeHeadersFromEvent(event: H3Event, key: string) {
const normalizedKey = key.toLowerCase();
if (event.node.req.headers[normalizedKey])
delete event.node.req.headers[normalizedKey];
}
export function cleanupHeadersBeforeProxy(event: H3Event) {
blacklistedHeaders.forEach((key) => {
removeHeadersFromEvent(event, key);
});
}

10
src/utils/sending.ts Normal file
View File

@@ -0,0 +1,10 @@
import { H3Event, EventHandlerRequest } from 'h3';
export async function sendJson(ops: {
event: H3Event<EventHandlerRequest>;
data: Record<string, any>;
status?: number;
}) {
setResponseStatus(ops.event, ops.status ?? 200);
await send(ops.event, JSON.stringify(ops.data, null, 2), 'application/json');
}