Code पाहा
// Falcon proxy — Cloudflare Worker (मोफत)
// ----------------------------------------
// Upstox browser मधून थेट call करू देत नाही (CORS). हा छोटा Worker Falcon आणि Upstox
// च्या मध्ये बसतो आणि फक्त Upstox चे data (GET) पुढे पाठवतो.
// - फक्त api.upstox.com आणि assets.upstox.com ला जातो; दुसरीकडे कुठेही नाही.
// - Token कुठेही साठवत नाही; फक्त तुमच्या request सोबत Upstox ला पुढे पाठवतो.
// - हा Worker तुमच्याच Cloudflare account मध्ये चालतो.
//
// Falcon मध्ये "Proxy address" मध्ये या Worker चा URL टाका, उदा.
// https://falcon-proxy.तुमचं-नाव.workers.dev
const ROUTES = [
['/upstox-assets/', 'https://assets.upstox.com/'],
['/upstox/', 'https://api.upstox.com/'],
];
const CORS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'authorization, accept, content-type',
'Access-Control-Max-Age': '86400',
};
export default {
async fetch(request) {
const url = new URL(request.url);
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS });
if (request.method !== 'GET') return new Response('Only GET', { status: 405, headers: CORS });
if (url.pathname === '/upstox-ok') return new Response('ok', { headers: { ...CORS, 'Content-Type': 'text/plain' } });
const route = ROUTES.find(([prefix]) => url.pathname.startsWith(prefix));
if (!route) {
return new Response('Falcon proxy चालू आहे ✅', { headers: { ...CORS, 'Content-Type': 'text/plain; charset=utf-8' } });
}
const target = route[1] + url.pathname.slice(route[0].length) + url.search;
const isAssets = route[0] === '/upstox-assets/';
const headers = new Headers({
// काही servers User-Agent नसलेल्या requests ना 403 देतात, म्हणून browser सारखा UA
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36',
'Accept': request.headers.get('accept') || (isAssets ? '*/*' : 'application/json'),
});
// token फक्त api.upstox.com ला; assets (stocks ची यादी) ला token पाठवत नाही
const auth = request.headers.get('authorization');
if (auth && !isAssets) headers.set('Authorization', auth);
let upstream;
try {
upstream = await fetch(target, { headers, cf: { cacheTtl: isAssets ? 3600 : 0 } });
} catch (e) {
return new Response(JSON.stringify({ status: 'error', errors: [{ message: 'Upstox पर्यंत पोहोचता आलं नाही: ' + e }] }),
{ status: 502, headers: { ...CORS, 'Content-Type': 'application/json' } });
}
const out = new Headers(upstream.headers);
for (const [k, v] of Object.entries(CORS)) out.set(k, v);
out.delete('set-cookie');
out.delete('content-encoding'); // body आधीच उघडलेला असतो; Falcon दोन्ही प्रकार ओळखतो
out.delete('content-length');
return new Response(upstream.body, { status: upstream.status, headers: out });
},
};