Skip to content

Instantly share code, notes, and snippets.

@kLiHz
Last active September 25, 2024 19:33
Show Gist options
  • Save kLiHz/a240216e4f02982477143999879c7e65 to your computer and use it in GitHub Desktop.
Save kLiHz/a240216e4f02982477143999879c7e65 to your computer and use it in GitHub Desktop.
Reverse proxying share.dmhy.org
export default {
/**
* Default fetch event handler
* @param request {Request}
* @param env
* @param ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
const url = new URL(request.url);
// handling direct url revese proxying
// only proxying 'dl.dmhy.org'
if (url.pathname.match(/^\/https?:\/\/dl\.dmhy\.org/)) {
const link = url.pathname.slice(1);
return fetch(link, request);
}
// proxy other requests to 'share.dmhy.org'; don't forget headers (cookies)
const response = await fetch(new URL(url.pathname + url.search, 'https://share.dmhy.org'), request);
// if response is text/html, altering its content
if (response.headers.get('Content-Type')?.includes('text/html')) {
// getting html text
const html = await response.text();
// adding CSP header
const headers = new Headers(response.headers);
headers.set('Content-Security-Policy', `script-src ${url.origin} 'unsafe-inline' 'unsafe-eval' https://js.kiwihk.net/ ; style-src 'self' 'unsafe-inline' https://js.kiwihk.net/ `);
return new Response(
html
// modifying title, adding "no-referrer", adding custom style
.replace(/(<\s*title[^>]*>)([^<]*)(<\/\s*title[^>]*>)/, `$1 (镜像) $2 (Powered by Cloudflare Workers)$3
<meta name="referrer" content="no-referrer" />
<style> img {max-width: 100%;} </style>
`)
// replacing links to / text of (sub-)domains on page
// .replaceAll(/(?<!\.)(?:(?:share\.|www\.)?dmhy\.org)/g, url.host)
// modifying 'dl.dmhy.org' links on page
.replaceAll(/(href=")((?:https?:)?\/\/dl\.dmhy\.org)/g, (_match, p1, p2) => p2.startsWith('//') ? `${p1}/https:${p2}` : `${p1}/${p2}`)
, {
headers,
status: response.status,
}
);
}
return response;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment