mirror of
https://github.com/movie-web/simple-proxy.git
synced 2025-09-13 10:23:25 +00:00
Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
5a09e0c602 | ||
|
8852fca320 | ||
|
1e147a793d | ||
|
e88a4f3203 | ||
|
7dc9d1809f | ||
|
02b4dca218 | ||
|
5faca36cb4 | ||
|
ad0ae4aaae | ||
|
07a87b4571 | ||
|
e216a59cbb | ||
|
015f15d2e7 | ||
|
3a1e8688cc | ||
|
d348892158 | ||
|
3d192e8bb8 | ||
|
882e26fa1b | ||
|
054ea6aa07 | ||
|
8c503269d1 | ||
|
15b438be48 |
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 movie-web
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@@ -1,9 +1,13 @@
|
||||
import { join } from "path";
|
||||
import pkg from "./package.json";
|
||||
|
||||
//https://nitro.unjs.io/config
|
||||
export default defineNitroConfig({
|
||||
noPublicDir: true,
|
||||
srcDir: "./src",
|
||||
runtimeConfig: {
|
||||
version: pkg.version
|
||||
},
|
||||
alias: {
|
||||
"@": join(__dirname, "src")
|
||||
}
|
||||
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "simple-proxy",
|
||||
"private": true,
|
||||
"version": "2.1.0",
|
||||
"version": "2.1.3",
|
||||
"scripts": {
|
||||
"prepare": "nitropack prepare",
|
||||
"dev": "nitropack dev",
|
||||
@@ -15,9 +15,9 @@
|
||||
"preinstall": "npx only-allow pnpm"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tsndr/cloudflare-worker-jwt": "^2.3.2",
|
||||
"h3": "^1.8.1",
|
||||
"nitropack": "latest"
|
||||
"h3": "^1.10.0",
|
||||
"jose": "^5.2.0",
|
||||
"nitropack": "^2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "^6.7.0",
|
||||
|
812
pnpm-lock.yaml
generated
812
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,7 @@ import { getBodyBuffer } from '@/utils/body';
|
||||
import {
|
||||
getProxyHeaders,
|
||||
getAfterResponseHeaders,
|
||||
cleanupHeadersBeforeProxy,
|
||||
getBlacklistedHeaders,
|
||||
} from '@/utils/headers';
|
||||
import {
|
||||
createTokenIfNeeded,
|
||||
@@ -21,7 +21,9 @@ export default defineEventHandler(async (event) => {
|
||||
event,
|
||||
status: 200,
|
||||
data: {
|
||||
message: 'Proxy is working as expected',
|
||||
message: `Proxy is working as expected (v${
|
||||
useRuntimeConfig(event).version
|
||||
})`,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -39,17 +41,22 @@ export default defineEventHandler(async (event) => {
|
||||
const token = await createTokenIfNeeded(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);
|
||||
if (token) setTokenHeader(event, token);
|
||||
},
|
||||
});
|
||||
try {
|
||||
await specificProxyRequest(event, destination, {
|
||||
blacklistedHeaders: getBlacklistedHeaders(),
|
||||
fetchOptions: {
|
||||
redirect: 'follow',
|
||||
headers: getProxyHeaders(event.headers),
|
||||
body,
|
||||
},
|
||||
onResponse(outputEvent, response) {
|
||||
const headers = getAfterResponseHeaders(response.headers, response.url);
|
||||
setResponseHeaders(outputEvent, headers);
|
||||
if (token) setTokenHeader(event, token);
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Error fetching', e);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
@@ -1,4 +1,10 @@
|
||||
import { H3Event } from 'h3';
|
||||
const headerMap: Record<string, string> = {
|
||||
'X-Cookie': 'Cookie',
|
||||
'X-Referer': 'Referer',
|
||||
'X-Origin': 'Origin',
|
||||
'X-User-Agent': 'User-Agent',
|
||||
'X-X-Real-Ip': 'X-Real-Ip',
|
||||
};
|
||||
|
||||
const blacklistedHeaders = [
|
||||
'cf-connecting-ip',
|
||||
@@ -6,11 +12,16 @@ const blacklistedHeaders = [
|
||||
'cf-ray',
|
||||
'cf-visitor',
|
||||
'cf-ew-via',
|
||||
'cdn-loop',
|
||||
'x-amzn-trace-id',
|
||||
'cf-ipcountry',
|
||||
'x-forwarded-for',
|
||||
'x-forwarded-host',
|
||||
'x-forwarded-proto',
|
||||
'forwarded',
|
||||
'x-real-ip',
|
||||
'content-length',
|
||||
...Object.keys(headerMap),
|
||||
];
|
||||
|
||||
function copyHeader(
|
||||
@@ -26,20 +37,16 @@ function copyHeader(
|
||||
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]);
|
||||
});
|
||||
|
||||
// default user agent
|
||||
output.set(
|
||||
'User-Agent',
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0',
|
||||
);
|
||||
|
||||
Object.entries(headerMap).forEach((entry) => {
|
||||
copyHeader(headers, output, entry[0], entry[1]);
|
||||
});
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
@@ -60,14 +67,6 @@ export function getAfterResponseHeaders(
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
export function getBlacklistedHeaders() {
|
||||
return blacklistedHeaders;
|
||||
}
|
||||
|
92
src/utils/proxy.ts
Normal file
92
src/utils/proxy.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import {
|
||||
H3Event,
|
||||
Duplex,
|
||||
ProxyOptions,
|
||||
getProxyRequestHeaders,
|
||||
RequestHeaders,
|
||||
} from 'h3';
|
||||
|
||||
const PayloadMethods = new Set(['PATCH', 'POST', 'PUT', 'DELETE']);
|
||||
|
||||
export interface ExtraProxyOptions {
|
||||
blacklistedHeaders?: string[];
|
||||
}
|
||||
|
||||
function mergeHeaders(
|
||||
defaults: HeadersInit,
|
||||
...inputs: (HeadersInit | RequestHeaders | undefined)[]
|
||||
) {
|
||||
const _inputs = inputs.filter(Boolean) as HeadersInit[];
|
||||
if (_inputs.length === 0) {
|
||||
return defaults;
|
||||
}
|
||||
const merged = new Headers(defaults);
|
||||
for (const input of _inputs) {
|
||||
if (input.entries) {
|
||||
for (const [key, value] of (input.entries as any)()) {
|
||||
if (value !== undefined) {
|
||||
merged.set(key, value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
if (value !== undefined) {
|
||||
merged.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export async function specificProxyRequest(
|
||||
event: H3Event,
|
||||
target: string,
|
||||
opts: ProxyOptions & ExtraProxyOptions = {},
|
||||
) {
|
||||
let body;
|
||||
let duplex: Duplex | undefined;
|
||||
if (PayloadMethods.has(event.method)) {
|
||||
if (opts.streamRequest) {
|
||||
body = getRequestWebStream(event);
|
||||
duplex = 'half';
|
||||
} else {
|
||||
body = await readRawBody(event, false).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const method = opts.fetchOptions?.method || event.method;
|
||||
const oldHeaders = getProxyRequestHeaders(event);
|
||||
opts.blacklistedHeaders?.forEach((header) => {
|
||||
const keys = Object.keys(oldHeaders).filter(
|
||||
(v) => v.toLowerCase() === header.toLowerCase(),
|
||||
);
|
||||
keys.forEach((k) => delete oldHeaders[k]);
|
||||
});
|
||||
|
||||
const fetchHeaders = mergeHeaders(
|
||||
oldHeaders,
|
||||
opts.fetchOptions?.headers,
|
||||
opts.headers,
|
||||
);
|
||||
const headerObj = Object.fromEntries([...(fetchHeaders.entries as any)()]);
|
||||
if (process.env.REQ_DEBUG === 'true') {
|
||||
console.log({
|
||||
type: 'request',
|
||||
method,
|
||||
url: target,
|
||||
headers: headerObj,
|
||||
});
|
||||
}
|
||||
|
||||
return sendProxy(event, target, {
|
||||
...opts,
|
||||
fetchOptions: {
|
||||
method,
|
||||
body,
|
||||
duplex,
|
||||
...opts.fetchOptions,
|
||||
headers: fetchHeaders,
|
||||
},
|
||||
});
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
import { H3Event, EventHandlerRequest } from 'h3';
|
||||
import jsonwebtoken from '@tsndr/cloudflare-worker-jwt';
|
||||
import { SignJWT, jwtVerify } from 'jose';
|
||||
import { getIp } from '@/utils/ip';
|
||||
|
||||
const turnstileSecret = process.env.TURNSTILE_SECRET ?? null;
|
||||
@@ -15,13 +15,10 @@ export function isTurnstileEnabled() {
|
||||
|
||||
export async function makeToken(ip: string) {
|
||||
if (!jwtSecret) throw new Error('Cannot make token without a secret');
|
||||
return await jsonwebtoken.sign(
|
||||
{
|
||||
ip,
|
||||
exp: Math.floor(Date.now() / 1000) + 60 * 10, // 10 Minutes
|
||||
},
|
||||
jwtSecret,
|
||||
);
|
||||
return await new SignJWT({ ip })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setExpirationTime('10m')
|
||||
.sign(new TextEncoder().encode(jwtSecret));
|
||||
}
|
||||
|
||||
export function setTokenHeader(
|
||||
@@ -54,13 +51,19 @@ export async function isAllowedToMakeRequest(
|
||||
|
||||
if (token.startsWith(jwtPrefix)) {
|
||||
const jwtToken = token.slice(jwtPrefix.length);
|
||||
const isValid = await jsonwebtoken.verify(jwtToken, jwtSecret, {
|
||||
algorithm: 'HS256',
|
||||
});
|
||||
if (!isValid) return false;
|
||||
const jwtBody = jsonwebtoken.decode<{ ip: string }>(jwtToken);
|
||||
if (!jwtBody.payload) return false;
|
||||
if (getIp(event) !== jwtBody.payload.ip) return false;
|
||||
let jwtPayload: { ip: string } | null = null;
|
||||
try {
|
||||
const jwtResult = await jwtVerify<{ ip: string }>(
|
||||
jwtToken,
|
||||
new TextEncoder().encode(jwtSecret),
|
||||
{
|
||||
algorithms: ['HS256'],
|
||||
},
|
||||
);
|
||||
jwtPayload = jwtResult.payload;
|
||||
} catch {}
|
||||
if (!jwtPayload) return false;
|
||||
if (getIp(event) !== jwtPayload.ip) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user