Initial setup

This commit is contained in:
Isra 2023-09-08 22:59:05 -05:00
parent c5233b7088
commit 883078fdbc
14 changed files with 6383 additions and 56 deletions

View File

@ -3,13 +3,5 @@ root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.js]
indent_style = space
indent_size = 2
[{package.json,*.yml,*.cjson}]
indent_style = space
indent_size = 2

View File

@ -1,5 +0,0 @@
{
"extends": [
"@nuxtjs/eslint-config-typescript"
]
}

52
.eslintrc.js Normal file
View File

@ -0,0 +1,52 @@
module.exports = {
env: {
browser: true,
},
extends: [
"airbnb",
"airbnb/hooks",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
],
ignorePatterns: ["public/*", "dist/*", "/*.js", "/*.ts"],
parser: "@typescript-eslint/parser",
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: "./",
},
settings: {
"import/resolver": {
typescript: {
project: "./tsconfig.json",
},
},
},
plugins: ["@typescript-eslint", "import", "prettier"],
rules: {
"no-underscore-dangle": "off",
"@typescript-eslint/no-explicit-any": "off",
"no-console": "off",
"@typescript-eslint/no-this-alias": "off",
"import/prefer-default-export": "off",
"@typescript-eslint/no-empty-function": "off",
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"],
"no-restricted-syntax": "off",
"import/no-unresolved": ["error", { ignore: ["^virtual:"] }],
"consistent-return": "off",
"no-continue": "off",
"no-eval": "off",
"no-await-in-loop": "off",
"no-nested-ternary": "off",
"prefer-destructuring": "off",
"@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }],
"import/extensions": [
"error",
"ignorePackages",
{
ts: "never",
tsx: "never",
},
]
},
}

18
.github/workflows/cloudflare.yml vendored Normal file
View File

@ -0,0 +1,18 @@
# Docs: https://github.com/marketplace/actions/deploy-to-cloudflare-workers-with-wrangler
name: Deploy Worker
on:
push:
pull_request:
repository_dispatch:
jobs:
deploy:
runs-on: ubuntu-latest
timeout-minutes: 60
needs: test
steps:
- uses: actions/checkout@v2
- name: Build & Deploy Worker
uses: cloudflare/wrangler-action@2.0.0
with:
apiToken: ${{ secrets.CF_API_TOKEN }}
accountId: ${{ secrets.CF_ACCOUNT_ID }}

2
.npmrc
View File

@ -1,2 +0,0 @@
shamefully-hoist=true
strict-peer-dependencies=false

3
.prettierrc.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
trailingComma: "all",
};

View File

@ -1,42 +1,15 @@
# Nitro Minimal Starter
# CORS proxy
Look at the [Nitro documentation](https://nitro.unjs.io/) to learn more.
A CORS proxy used to bypass the CORS policy within the [movie-web](https://movie-web.app) app.
## Setup
## Deployment
Make sure to install the dependencies:
Because [Nitro](https://nitro.unjs.io/) allows users to servers on multiple runtimes, we have provided a few buttons to help you deploy this example to your favorite provider. However, [Cloudflare workers](https://workers.cloudflare.com/) remain the recommended option because of their large IP range and generous free tier.
```bash
# npm
npm install
For more information on how to deploy this example to your provider of choice, please refer to the [Nitro documentation](https://nitro.unjs.io/docs/deployment).
# yarn
yarn install
[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/movie-web/simple-proxy)
# pnpm
pnpm install
```
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fmovie-web%2Fsimple-proxy)
## Development Server
Start the development server on <http://localhost:3000>
```bash
npm run dev
```
## Production
Build the application for production:
```bash
npm run build
```
Locally preview production build:
```bash
npm run preview
```
Check out the [deployment documentation](https://nitro.unjs.io/deploy) for more information.
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/movie-web/simple-proxy)

View File

@ -1,2 +1,4 @@
//https://nitro.unjs.io/config
export default defineNitroConfig({});
export default defineNitroConfig({
noPublicDir: true,
});

5880
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -8,5 +8,12 @@
},
"dependencies": {
"nitropack": "latest"
},
"devDependencies": {
"eslint": "^8.48.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.0.0",
"prettier": "^3.0.3",
"typescript": "^5.2.2"
}
}
}

View File

