export async function onRequest(context) { const url = new URL(context.request.url); const code = url.searchParams.get("code"); const returnedState = url.searchParams.get("state"); const error = url.searchParams.get("error"); if (error) { return new Response( `
Deriv authorization was cancelled or failed.
`, { status: 400, headers: { "Content-Type": "text/html" } } ); } if (!code || !returnedState) { return new Response( "Missing authorization code or state.
", { status: 400, headers: { "Content-Type": "text/html" } } ); } const cookies = context.request.headers.get("Cookie") || ""; const getCookie = (name) => { const match = cookies.match( new RegExp("(^|;\\s*)" + name + "=([^;]*)") ); return match ? decodeURIComponent(match[2]) : null; }; const savedState = getCookie("dt_oauth_state"); const codeVerifier = getCookie("dt_pkce_verifier"); if (!savedState || !codeVerifier) { return new Response( "OAuth session information is missing.
", { status: 400, headers: { "Content-Type": "text/html" } } ); } if (returnedState !== savedState) { return new Response( "State verification failed.
", { status: 400, headers: { "Content-Type": "text/html" } } ); } const clientId = "347btQbpUS2La9uhcLb2X"; const redirectUri = "https://dollarticks.pages.dev/callback"; const tokenResponse = await fetch( "https://auth.deriv.com/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, code, code_verifier: codeVerifier, redirect_uri: redirectUri }) } ); const tokenData = await tokenResponse.json(); if (!tokenResponse.ok || !tokenData.access_token) { return new Response( `Deriv authorization could not be completed.
Please try again.
`, { status: 400, headers: { "Content-Type": "text/html" } } ); } /* * Store the OAuth token in an HttpOnly cookie. * JavaScript in index.html cannot read this cookie. * The Cloudflare backend can use it for authenticated * Deriv API requests. */ const tokenCookie = `dt_access_token=${encodeURIComponent(tokenData.access_token)}; ` + `Path=/; Max-Age=${Math.min(tokenData.expires_in || 3600, 3600)}; ` + `Secure; HttpOnly; SameSite=Lax`; const clearStateCookie = "dt_oauth_state=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Lax"; const clearVerifierCookie = "dt_pkce_verifier=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Lax"; return new Response( `Deriv account connected successfully.
`, { headers: { "Content-Type": "text/html", "Set-Cookie": `${tokenCookie}, ${clearStateCookie}, ${clearVerifierCookie}` } } ); }