Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- addEventListener('fetch', function(event) {
- const { request } = event;
- const response = handleRequest(request).catch(handleError);
- event.respondWith(response);
- })
- /**
- * Receives a HTTP request and replies with a response.
- * @param {Request} request
- * @returns {Promise<Response>}
- */
- var iptbl={};
- async function handleRequest(request) {
- const { method, url } = request;
- var hedr=request.headers;
- const { host, pathname } = new URL(url);
- switch (pathname) {
- case '/time':
- return respondTime(request);
- case '/echo':
- return respondEcho(request);
- case '/favicon.ico':
- case '/robots.txt':
- return new Response(null, { status: 204 });
- }
- // Workers on these hostnames have no origin server,
- // therefore there is nothing else to be found
- //?
- /*
- if (host.endsWith('.workers.dev')
- || host.endsWith('.cloudflareworkers.com')) {
- return new Response('Not Found', { status: 404 })
- }
- */
- //ip request limtis 2 requests every 3 seconds
- var rmip=request.headers.get("CF-Connecting-IP"),
- lcrt_=rmip in iptbl?iptbl[rmip].pop():(iptbl[rmip]=[1])[0],cst_=(new Date()).getTime();
- iptbl[rmip].unshift(cst_);
- if(cst_-lcrt_<3000) return new Response("Error, exeeds the 2-requests-per-3-seconds limit.",
- { status: 503, headers:{"Access-Control-Allow-Origin":"*"}});
- if(pathname.startsWith("/proxy/")){
- //begin cors proxy code
- var prespon,mrespon,chd;
- if(request.method=="OPTIONS"){ //ug options
- if(chd=request.headers.get("access-control-request-headers"))chd=", "+chd;
- prespon=["You will run out of options.",
- { status: 200, headers:{"Access-Control-Allow-Headers":"Authorization, Content-Type"+chd} }
- ];
- }else if(pathname.length<15){
- return new Response(`Error no target url.
- Please put the url you want to access through
- this proxy immediately following /proxy/ in this server url.
- example: https://${host}/proxy/https://www.example.com `
- ,{status:400});
- }else if(!request.headers.has("X-Requested-With")){
- return new Response(`Error the X-Requested-With header must be set in the
- request headers`
- ,{status:400});
- }else if(pathname.indexOf(host)+1){
- return new Response(`Error, proxy requesting the proxy server is not allowed.`
- ,{status:400});
- }else{
- var rinit={
- headers:new Headers(),
- method:request.method
- };
- var val,reqh=request.headers,rinh=rinit.headers,
- xnope=["x-nope","host"];
- if(reqh.has("X-Nope"))xnope=xnope.concat(reqh.get("X-Nope").split(","));
- for(let h in reqh.keys()){
- val=reqh.get(h);
- if(h.startsWith("x-a-")) rinh.set(h.substr(4),val);
- else if(!(rinh.has(h)||xnope.indexOf(h.toLowerCase())+1)) rinh.set(h,val);
- }
- if(request.bodyUsed) rinit.body=request.body;
- //actually do the proxy:
- mrespon=await fetch(url.substr(url.indexOf("/proxy/")+7), rinit);
- prespon=[mrespon.body,{status:mrespon.status,headers:Object.fromEntries([...mrespon.headers])}];
- }
- prespon[1].headers["Access-Control-Allow-Origin"]="*";
- prespon[1].headers["Access-Control-Allow-Methods"]="GET, POST, PUT, PATCH, DELETE, UPLOAD";
- return new Response(prespon[0],prespon[1]);
- //return new Response(JSON.stringify( prespon ),{status:200});
- //end cors proxy code
- }
- return new Response(`corsh: CORS Hack.
- A cors proxy that lets you set forbidden headers.
- useage https://${host}/proxy/https://www.example.com
- requests must set the "x-requested-with" header
- prefix forbidden headers with x-a-
- example: x-a-orgin: https://www.example.com
- also use the header x-nope, to omit request headers
- from the request.
- example: "x-nope: CF-Connecting-IP,Cookie"
- `,
- { status: 200 });
- }
- /**
- * Responds with an uncaught error.
- * @param {Error} error
- * @returns {Response}
- */
- function handleError(error) {
- console.error('Uncaught error:', error);
- const { stack } = error;
- return new Response(stack || error, {
- status: 500,
- headers: {
- 'Content-Type': 'text/plain;charset=UTF-8'
- }
- });
- }
- /**
- * Responds with an echo of a request.
- * @param {Request} request
- * @returns {Promise<Response>}
- */
- async function respondEcho(request) {
- const { url, method, cf } = request;
- const headers = Object.fromEntries([...request.headers]);
- const body = await request.text();
- const echo = { method, url, body, headers, cf };
- const echoBody = JSON.stringify(echo, null, 2);
- return new Response(echoBody, {
- status: 200,
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8',
- 'Cache-Control': 'no-store',
- }
- });
- }
- /**
- * Gets a human-readable description of the local time.
- * @param {string} locale
- * @param {object} cf
- * @returns {string}
- */
- function getTime(locale, cf) {
- // In the preview editor, the 'cf' object will be null.
- // To view the object and its variables: make sure you are logged in,
- // click the "Save and Deploy" button, then open the URL in a new tab.
- const { city, region, country, timezone: timeZone } = cf || {};
- const localTime = new Date().toLocaleTimeString(locale, { timeZone });
- const location = [city, region, country].filter(Boolean).join(', ');
- return timeZone
- ? 'The local time in ' + location + ' is ' + localTime
- : 'The UTC time is ' + localTime;
- }
- /**
- * Responds with the local time.
- * @param {Request} request
- * @returns {Response}
- */
- function respondTime(request) {
- const { headers, cf } = request;
- const locale = (headers.get('Accept-Language') || 'en-US').split(',')[0];
- const body = getTime(locale, cf);
- return new Response(body, {
- status: 200,
- headers: {
- 'Content-Type': 'text/plain;charset=UTF-8',
- 'Content-Language': locale
- }
- });
- }
Add Comment
Please, Sign In to add comment