@ -1,3 +1,214 @@
export default eventHandler(() => {
return { nitro: 'Is Awesome!' }
})
import {
defineEventHandler,
EventHandlerRequest,
readBody,
getQuery,
isMethod,
H3Event,
} from 'h3';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
'Access-Control-Max-Age': '86400',
};
async function handleRequest(
requestData: {
headers: Headers;
method: string;
body: any;
destination: string;
},
iteration = 0,
): Promise<Response> {
console.log(
`PROXYING ${requestData.destination}${
iteration ? ' ON ITERATION ' + iteration : ''
}`,
);
// Create a new mutable request object for the destination
const request = new Request(requestData.destination, {
headers: requestData.headers,
method: requestData.method,
body: requestData.body,
});
request.headers.set('Origin', new URL(requestData.destination).origin);
// TODO: Make cookie handling better. PHPSESSID overwrites all other cookie related headers
// Add custom X headers from client
// These headers are usually forbidden to be set by fetch
const cookieValue = request.headers.get('X-Cookie');
if (cookieValue) {
request.headers.set('Cookie', cookieValue);
request.headers.delete('X-Cookie');
}
const refererValue = request.headers.get('X-Referer');
if (refererValue) {
request.headers.set('Referer', refererValue);
request.headers.delete('X-Referer');
}
const originValue = request.headers.get('X-Origin');
if (originValue) {
request.headers.set('Origin', originValue);
request.headers.delete('X-Origin');
}
// Set PHPSESSID cookie
if (request.headers.get('PHPSESSID')) {
request.headers.set(
'Cookie',
`PHPSESSID=${request.headers.get('PHPSESSID')}`,
);
}
// Set User Agent, if not exists
const userAgent = request.headers.get('User-Agent');
if (!userAgent) {
request.headers.set(
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0',
);
}
// Fetch the new resource
const oResponse = await fetch(request.clone());
// If the server returned a redirect, follow it
const locationValue = oResponse.headers.get('location');
if ((oResponse.status === 302 || oResponse.status === 301) && locationValue) {
// Server tried to redirect too many times
if (iteration > 5) {
return new Response('418 Too many redirects', {
status: 418,
});
}
// Handle and return the request for the redirected destination
return await handleRequest(
{
headers: oResponse.headers,
method: requestData.method,
body: requestData.body,
destination: locationValue,
},
iteration + 1,
);
}
// Create mutable response using the original response as init
const response = new Response(oResponse.body, oResponse);
// Set CORS headers
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Expose-Headers', '*');
const cookiesToSet = response.headers.get('Set-Cookie');
// Transfer Set-Cookie to X-Set-Cookie
// Normally the Set-Cookie header is not accessible to fetch clients
const setCookieValue = response.headers.get('Set-Cookie');
if (cookiesToSet && setCookieValue) {
response.headers.set('X-Set-Cookie', setCookieValue);
}
// Set PHPSESSID cookie
if (
cookiesToSet &&
cookiesToSet.includes('PHPSESSID') &&
cookiesToSet.includes(';')
) {
let phpsessid = cookiesToSet.slice(cookiesToSet.search('PHPSESSID') + 10);
phpsessid = phpsessid.slice(0, phpsessid.search(';'));
response.headers.set('PHPSESSID', phpsessid);
}
// Append to/Add Vary header so browser will cache response correctly
response.headers.append('Vary', 'Origin');
// Add X-Final-Destination header to get the final url
response.headers.set('X-Final-Destination', oResponse.url);
return response;
}
function handleOptions(request: H3Event<EventHandlerRequest>) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
const headers = request.headers;
let response = new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
});
if (
headers.get('Origin') !== null &&
headers.get('Access-Control-Request-Method') !== null &&
headers.get('Access-Control-Request-Headers') !== null
) {
let accessControlRequestValue = headers.get(
'Access-Control-Request-Headers',
);
response = new Response(null, {
headers: {
...corsHeaders,
// Allow all future content Request headers to go back to browser
// such as Authorization (Bearer) or X-Client-Name-Version
accessControlRequestValue: accessControlRequestValue || '',
},
});
}
return response;
}
export default defineEventHandler(async (event) => {
const destination = getQuery(event).destination;
let response = new Response('404 Not Found', {
status: 404,
});
let body;
try {
body = await readBody(event);
} catch {
body = null;
}
if (isMethod(event, 'OPTIONS')) {
// Handle CORS preflight requests
response = handleOptions(event);
} else if (!destination?.toString()) {
response = new Response('200 OK', {
status: 200,
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Origin': '*',
},
});
} else if (
isMethod(event, 'GET') ||
isMethod(event, 'HEAD') ||
isMethod(event, 'POST')
) {
// Handle request
response = await handleRequest({
headers: event.headers,
method: event.method,
destination: destination.toString(),
body,
});
}
return response;
});

