Skip to content

Commit

Permalink
Implemented the redirector
Browse files Browse the repository at this point in the history
  • Loading branch information
4r7if3x committed Jun 12, 2024
1 parent 1bedb8c commit 0da5ade
Showing 1 changed file with 66 additions and 15 deletions.
81 changes: 66 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,69 @@
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `npm run deploy` to publish your worker
*
* Bind resources to your worker in `wrangler.toml`. After adding bindings, a type definition for the
* `Env` object can be regenerated with `npm run cf-typegen`.
*
* Learn more at https://developers.cloudflare.com/workers/
*/
interface Headers {
[key: string]: string;
}

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response('Hello World!');
},
async fetch(
request: Request,
// @ts-ignore
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const referer = request.headers.get('Referer');

let headers: Headers = {
// 'Link': '<data:>; rel=icon', // it doesn't work
'Content-Security-Policy': "default-src 'self'; img-src 'none';", // disable favicon requests
'X-Robots-Tag': 'noindex, nofollow, noarchive, nosnippet'
};

if (referer) {
try {
const url = new URL(request.url);
const destination = url.pathname;

const refererUrl = new URL(referer);
const hostname = refererUrl.hostname;
let path = refererUrl.pathname

if (url.searchParams.has('base')) {
switch (url.searchParams.get('base')) {
case 'root':
path = '';
break;
case 'path':
path = refererUrl.pathname;
break;
case 'repo':
path = refererUrl.pathname.split("/", 3).join("/");
break;
default:
return new Response('Invalid base option', { status: 400 });
}
} else {
switch (hostname) {
case 'github.com':
path = refererUrl.pathname.split("/", 3).join("/");
break;
}
}

const targetUrl = `https://${hostname}${path}${destination}`;
headers = {
...headers,
'Location': targetUrl,
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
'Surrogate-Control': 'no-store',
'Pragma': 'no-cache',
'Expires': '0'
};

return new Response(null, { status: 302, headers });
} catch (error) {
return new Response('Invalid referer URL', { status: 400, headers });
}
} else {
return new Response('Referer header is missing or invalid', { status: 400, headers });
}
}
};

0 comments on commit 0da5ade

Please sign in to comment.