(request: Request, configuredDsn: string)
| 25 | const badSentryEnvelopeResponse = () => new Response("bad envelope", { status: 400 }); |
| 26 | |
| 27 | export const handleSentryTunnelRequest = (request: Request, configuredDsn: string) => |
| 28 | Effect.gen(function* () { |
| 29 | const envelope = yield* Effect.tryPromise({ |
| 30 | try: () => request.text(), |
| 31 | catch: (cause) => new SentryTunnelError({ cause }), |
| 32 | }); |
| 33 | const firstLine = envelope.slice(0, envelope.indexOf("\n")); |
| 34 | const header = yield* decodeSentryEnvelopeHeader(firstLine).pipe( |
| 35 | Effect.mapError((cause) => new SentryTunnelError({ cause })), |
| 36 | ); |
| 37 | const dsn = header.dsn; |
| 38 | if (!dsn) return new Response("missing dsn", { status: 400 }); |
| 39 | |
| 40 | const envelopeDsn = yield* Effect.try({ |
| 41 | try: () => new URL(dsn), |
| 42 | catch: (cause) => new SentryTunnelError({ cause }), |
| 43 | }); |
| 44 | const ourDsn = yield* Effect.try({ |
| 45 | try: () => new URL(configuredDsn), |
| 46 | catch: (cause) => new SentryTunnelError({ cause }), |
| 47 | }); |
| 48 | if (envelopeDsn.host !== ourDsn.host || envelopeDsn.pathname !== ourDsn.pathname) { |
| 49 | return new Response("dsn mismatch", { status: 400 }); |
| 50 | } |
| 51 | |
| 52 | const projectId = envelopeDsn.pathname.replace(/^\//, ""); |
| 53 | const ingestUrl = `https://${envelopeDsn.host}/api/${projectId}/envelope/`; |
| 54 | return yield* Effect.tryPromise({ |
| 55 | try: () => |
| 56 | fetch(ingestUrl, { |
| 57 | method: "POST", |
| 58 | body: envelope, |
| 59 | headers: { "Content-Type": "application/x-sentry-envelope" }, |
| 60 | }), |
| 61 | catch: (cause) => new SentryTunnelError({ cause }), |
| 62 | }); |
| 63 | }).pipe(Effect.catch(() => Effect.succeed(badSentryEnvelopeResponse()))); |
| 64 | |
| 65 | export const sentryTunnelMiddleware = createMiddleware({ type: "request" }).server( |
| 66 | ({ pathname, request, next }) => { |
no test coverage detected