173
routes/worker.js.txt Normal file
View File

@ -0,0 +1,173 @@
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
'Access-Control-Max-Age': '86400',
};
function handleRequest(oRequest, destination, iteration = 0) {
console.log(
`PROXYING ${destination}${iteration ? ' ON ITERATION ' + iteration : ''}`,
);
// Create a new mutable request object for the destination
const request = new Request(destination, oRequest);
request.headers.set('Origin', new URL(destination).origin);
// TODO - Make cookie handling better. PHPSESSID overwrites all other cookie related headers
// Add custom X headers from client
// These headers are usually forbidden to be set by fetch
if (oRequest.headers.has('X-Cookie')) {
request.headers.set('Cookie', oRequest.headers.get('X-Cookie'));
request.headers.delete('X-Cookie');
}
if (request.headers.has('X-Referer')) {
request.headers.set('Referer', request.headers.get('X-Referer'));
request.headers.delete('X-Referer');
}
if (request.headers.has('X-Origin')) {
request.headers.set('Origin', request.headers.get('X-Origin'));
request.headers.delete('X-Origin');
}
// Set PHPSESSID cookie
if (request.headers.get('PHPSESSID')) {
request.headers.set(
'Cookie',
`PHPSESSID=${request.headers.get('PHPSESSID')}`,
);
}
// Set User Agent, if not exists
const useragent = request.headers.get('User-Agent');
if (!useragent) {
request.headers.set(
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0',
);
}
// Fetch the new resource
const oResponse = await fetch(request.clone());
// If the server returned a redirect, follow it
if (
(oResponse.status === 302 || oResponse.status === 301) &&
oResponse.headers.get('location')
) {
// Server tried to redirect too many times
if (iteration > 5) {
return new Response('418 Too many redirects', {
status: 418,
});
}
// Handle and return the request for the redirected destination
return await handleRequest(
request,
oResponse.headers.get('location'),
iteration + 1,
);
}
// Create mutable response using the original response as init
const response = new Response(oResponse.body, oResponse);
// Set CORS headers
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Expose-Headers', '*');
const cookiesToSet = response.headers.get('Set-Cookie');
// Transfer Set-Cookie to X-Set-Cookie
// Normally the Set-Cookie header is not accessible to fetch clients
if (cookiesToSet) {
response.headers.set('X-Set-Cookie', response.headers.get('Set-Cookie'));
}
// Set PHPSESSID cookie
if (
cookiesToSet &&
cookiesToSet.includes('PHPSESSID') &&
cookiesToSet.includes(';')
) {
let phpsessid = cookiesToSet.slice(cookiesToSet.search('PHPSESSID') + 10);
phpsessid = phpsessid.slice(0, phpsessid.search(';'));
response.headers.set('PHPSESSID', phpsessid);
}
// Append to/Add Vary header so browser will cache response correctly
response.headers.append('Vary', 'Origin');
// Add X-Final-Destination header to get the final url
response.headers.set('X-Final-Destination', oResponse.url);
return response;
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
const headers = request.headers;
let response = new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
});
if (
headers.get('Origin') !== null &&
headers.get('Access-Control-Request-Method') !== null &&
headers.get('Access-Control-Request-Headers') !== null
) {
response = new Response(null, {
headers: {
...corsHeaders,
// Allow all future content Request headers to go back to browser
// such as Authorization (Bearer) or X-Client-Name-Version
'Access-Control-Allow-Headers': request.headers.get(
'Access-Control-Request-Headers',
),
},
});
}
return response;
}
addEventListener('fetch', (event) => {
const request = event.request;
const url = new URL(request.url);
const destination = url.searchParams.get('destination');
console.log(`HTTP ${request.method} - ${request.url}`);
let response = new Response('404 Not Found', {
status: 404,
});
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
response = handleOptions(request);
} else if (!destination) {
response = new Response('200 OK', {
status: 200,
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Origin': '*',
},
});
} else if (
request.method === 'GET' ||
request.method === 'HEAD' ||
request.method === 'POST'
) {
// Handle request
response = handleRequest(request, destination);
}
event.respondWith(response);
});

View File

@ -1,3 +1,22 @@
{
"extends": "./.nitro/types/tsconfig.json"
"compilerOptions": {
"target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"baseUrl": "./src",
"paths": {
"@/*": ["./*"]
}
},
}

4
wrangler.toml Normal file
View File

@ -0,0 +1,4 @@
name = "playground"
main = "./.output/server/index.mjs"
workers_dev = true
compatibility_date = "2022-09-10"