mirror of
https://github.com/movie-web/simple-proxy.git
synced 2025-09-13 17:03:27 +00:00
Compare commits
53 Commits
v2.0.1
...
f3612d4a4e
Author | SHA1 | Date | |
---|---|---|---|
|
f3612d4a4e | ||
|
f0d858460c | ||
|
9d2df30348 | ||
|
0af2174784 | ||
|
b25fc06857 | ||
|
84ac1c6fa1 | ||
|
2d4b1a5848 | ||
|
6097252cf0 | ||
|
3769b37e8a | ||
|
de07b4882b | ||
|
259b7bf1f7 | ||
|
2b77df66ec | ||
|
d907fa36f2 | ||
|
610ac5db2c | ||
|
ddabde15b6 | ||
|
e09decb8e2 | ||
|
440ae9bd2c | ||
|
d0c5a41c69 | ||
|
6bb6914798 | ||
|
f47e4f9ec1 | ||
|
b16ebe48b0 | ||
|
6828e31497 | ||
|
8b26bcf554 | ||
|
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 |
4
.github/workflows/cloudflare.yml
vendored
4
.github/workflows/cloudflare.yml
vendored
@@ -11,7 +11,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install packages
|
||||
|
@@ -14,16 +14,16 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install packages
|
||||
@@ -41,16 +41,16 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install pnpm packages
|
||||
@@ -58,3 +58,17 @@ jobs:
|
||||
|
||||
- name: Build Project
|
||||
run: pnpm build
|
||||
|
||||
docker:
|
||||
name: Build docker
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build
|
||||
uses: docker/build-push-action@v5
|
13
.github/workflows/publish.yml
vendored
13
.github/workflows/publish.yml
vendored
@@ -19,17 +19,17 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Get version
|
||||
id: package-version
|
||||
uses: martinbeentjes/npm-get-version-action@main
|
||||
|
||||
- name: Log into registry ${{ env.REGISTRY }}
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
flavor: |
|
||||
@@ -47,9 +47,12 @@ jobs:
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@v4
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
context: .
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
6
.github/workflows/release.yml
vendored
6
.github/workflows/release.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
@@ -41,13 +41,13 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: v${{ steps.package-version.outputs.current-version }}
|
||||
release_name: Bot v${{ steps.package-version.outputs.current-version }}
|
||||
release_name: Simple-proxy v${{ steps.package-version.outputs.current-version }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
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
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@@ -4,4 +4,5 @@ node_modules
|
||||
.cache
|
||||
.output
|
||||
.env
|
||||
dist
|
||||
dist
|
||||
.netlify
|
||||
|
@@ -1,4 +1,4 @@
|
||||
FROM node:18-alpine as base
|
||||
FROM node:20-alpine as base
|
||||
WORKDIR /app
|
||||
|
||||
# Build layer
|
||||
|
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/introduction
|
||||
|
||||
---
|
||||
|
||||
@@ -10,8 +9,13 @@ 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
|
||||
- AWS lambda
|
||||
- nodejs
|
||||
- netlify edge functions
|
||||
|
4
netlify.toml
Normal file
4
netlify.toml
Normal file
@@ -0,0 +1,4 @@
|
||||
[build]
|
||||
command = "pnpm build:netlify"
|
||||
publish = "."
|
||||
edge_functions = ".netlify"
|
@@ -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")
|
||||
}
|
||||
|
16
package.json
16
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "simple-proxy",
|
||||
"private": true,
|
||||
"version": "2.0.1",
|
||||
"version": "2.1.4",
|
||||
"scripts": {
|
||||
"prepare": "nitropack prepare",
|
||||
"dev": "nitropack dev",
|
||||
@@ -9,14 +9,16 @@
|
||||
"build:cloudflare": "NITRO_PRESET=cloudflare npm run build",
|
||||
"build:aws": "NITRO_PRESET=aws_lambda npm run build",
|
||||
"build:node": "NITRO_PRESET=node-server npm run build",
|
||||
"build:netlify": "NITRO_PRESET=netlify_edge npm run build",
|
||||
"start": "node .output/server/index.mjs",
|
||||
"lint": "eslint --ext .ts src/",
|
||||
"lint:fix": "eslint --fix --ext .ts src/",
|
||||
"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",
|
||||
@@ -25,6 +27,12 @@
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-import-resolver-typescript": "^3.6.0",
|
||||
"eslint-plugin-prettier": "^5.0.0"
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"@rollup/wasm-node": "^4.9.4"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"rollup": "npm:@rollup/wasm-node"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
731
pnpm-lock.yaml
generated
731
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,13 @@ 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
|
||||
@@ -14,26 +19,44 @@ export default defineEventHandler(async (event) => {
|
||||
if (!destination)
|
||||
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),
|
||||
body,
|
||||
},
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
@@ -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,
|
||||
},
|
||||
});
|
||||
}
|
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