mirror of
https://github.com/movie-web/simple-proxy.git
synced 2025-09-13 14:33:27 +00:00
Compare commits
33 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
5a09e0c602 | ||
|
8852fca320 | ||
|
1e147a793d | ||
|
e88a4f3203 | ||
|
7dc9d1809f | ||
|
02b4dca218 | ||
|
5faca36cb4 | ||
|
ad0ae4aaae | ||
|
07a87b4571 | ||
|
e216a59cbb | ||
|
015f15d2e7 | ||
|
3a1e8688cc | ||
|
d348892158 | ||
|
3d192e8bb8 | ||
|
882e26fa1b | ||
|
054ea6aa07 | ||
|
8c503269d1 | ||
|
15b438be48 | ||
|
88b1852a91 | ||
|
8c89f79441 | ||
|
a03e1c1b59 | ||
|
9e5d1a2993 | ||
|
0a553a8b84 | ||
|
9ef1467ee1 | ||
|
ed4d8826ce | ||
|
3e63fe5b61 | ||
|
0500b7caa5 | ||
|
193fcc06f7 | ||
|
eb58298582 | ||
|
655b053fd6 | ||
|
67a7c55a88 | ||
|
37802661ad | ||
|
c0ce4c9e84 |
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@@ -47,7 +47,7 @@ jobs:
|
||||
body: |
|
||||
Instead of downloading a package, you can also run it in docker:
|
||||
```sh
|
||||
docker run movie-web/simple-proxy:${{ steps.package-version.outputs.current-version }}
|
||||
docker run ghcr.io/movie-web/simple-proxy:${{ steps.package-version.outputs.current-version }}
|
||||
```
|
||||
|
||||
- name: Upload cloudflare build
|
||||
|
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,8 +1,7 @@
|
||||
# simple-proxy
|
||||
|
||||
Simple reverse proxy to bypass CORS, used by [movie-web](https://movie-web.app).
|
||||
|
||||
[](https://deploy.workers.cloudflare.com/?url=https://github.com/movie-web/simple-proxy)
|
||||
Read the docs at https://docs.movie-web.app/proxy
|
||||
|
||||
---
|
||||
|
||||
@@ -10,6 +9,10 @@ Simple reverse proxy to bypass CORS, used by [movie-web](https://movie-web.app).
|
||||
- Deployable on many platforms - thanks to nitro
|
||||
- header rewrites - read and write protected headers
|
||||
- bypass CORS - always allows browser to send requests through it
|
||||
- secure it with turnstile - prevent bots from using your proxy
|
||||
|
||||
> [!WARNING]
|
||||
> Turnstile integration only works properly with cloudflare workers as platform
|
||||
|
||||
### supported platforms:
|
||||
- cloudflare workers
|
||||
|
@@ -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.0.0",
|
||||
"version": "2.1.3",
|
||||
"scripts": {
|
||||
"prepare": "nitropack prepare",
|
||||
"dev": "nitropack dev",
|
||||
@@ -15,8 +15,9 @@
|
||||
"preinstall": "npx only-allow pnpm"
|
||||
},
|
||||
"dependencies": {
|
||||
"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",
|
||||
|
833
pnpm-lock.yaml
generated
833
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,14 @@
|
||||
import { getBodyBuffer } from '@/utils/body';
|
||||
import {
|
||||
getProxyHeaders,
|
||||
getAfterResponseHeaders,
|
||||
cleanupHeadersBeforeProxy,
|
||||
getBlacklistedHeaders,
|
||||
} from '@/utils/headers';
|
||||
import {
|
||||
createTokenIfNeeded,
|
||||
isAllowedToMakeRequest,
|
||||
setTokenHeader,
|
||||
} from '@/utils/turnstile';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// handle cors, if applicable
|
||||
@@ -11,24 +17,46 @@ export default defineEventHandler(async (event) => {
|
||||
// parse destination URL
|
||||
const destination = getQuery<{ destination?: string }>(event).destination;
|
||||
if (!destination)
|
||||
return sendJson({
|
||||
return await sendJson({
|
||||
event,
|
||||
status: 400,
|
||||
status: 200,
|
||||
data: {
|
||||
error: 'destination query parameter invalid',
|
||||
message: `Proxy is working as expected (v${
|
||||
useRuntimeConfig(event).version
|
||||
})`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!(await isAllowedToMakeRequest(event)))
|
||||
return await sendJson({
|
||||
event,
|
||||
status: 401,
|
||||
data: {
|
||||
error: 'Invalid or missing token',
|
||||
},
|
||||
});
|
||||
|
||||
// read body
|
||||
const body = await getBodyBuffer(event);
|
||||
const token = await createTokenIfNeeded(event);
|
||||
|
||||
// proxy
|
||||
cleanupHeadersBeforeProxy(event);
|
||||
await proxyRequest(event, destination, {
|
||||
fetchOptions: {
|
||||
redirect: 'follow',
|
||||
headers: getProxyHeaders(event.headers),
|
||||
},
|
||||
onResponse(outputEvent, response) {
|
||||
const headers = getAfterResponseHeaders(response.headers, response.url);
|
||||
setResponseHeaders(outputEvent, headers);
|
||||
},
|
||||
});
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
13
src/utils/body.ts
Normal file
13
src/utils/body.ts
Normal 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);
|
||||
}
|
@@ -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;
|
||||
}
|
||||
|
10
src/utils/ip.ts
Normal file
10
src/utils/ip.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { EventHandlerRequest, H3Event } from 'h3';
|
||||
|
||||
export function getIp(event: H3Event<EventHandlerRequest>) {
|
||||
const value = getHeader(event, 'CF-Connecting-IP');
|
||||
if (!value)
|
||||
throw new Error(
|
||||
'Ip header not found, turnstile only works on cloudflare workers',
|
||||
);
|
||||
return value;
|
||||
}
|
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,11 +1,10 @@
|
||||
import { H3Event, EventHandlerRequest } from 'h3';
|
||||
|
||||
export function sendJson(ops: {
|
||||
export async function sendJson(ops: {
|
||||
event: H3Event<EventHandlerRequest>;
|
||||
data: Record<string, any>;
|
||||
status?: number;
|
||||
}) {
|
||||
setResponseStatus(ops.event, ops.status ?? 200);
|
||||
appendResponseHeader(ops.event, 'content-type', 'application/json');
|
||||
send(ops.event, JSON.stringify(ops.data, null, 2));
|
||||
await send(ops.event, JSON.stringify(ops.data, null, 2), 'application/json');
|
||||
}
|
||||
|
90
src/utils/turnstile.ts
Normal file
90
src/utils/turnstile.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { H3Event, EventHandlerRequest } from 'h3';
|
||||
import { SignJWT, jwtVerify } from 'jose';
|
||||
import { getIp } from '@/utils/ip';
|
||||
|
||||
const turnstileSecret = process.env.TURNSTILE_SECRET ?? null;
|
||||
const jwtSecret = process.env.JWT_SECRET ?? null;
|
||||
|
||||
const tokenHeader = 'X-Token';
|
||||
const jwtPrefix = 'jwt|';
|
||||
const turnstilePrefix = 'turnstile|';
|
||||
|
||||
export function isTurnstileEnabled() {
|
||||
return !!turnstileSecret && !!jwtSecret;
|
||||
}
|
||||
|
||||
export async function makeToken(ip: string) {
|
||||
if (!jwtSecret) throw new Error('Cannot make token without a secret');
|
||||
return await new SignJWT({ ip })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setExpirationTime('10m')
|
||||
.sign(new TextEncoder().encode(jwtSecret));
|
||||
}
|
||||
|
||||
export function setTokenHeader(
|
||||
event: H3Event<EventHandlerRequest>,
|
||||
token: string,
|
||||
) {
|
||||
setHeader(event, tokenHeader, token);
|
||||
}
|
||||
|
||||
export async function createTokenIfNeeded(
|
||||
event: H3Event<EventHandlerRequest>,
|
||||
): Promise<null | string> {
|
||||
if (!isTurnstileEnabled()) return null;
|
||||
if (!jwtSecret) return null;
|
||||
const token = event.headers.get(tokenHeader);
|
||||
if (!token) return null;
|
||||
if (!token.startsWith(turnstilePrefix)) return null;
|
||||
|
||||
return await makeToken(getIp(event));
|
||||
}
|
||||
|
||||
export async function isAllowedToMakeRequest(
|
||||
event: H3Event<EventHandlerRequest>,
|
||||
) {
|
||||
if (!isTurnstileEnabled()) return true;
|
||||
|
||||
const token = event.headers.get(tokenHeader);
|
||||
if (!token) return false;
|
||||
if (!jwtSecret || !turnstileSecret) return false;
|
||||
|
||||
if (token.startsWith(jwtPrefix)) {
|
||||
const jwtToken = token.slice(jwtPrefix.length);
|
||||
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;
|
||||
}
|
||||
|
||||
if (token.startsWith(turnstilePrefix)) {
|
||||
const turnstileToken = token.slice(turnstilePrefix.length);
|
||||
const formData = new FormData();
|
||||
formData.append('secret', turnstileSecret);
|
||||
formData.append('response', turnstileToken);
|
||||
formData.append('remoteip', getIp(event));
|
||||
|
||||
const result = await fetch(
|
||||
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
|
||||
{
|
||||
body: formData,
|
||||
method: 'POST',
|
||||
},
|
||||
);
|
||||
|
||||
const outcome: { success: boolean } = await result.json();
|
||||
return outcome.success;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
Reference in New Issue
Block a user