6 Commits

Author SHA1 Message Date
mrjvs
d348892158 bump version 2024-01-04 21:06:50 +01:00
mrjvs
3d192e8bb8 Do proper proxying 2024-01-04 20:57:54 +01:00
mrjvs
882e26fa1b Upgrade h3 2024-01-04 20:16:53 +01:00
mrjvs
054ea6aa07 Support overwriting user agent 2024-01-04 19:54:24 +01:00
mrjvs
8c503269d1 Fixed AWS and NodeJS support 2024-01-04 19:54:14 +01:00
mrjvs
15b438be48 Create LICENSE 2023-12-23 23:25:03 +01:00
7 changed files with 176 additions and 61 deletions

21
LICENSE Normal file
View 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.

View File

@@ -1,7 +1,7 @@
{ {
"name": "simple-proxy", "name": "simple-proxy",
"private": true, "private": true,
"version": "2.1.0", "version": "2.1.1",
"scripts": { "scripts": {
"prepare": "nitropack prepare", "prepare": "nitropack prepare",
"dev": "nitropack dev", "dev": "nitropack dev",
@@ -15,8 +15,8 @@
"preinstall": "npx only-allow pnpm" "preinstall": "npx only-allow pnpm"
}, },
"dependencies": { "dependencies": {
"@tsndr/cloudflare-worker-jwt": "^2.3.2", "h3": "^1.9.0",
"h3": "^1.8.1", "jose": "^5.2.0",
"nitropack": "latest" "nitropack": "latest"
}, },
"devDependencies": { "devDependencies": {

52
pnpm-lock.yaml generated
View File

@@ -5,12 +5,12 @@ settings:
excludeLinksFromLockfile: false excludeLinksFromLockfile: false
dependencies: dependencies:
'@tsndr/cloudflare-worker-jwt':
specifier: ^2.3.2
version: 2.3.2
h3: h3:
specifier: ^1.8.1 specifier: ^1.9.0
version: 1.8.1 version: 1.9.0
jose:
specifier: ^5.2.0
version: 5.2.0
nitropack: nitropack:
specifier: latest specifier: latest
version: 2.6.3 version: 2.6.3
@@ -704,10 +704,6 @@ packages:
rollup: 3.29.1 rollup: 3.29.1
dev: false dev: false
/@tsndr/cloudflare-worker-jwt@2.3.2:
resolution: {integrity: sha512-g1jSm5olPqKh15kadnj0666YPudibHYGyFyM0URLXSeY5MzNIGkfhFedLgKHq8NCDBMzLUMX7Oz8d+jmQXqBuw==}
dev: false
/@types/estree@1.0.1: /@types/estree@1.0.1:
resolution: {integrity: sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==} resolution: {integrity: sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==}
dev: false dev: false
@@ -1406,6 +1402,10 @@ packages:
resolution: {integrity: sha512-+uO4+qr7msjNNWKYPHqN/3+Dx3NFkmIzayk2L1MyZQlvgZb/J1A0fo410dpKrN2SnqFjt8n4JL8fDJE0wIgjFQ==} resolution: {integrity: sha512-+uO4+qr7msjNNWKYPHqN/3+Dx3NFkmIzayk2L1MyZQlvgZb/J1A0fo410dpKrN2SnqFjt8n4JL8fDJE0wIgjFQ==}
dev: false dev: false
/defu@6.1.3:
resolution: {integrity: sha512-Vy2wmG3NTkmHNg/kzpuvHhkqeIx3ODWqasgCRbKtbXEN0G+HpEEv9BtJLp7ZG1CZloFaC41Ah3ZFbq7aqCqMeQ==}
dev: false
/delegates@1.0.0: /delegates@1.0.0:
resolution: {integrity: sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==} resolution: {integrity: sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==}
dev: false dev: false
@@ -1424,6 +1424,10 @@ packages:
resolution: {integrity: sha512-M1Ob1zPSIvlARiJUkKqvAZ3VAqQY6Jcuth/pBKQ2b1dX/Qx0OnJ8Vux6J2H5PTMQeRzWrrbTu70VxBfv/OPDJA==} resolution: {integrity: sha512-M1Ob1zPSIvlARiJUkKqvAZ3VAqQY6Jcuth/pBKQ2b1dX/Qx0OnJ8Vux6J2H5PTMQeRzWrrbTu70VxBfv/OPDJA==}
dev: false dev: false
/destr@2.0.2:
resolution: {integrity: sha512-65AlobnZMiCET00KaFFjUefxDX0khFA/E4myqZ7a6Sq1yZtR8+FVIvilVX66vF2uobSumxooYZChiRPCKNqhmg==}
dev: false
/destroy@1.2.0: /destroy@1.2.0:
resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
@@ -2184,15 +2188,15 @@ packages:
duplexer: 0.1.2 duplexer: 0.1.2
dev: false dev: false
/h3@1.8.1: /h3@1.9.0:
resolution: {integrity: sha512-m5rFuu+5bpwBBHqqS0zexjK+Q8dhtFRvO9JXQG0RvSPL6QrIT6vv42vuBM22SLOgGMoZYsHk0y7VPidt9s+nkw==} resolution: {integrity: sha512-+F3ZqrNV/CFXXfZ2lXBINHi+rM4Xw3CDC5z2CDK3NMPocjonKipGLLDSkrqY9DOrioZNPTIdDMWfQKm//3X2DA==}
dependencies: dependencies:
cookie-es: 1.0.0 cookie-es: 1.0.0
defu: 6.1.2 defu: 6.1.3
destr: 2.0.1 destr: 2.0.2
iron-webcrypto: 0.8.2 iron-webcrypto: 1.0.0
radix3: 1.1.0 radix3: 1.1.0
ufo: 1.3.0 ufo: 1.3.2
uncrypto: 0.1.3 uncrypto: 0.1.3
unenv: 1.7.4 unenv: 1.7.4
dev: false dev: false
@@ -2334,8 +2338,8 @@ packages:
- supports-color - supports-color
dev: false dev: false
/iron-webcrypto@0.8.2: /iron-webcrypto@1.0.0:
resolution: {integrity: sha512-jGiwmpgTuF19Vt4hn3+AzaVFGpVZt7A1ysd5ivFel2r4aNVFwqaYa6aU6qsF1PM7b+WFivZHz3nipwUOXaOnHg==} resolution: {integrity: sha512-anOK1Mktt8U1Xi7fCM3RELTuYbnFikQY5VtrDj7kPgpejV7d43tWKhzgioO0zpkazLEL/j/iayRqnJhrGfqUsg==}
dev: false dev: false
/is-array-buffer@3.0.2: /is-array-buffer@3.0.2:
@@ -2537,6 +2541,10 @@ packages:
hasBin: true hasBin: true
dev: false dev: false
/jose@5.2.0:
resolution: {integrity: sha512-oW3PCnvyrcm1HMvGTzqjxxfnEs9EoFOFWi2HsEGhlFVOXxTE3K9GKWVMFoFw06yPUqwpvEWic1BmtUZBI/tIjw==}
dev: false
/js-yaml@4.1.0: /js-yaml@4.1.0:
resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==}
hasBin: true hasBin: true
@@ -2615,7 +2623,7 @@ packages:
consola: 3.2.3 consola: 3.2.3
defu: 6.1.2 defu: 6.1.2
get-port-please: 3.1.1 get-port-please: 3.1.1
h3: 1.8.1 h3: 1.9.0
http-shutdown: 1.2.2 http-shutdown: 1.2.2
jiti: 1.20.0 jiti: 1.20.0
mlly: 1.4.2 mlly: 1.4.2
@@ -2834,7 +2842,7 @@ packages:
fs-extra: 11.1.1 fs-extra: 11.1.1
globby: 13.2.2 globby: 13.2.2
gzip-size: 7.0.0 gzip-size: 7.0.0
h3: 1.8.1 h3: 1.9.0
hookable: 5.5.3 hookable: 5.5.3
httpxy: 0.1.5 httpxy: 0.1.5
is-primitive: 3.0.1 is-primitive: 3.0.1
@@ -3778,6 +3786,10 @@ packages:
resolution: {integrity: sha512-bRn3CsoojyNStCZe0BG0Mt4Nr/4KF+rhFlnNXybgqt5pXHNFRlqinSoQaTrGyzE4X8aHplSb+TorH+COin9Yxw==} resolution: {integrity: sha512-bRn3CsoojyNStCZe0BG0Mt4Nr/4KF+rhFlnNXybgqt5pXHNFRlqinSoQaTrGyzE4X8aHplSb+TorH+COin9Yxw==}
dev: false dev: false
/ufo@1.3.2:
resolution: {integrity: sha512-o+ORpgGwaYQXgqGDwd+hkS4PuZ3QnmqMMxRuajK/a38L6fTpcE5GPIfrf+L/KemFzfUpeUQc1rRS1iDBozvnFA==}
dev: false
/unbox-primitive@1.0.2: /unbox-primitive@1.0.2:
resolution: {integrity: sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==} resolution: {integrity: sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==}
dependencies: dependencies:
@@ -3890,7 +3902,7 @@ packages:
anymatch: 3.1.3 anymatch: 3.1.3
chokidar: 3.5.3 chokidar: 3.5.3
destr: 2.0.1 destr: 2.0.1
h3: 1.8.1 h3: 1.9.0
ioredis: 5.3.2 ioredis: 5.3.2
listhen: 1.5.1 listhen: 1.5.1
lru-cache: 10.0.1 lru-cache: 10.0.1

View File

@@ -2,7 +2,7 @@ import { getBodyBuffer } from '@/utils/body';
import { import {
getProxyHeaders, getProxyHeaders,
getAfterResponseHeaders, getAfterResponseHeaders,
cleanupHeadersBeforeProxy, getBlacklistedHeaders,
} from '@/utils/headers'; } from '@/utils/headers';
import { import {
createTokenIfNeeded, createTokenIfNeeded,
@@ -39,8 +39,8 @@ export default defineEventHandler(async (event) => {
const token = await createTokenIfNeeded(event); const token = await createTokenIfNeeded(event);
// proxy // proxy
cleanupHeadersBeforeProxy(event); await specificProxyRequest(event, destination, {
await proxyRequest(event, destination, { blacklistedHeaders: getBlacklistedHeaders(),
fetchOptions: { fetchOptions: {
redirect: 'follow', redirect: 'follow',
headers: getProxyHeaders(event.headers), headers: getProxyHeaders(event.headers),

View File

@@ -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 = [ const blacklistedHeaders = [
'cf-connecting-ip', 'cf-connecting-ip',
@@ -11,6 +17,7 @@ const blacklistedHeaders = [
'x-forwarded-proto', 'x-forwarded-proto',
'forwarded', 'forwarded',
'x-real-ip', 'x-real-ip',
...Object.keys(headerMap),
]; ];
function copyHeader( function copyHeader(
@@ -26,20 +33,16 @@ function copyHeader(
export function getProxyHeaders(headers: Headers): Headers { export function getProxyHeaders(headers: Headers): Headers {
const output = new Headers(); const output = new Headers();
const headerMap: Record<string, string> = { // default user agent
'X-Cookie': 'Cookie',
'X-Referer': 'Referer',
'X-Origin': 'Origin',
};
Object.entries(headerMap).forEach((entry) => {
copyHeader(headers, output, entry[0], entry[1]);
});
output.set( output.set(
'User-Agent', 'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0', '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; return output;
} }
@@ -60,14 +63,6 @@ export function getAfterResponseHeaders(
}; };
} }
export function removeHeadersFromEvent(event: H3Event, key: string) { export function getBlacklistedHeaders() {
const normalizedKey = key.toLowerCase(); return blacklistedHeaders;
if (event.node.req.headers[normalizedKey])
delete event.node.req.headers[normalizedKey];
}
export function cleanupHeadersBeforeProxy(event: H3Event) {
blacklistedHeaders.forEach((key) => {
removeHeadersFromEvent(event, key);
});
} }

84
src/utils/proxy.ts Normal file
View File

@@ -0,0 +1,84 @@
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,
);
(fetchHeaders.forEach as any)(console.log);
return sendProxy(event, target, {
...opts,
fetchOptions: {
method,
body,
duplex,
...opts.fetchOptions,
headers: fetchHeaders,
},
});
}

View File

@@ -1,5 +1,5 @@
import { H3Event, EventHandlerRequest } from 'h3'; import { H3Event, EventHandlerRequest } from 'h3';
import jsonwebtoken from '@tsndr/cloudflare-worker-jwt'; import { SignJWT, jwtVerify } from 'jose';
import { getIp } from '@/utils/ip'; import { getIp } from '@/utils/ip';
const turnstileSecret = process.env.TURNSTILE_SECRET ?? null; const turnstileSecret = process.env.TURNSTILE_SECRET ?? null;
@@ -15,13 +15,10 @@ export function isTurnstileEnabled() {
export async function makeToken(ip: string) { export async function makeToken(ip: string) {
if (!jwtSecret) throw new Error('Cannot make token without a secret'); if (!jwtSecret) throw new Error('Cannot make token without a secret');
return await jsonwebtoken.sign( return await new SignJWT({ ip })
{ .setProtectedHeader({ alg: 'HS256' })
ip, .setExpirationTime('10m')
exp: Math.floor(Date.now() / 1000) + 60 * 10, // 10 Minutes .sign(new TextEncoder().encode(jwtSecret));
},
jwtSecret,
);
} }
export function setTokenHeader( export function setTokenHeader(
@@ -54,13 +51,19 @@ export async function isAllowedToMakeRequest(
if (token.startsWith(jwtPrefix)) { if (token.startsWith(jwtPrefix)) {
const jwtToken = token.slice(jwtPrefix.length); const jwtToken = token.slice(jwtPrefix.length);
const isValid = await jsonwebtoken.verify(jwtToken, jwtSecret, { let jwtPayload: { ip: string } | null = null;
algorithm: 'HS256', try {
}); const jwtResult = await jwtVerify<{ ip: string }>(
if (!isValid) return false; jwtToken,
const jwtBody = jsonwebtoken.decode<{ ip: string }>(jwtToken); new TextEncoder().encode(jwtSecret),
if (!jwtBody.payload) return false; {
if (getIp(event) !== jwtBody.payload.ip) return false; algorithms: ['HS256'],
},
);
jwtPayload = jwtResult.payload;
} catch {}
if (!jwtPayload) return false;
if (getIp(event) !== jwtPayload.ip) return false;
return true; return true;
} }