|
| 1 | +import { ExecutionContext } from "@cloudflare/workers-types"; |
| 2 | + |
| 3 | +interface Env { |
| 4 | + SENTRY_DSN: string; |
| 5 | +} |
| 6 | + |
| 7 | +interface SentryResponse { |
| 8 | + error?: string; |
| 9 | + message?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export async function onRequestPost({ |
| 13 | + request, |
| 14 | + env, |
| 15 | +}: { |
| 16 | + request: Request; |
| 17 | + env: Env; |
| 18 | +}) { |
| 19 | + try { |
| 20 | + const dsn = new URL(env.SENTRY_DSN); |
| 21 | + const projectId = dsn.pathname.split("/").pop(); |
| 22 | + if (!projectId) { |
| 23 | + throw new Error("Invalid SENTRY_DSN: missing project ID"); |
| 24 | + } |
| 25 | + |
| 26 | + const sentryIngestUrl = `https://${dsn.host}/api/${projectId}/envelope/`; |
| 27 | + |
| 28 | + const newRequest = new Request(sentryIngestUrl, { |
| 29 | + method: "POST", |
| 30 | + headers: { |
| 31 | + "Content-Type": "application/x-sentry-envelope", |
| 32 | + "X-Forwarded-For": request.headers.get("CF-Connecting-IP") || "", |
| 33 | + }, |
| 34 | + body: await request.arrayBuffer(), |
| 35 | + }); |
| 36 | + |
| 37 | + const response = await fetch(newRequest); |
| 38 | + |
| 39 | + return new Response(response.body, { |
| 40 | + status: response.status, |
| 41 | + headers: { |
| 42 | + ...corsHeaders(), |
| 43 | + "Content-Type": "application/x-sentry-envelope", |
| 44 | + }, |
| 45 | + }); |
| 46 | + } catch (error: unknown) { |
| 47 | + console.error("Sentry proxy failed:", error); |
| 48 | + const errorMessage = |
| 49 | + error instanceof Error ? error.message : "Unknown error"; |
| 50 | + return new Response( |
| 51 | + JSON.stringify({ |
| 52 | + error: "Internal server error", |
| 53 | + message: `Failed to proxy Sentry request: ${errorMessage}`, |
| 54 | + } as SentryResponse), |
| 55 | + { |
| 56 | + status: 500, |
| 57 | + headers: corsHeaders(), |
| 58 | + } |
| 59 | + ); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +export async function onRequestOptions() { |
| 64 | + return new Response(null, { |
| 65 | + status: 204, |
| 66 | + headers: corsHeaders(), |
| 67 | + }); |
| 68 | +} |
| 69 | + |
| 70 | +function corsHeaders(): Record<string, string> { |
| 71 | + return { |
| 72 | + "Access-Control-Allow-Origin": "*", |
| 73 | + "Access-Control-Allow-Methods": "GET, POST, OPTIONS", |
| 74 | + "Access-Control-Allow-Headers": "Content-Type", |
| 75 | + "Cache-Control": "public, max-age=300", |
| 76 | + }; |
| 77 | +} |
0 commit comments