import {submitAppeal} from './appeals'; import {accountConfig, accountSession, accountToken, verifiedAccount, type AccountConfig} from './accounts'; import {optimizedAssets} from './optimized-assets'; import { wakeRender } from './relay-wake'; import { renderWispUpgrade } from './wisp'; import { assertSameOrigin, ProxyError, validateTarget } from "./policy"; import { authenticated, unlock } from "./session"; import { relayHttp, relayWebSocket } from "./relay"; import { renderRelayHttp, useRenderRelay, type RenderConfig } from "./render"; import { jimmyRelayHttp, useJimmyRelay, type JimmyConfig } from "./jimmy"; export default { async fetch(request, env, ctx): Promise { const accounts = env as Env & AccountConfig; const allowed = async () => accounts.AUTH_MODE === 'accounts' ? (await verifiedAccount(accounts, accountToken(request)))?.status === 'approved' : authenticated(request, env.PROXY_PASSWORD); const path = new URL(request.url).pathname; // Public test fixture is opt-in on loopback only; production's allowed hosts do not change. const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(new URL(request.url).hostname); const allowedHosts = loopback ? env.ALLOWED_HOSTS + ",httpbingo.org" : env.ALLOWED_HOSTS; try { const sourcePath = decodeURIComponent(path); const sourceRoute = sourcePath === '/source' || sourcePath.startsWith('/source/'); const publicSourceFile = ['/source', '/source/', '/source/index.html', '/source/project.html', '/source/LICENSE.txt', '/source/THIRD_PARTY.md.txt', '/source/BUILDING.md.txt', '/source/manifest.json', '/source/corresponding-source.tar.gz'].includes(sourcePath) || sourcePath.startsWith('/source/files/') || sourcePath.startsWith('/source/upstream/'); if (sourceRoute && !publicSourceFile) { return new Response('Not found.', {status:404, headers:{'cache-control':'no-store'}}); } if (path === "/api/account/config") { if (request.method !== 'GET') return new Response(null,{status:405}); return Response.json(accounts.AUTH_MODE === 'accounts' ? {enabled:true,...accountConfig(accounts),google:String(accounts.GOOGLE_AUTH_ENABLED) === 'true'} : {enabled:false},{headers:{'cache-control':'no-store'}}); } if (path === "/api/account/appeal") { if(accounts.AUTH_MODE !== 'accounts')return new Response('Accounts unavailable.',{status:404}); return submitAppeal(request,accounts as Env & AccountConfig & import('./appeals').AppealsConfig); } if (path === "/api/account/session") { assertSameOrigin(request); if (accounts.AUTH_MODE !== 'accounts') return new Response('Accounts are not enabled.',{status:404}); return await accountSession(request,accounts); } if (path === "/admin" || path === "/admin.html") { if (accounts.AUTH_MODE !== 'accounts') return new Response('Not found.',{status:404}); const admin = await verifiedAccount(accounts, accountToken(request)); if (!admin) return new Response(null,{status:303,headers:{location:'/signin','cache-control':'no-store'}}); if (admin.status !== 'approved') return new Response('Forbidden',{status:403,headers:{'cache-control':'no-store'}}); if (!admin.owner) { // Check delegated role through a verified Supabase JWT; cosmetic badges never authorize. const token=accountToken(request); const {url,key}=accountConfig(accounts); const roleResponse=await fetch(url+'/rest/v1/rpc/staff_my_role',{ method:'POST',redirect:'manual', headers:{apikey:key,authorization:'Bearer '+token,'content-type':'application/json'}, body:'{}',signal:AbortSignal.timeout(8000) }); if(!roleResponse.ok)return new Response('Staff authorization unavailable.',{status:503,headers:{'cache-control':'no-store'}}); const role=await roleResponse.json() as string; if(role!=='administrator'&&role!=='moderator') return new Response('Forbidden',{status:403,headers:{'cache-control':'no-store'}}); } if (request.method !== 'GET' && request.method !== 'HEAD') return new Response(null,{status:405,headers:{allow:'GET, HEAD'}}); } if (path === "/api/relay/wake") { assertSameOrigin(request); if(!await allowed())throw new ProxyError(401,"AUTH_REQUIRED","Unlock the relay first."); if(request.method!=="POST")return new Response("Use POST",{status:405}); return wakeRender(env as Env & RenderConfig); } if (path === "/wisp/") { assertSameOrigin(request); if(!await allowed())throw new ProxyError(401,"AUTH_REQUIRED","Unlock the relay first."); return renderWispUpgrade(request,env as Env & RenderConfig); } if (path === "/api/target") { assertSameOrigin(request); if(!await allowed())throw new ProxyError(401,"AUTH_REQUIRED","Unlock the relay first."); const target=validateTarget(new URL(request.url).searchParams.get("url")||"",allowedHosts); return Response.json({allowed:true,host:target.hostname},{headers:{"cache-control":"no-store"}}); } if (path === "/api/session") { assertSameOrigin(request); if (accounts.AUTH_MODE === 'accounts') return await accountSession(request,accounts); if (request.method === "POST") return await unlock(request, env.PROXY_PASSWORD); return Response.json({authenticated: await allowed()}, { headers: {"cache-control": "no-store"}, }); } if (path === "/bare/" || path === "/bare/v3/") { assertSameOrigin(request); if (!await allowed()) { return Response.json({code: "AUTH_REQUIRED", message: "Unlock your proxy from its launch page first."}, { status: 401, headers: {"cache-control": "no-store"}, }); } if (path === "/bare/") return Response.json({ versions: ["v3"], language: "Cloudflare Workers", project: {name: "ZeyadsStuffV2", description: "Private website relay", version: "2.4.0"}, }, {headers: {"cache-control": "no-store"}}); if (request.headers.get("upgrade")?.toLowerCase() === "websocket") return relayWebSocket(request, allowedHosts, ctx); if (!["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].includes(request.method)) { throw new ProxyError(405, "METHOD_NOT_ALLOWED", "Unsupported request method."); } const target = validateTarget(request.headers.get("x-bare-url") ?? "", allowedHosts); const renderConfig = env as Env & RenderConfig; const jimmyConfig = env as Env & JimmyConfig; const render = useRenderRelay(target, renderConfig); const jimmy = useJimmyRelay(target, jimmyConfig); let response: Response; let backend: "jimmy" | "render" | "local" | "cloudflare"; if (jimmy) { try { response = await jimmyRelayHttp(request, target, jimmyConfig); backend = "jimmy"; } catch (error) { // Retrying writes could duplicate effects if Jimmy received the request. // Only fail over read-only methods, and never hide client validation errors. const readOnly = request.method === "GET" || request.method === "HEAD"; if (!render || !readOnly || request.signal.aborted || (error instanceof ProxyError && error.status < 500)) throw error; console.warn(JSON.stringify({ event: "jimmy_relay_fallback", code: error instanceof ProxyError ? error.code : "UPSTREAM_ERROR", })); response = await renderRelayHttp(request, target, renderConfig); backend = "render"; } } else if (render) { response = await renderRelayHttp(request, target, renderConfig); backend = "render"; } else { response = await relayHttp(request, allowedHosts); const hostname = new URL(request.url).hostname; backend = ["localhost", "127.0.0.1", "[::1]"].includes(hostname) ? "local" : "cloudflare"; } // Diagnostic route only; tokens and upstream credentials never leave the Worker. // WebSocket upgrades continue using the Workers relay. response.headers.set("x-relay-backend", backend); return response; } if (path.startsWith("/bare/")) return new Response("Unknown relay route", {status: 404}); if (accounts.AUTH_MODE === 'accounts' && ['/friends','/requests','/library','/friends.html','/requests.html','/library.html','/', '/index.html', '/index.optimized', '/index.optimized.html', '/embed', '/ZeyadsStuffV2.html'].includes(path) && !await allowed()) { return new Response(null, {status:303,headers:{location:'/signin','cache-control':'no-store'}}); } const optimized=optimizedAssets[path]; const acceptsGzip=(request.headers.get('accept-encoding')||'').split(',').some(value=>{const [name,...params]=value.trim().split(';');const q=params.find(p=>p.trim().startsWith('q='));return name.toLowerCase()==='gzip'&&(!q||Number(q.trim().slice(2))>0);}); const compressed=!!optimized&&acceptsGzip; const directoryRoute = path === '/users' || path === '/users/'; const profileRoute = path === '/profile' || /^\/users\/[A-Za-z0-9_]{3,24}\/?$/.test(path); const assetPath=['/friends','/requests','/library'].includes(path)?path+'.html':path === '/signin' ? '/signin.html' : path === '/account' ? '/account.html' : path === '/about' ? '/about.html' : path === '/terms' ? '/terms.html' : path === '/privacy' ? '/privacy.html' : path === '/admin' ? '/admin.html' : compressed?optimized.gzip:directoryRoute?'/people.html':profileRoute?'/profile.html':['/','/index.html','/embed'].includes(path)?'/index.optimized.html':path; const assetRequest=assetPath!==path?new Request(new URL(assetPath,request.url),request):request; const response = await env.ASSETS.fetch(assetRequest); const headers = new Headers(response.headers); if(optimized&&(response.status===200||response.status===304)){ headers.set('content-type',optimized.mime);headers.set('cache-control','public, max-age=31536000, immutable');headers.set('vary','Accept-Encoding'); if(compressed)headers.set('content-encoding','gzip'); } if(['/','/index.html','/embed'].includes(path))headers.set('cache-control','no-cache'); if (path === '/admin' || path === '/admin.html') headers.set('cache-control','no-store'); // Keep the EmulatorJS CDN sandboxed even if the player URL is opened directly. if (path === '/emulatorjs-app.html') headers.set('content-security-policy','sandbox allow-scripts allow-pointer-lock allow-downloads'); headers.set("referrer-policy", "no-referrer"); headers.set("x-content-type-options", "nosniff"); if(path!=="/embed")headers.set("x-frame-options", "SAMEORIGIN"); else {headers.delete("x-frame-options");headers.set("cache-control","no-store");} if (sourceRoute) headers.set('cache-control', 'no-store'); if (path === "/sw.js") { headers.set("service-worker-allowed", "/"); headers.set("cache-control", "no-cache"); } return new Response(response.body, {status: response.status, headers,...(compressed?{encodeBody:"manual" as const}:{})}); } catch (error) { const known = error instanceof ProxyError; if(known)console.warn(JSON.stringify({event:"relay_rejected",code:error.code,status:error.status,message:error.message})); return Response.json({ code: known ? error.code : "UPSTREAM_ERROR", message: known ? error.message : "The upstream connection failed. Retry in a moment.", }, {status: known ? error.status : 502, headers: {"cache-control": "no-store"}}); } }, } satisfies ExportedHandler;