@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
268 lines (267 loc) • 10.2 kB
JavaScript
import { getEnvelopeEndpointWithUrlEncodedAuth } from "../api.js";
import { getClient } from "../currentScopes.js";
import { suppressTracing } from "../tracing/trace.js";
import { debug } from "./debug-logger.js";
import { makeDsn } from "./dsn.js";
import { DEBUG_BUILD } from "../debug-build.js";
import { getServedTunnelMatch, matchesTunnel, resolveAllowedDsns, resolveTunnelMatch } from "./tunnel.js";
// src/utils/tunnelForward.ts
function handleTunnelRequest(requestOrOptions, responseOrOptions, nodeOptions) {
if (isNodeTunnelResponse(responseOrOptions)) {
const nodeResponse = responseOrOptions;
return forwardTunnelRequest(toFetchRequest(requestOrOptions), getAllowedDsns(nodeOptions)).then((fetchResponse) => writeNodeResponse(nodeResponse, fetchResponse));
}
const isLegacyCall = "request" in requestOrOptions && !("method" in requestOrOptions);
return forwardTunnelRequest(isLegacyCall ? requestOrOptions.request : requestOrOptions, getAllowedDsns(isLegacyCall ? requestOrOptions : responseOrOptions));
}
function handleTunnelRequestIfMatched(request, responseOrOptions, nodeOptions) {
const response = isNodeTunnelResponse(responseOrOptions) ? responseOrOptions : void 0;
const tunnel = resolveTunnelMatch(response ? nodeOptions : responseOrOptions);
if (!tunnel.allowedDsns.length || !matchesTunnel(request, tunnel)) return;
if (!response) return forwardTunnelRequest(request, tunnel.allowedDsns);
return forwardTunnelRequest(toFetchRequest(request), tunnel.allowedDsns).then((fetchResponse) => writeNodeResponse(response, fetchResponse));
}
/**
* Answers a request to the tunnel `serveTunnelIntegration` serves on a Node server, ahead of the app. Returns `true`
* when it claimed the request and answers it, `false` to hand the request to the app.
*
* It never throws, since it runs inside the server's `emit`, where a throw crashes the process. Until a request is
* claimed, a failure hands it to the app. Once claimed, its body may be read already, so a failure ends in a 502.
*/
function handleServedNodeTunnelRequest(request, response) {
let forward;
try {
const servedTunnel = getServedTunnelMatch(request);
if (!servedTunnel) return false;
const fetchRequest = toFetchRequest(request);
forward = () => servedTunnel.forward(fetchRequest, servedTunnel.allowedDsns);
} catch (error) {
DEBUG_BUILD && debug.error("Sentry tunnel: failed to match a request", error);
return false;
}
Promise.resolve().then(forward).then((fetchResponse) => writeNodeResponse(response, fetchResponse)).catch((error) => {
DEBUG_BUILD && debug.error("Sentry tunnel: failed to forward a request", error);
try {
if (!response.headersSent) response.writeHead(502);
response.end(/* @__PURE__ */ new Uint8Array());
} catch {}
});
return true;
}
/**
* `allowedDsns` plus the server's own DSN. Without `allowedDsns`, the DSNs `serveTunnelIntegration` allows, so its
* options apply here too.
*/
function getAllowedDsns(options) {
return options?.allowedDsns ? resolveAllowedDsns(options.allowedDsns, getClient()?.getDsn()) : resolveTunnelMatch().allowedDsns;
}
/**
* The headers of Sentry's answer the browser SDK reads. The rest describe the connection to Sentry, which HTTP/2
* rejects.
*/
const FORWARDED_RESPONSE_HEADERS = [
"content-type",
"retry-after",
"x-sentry-rate-limits"
];
/**
* The headers of Sentry's answer to pass on to the browser, see `FORWARDED_RESPONSE_HEADERS`.
*/
function pickForwardedHeaders(response) {
const headers = {};
for (const name of FORWARDED_RESPONSE_HEADERS) {
const value = response.headers.get(name);
if (value) headers[name] = value;
}
return headers;
}
function isNodeTunnelResponse(value) {
return typeof value?.writeHead === "function";
}
function toFetchRequest(request) {
const headers = new Headers();
for (const [name, value] of Object.entries(request.headers)) if (value !== void 0 && !name.startsWith(":")) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
let iterator;
const getIterator = () => iterator ?? (iterator = request[Symbol.asyncIterator]());
const encoder = new TextEncoder();
const body = new ReadableStream({
async pull(controller) {
const { done, value } = await getIterator().next();
if (done) {
controller.close();
return;
}
controller.enqueue(typeof value === "string" ? encoder.encode(value) : value);
},
async cancel() {
while (!(await getIterator().next()).done);
}
});
return new Request("http://localhost/", {
method: "POST",
headers,
body,
duplex: "half"
});
}
async function writeNodeResponse(response, fetchResponse) {
const body = await fetchResponse.arrayBuffer().catch(() => void 0);
if (!body) {
response.writeHead(500);
response.end(/* @__PURE__ */ new Uint8Array());
return;
}
response.writeHead(fetchResponse.status, pickForwardedHeaders(fetchResponse));
response.end(new Uint8Array(body));
}
function withDecodedBodyHeaders(response) {
const headers = new Headers(response.headers);
headers.delete("content-encoding");
headers.delete("content-length");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
/**
* Forwards an envelope to Sentry if its DSN is one of `allowedDsns`, otherwise answers with the rejecting response.
*/
async function forwardTunnelRequest(request, allowedDsns) {
return withDecodedBodyHeaders(await forwardEnvelope(request, allowedDsns));
}
/**
* How long a forward waits on Sentry, so a hanging Sentry doesn't hold the browser's connection open.
*/
const FORWARD_TIMEOUT_MS = 3e4;
async function forwardEnvelope(request, allowedDsns) {
if (allowedDsns.length === 0) return new Response("Tunnel not configured", { status: 500 });
if (!Number(request.headers.get("content-length"))) return new Response("Length required", { status: 411 });
const reader = request.body?.getReader();
const head = reader && await readEnvelopeHeaderLine(reader).catch(() => void 0);
if (!reader || !head) return new Response("Invalid envelope", { status: 400 });
const sentryIngestUrl = resolveIngestUrl(head.line, allowedDsns);
if (typeof sentryIngestUrl !== "string") {
reader.cancel().catch(() => void 0);
return sentryIngestUrl;
}
try {
return await suppressTracing(() => fetch(sentryIngestUrl, {
method: "POST",
headers: forwardHeaders(request),
body: prependToStream(head.read, reader),
duplex: "half",
signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
}));
} catch (error) {
debug.error("Sentry tunnel: failed to forward envelope", error);
return new Response("Failed to forward envelope to Sentry", { status: 500 });
}
}
/**
* Returns the ingest URL for an envelope header line, or the rejecting response.
*/
function resolveIngestUrl(headerLine, allowedDsns) {
let envelopeHeader;
try {
envelopeHeader = JSON.parse(new TextDecoder().decode(headerLine));
} catch {
return new Response("Invalid envelope", { status: 400 });
}
if (!envelopeHeader) return new Response("Invalid envelope: missing header", { status: 400 });
const dsn = envelopeHeader.dsn;
if (!dsn || typeof dsn !== "string") return new Response("Invalid envelope: missing DSN", { status: 400 });
if (!allowedDsns.some((allowed) => allowed === dsn)) {
debug.warn(`Sentry tunnel: rejected request with unauthorized DSN (${dsn})`);
return new Response("DSN not allowed", { status: 403 });
}
const dsnComponents = makeDsn(dsn);
if (!dsnComponents) {
debug.warn(`Could not extract DSN Components from: ${dsn}`);
return new Response("Invalid DSN", { status: 403 });
}
return getEnvelopeEndpointWithUrlEncodedAuth(dsnComponents);
}
/**
* A header line longer than this is not an envelope.
*/
const MAX_ENVELOPE_HEADER_BYTES = 65536;
/**
* Client headers Relay reads from a browser's own request: the user agent and its client hints to tell the browser,
* and `Origin` or `Referer` for the project's allowed domains check, which Relay skips without them.
*/
const FORWARDED_CLIENT_HEADERS = [
"user-agent",
"sec-ch-ua",
"sec-ch-ua-model",
"sec-ch-ua-platform",
"sec-ch-ua-platform-version",
"origin",
"referer"
];
/**
* Sentry SaaS replaces `X-Sentry-Forwarded-For` with the connecting IP, which is the tunnel server, but keeps these
* and prefers them. Passing them through keeps the client IP, as a rewrite proxy does.
*/
const FORWARDED_CLIENT_IP_HEADERS = [
"cf-connecting-ip",
"x-vercel-forwarded-for",
"x-forwarded-for"
];
/**
* Reads the body up to the envelope header line. Returns the line and every byte read, or `undefined`.
*/
async function readEnvelopeHeaderLine(reader) {
let read = /* @__PURE__ */ new Uint8Array(0);
while (read.length <= MAX_ENVELOPE_HEADER_BYTES) {
const { done, value } = await reader.read();
if (done) return read.length ? {
line: read,
read
} : void 0;
const searchFrom = read.length;
read = concatBytes(read, value);
const newline = read.indexOf(10, searchFrom);
if (newline !== -1) return {
line: read.subarray(0, newline),
read
};
}
await reader.cancel();
}
function concatBytes(a, b) {
const merged = new Uint8Array(a.length + b.length);
merged.set(a);
merged.set(b, a.length);
return merged;
}
function prependToStream(prefix, reader) {
return new ReadableStream({
start(controller) {
controller.enqueue(prefix);
},
async pull(controller) {
const { done, value } = await reader.read();
if (done) {
controller.close();
return;
}
controller.enqueue(value);
},
cancel(reason) {
return reader.cancel(reason);
}
});
}
function forwardHeaders(request) {
const headers = { "Content-Type": "application/x-sentry-envelope" };
const clientIp = FORWARDED_CLIENT_IP_HEADERS.map((name) => request.headers.get(name)).find(Boolean);
if (clientIp) headers["X-Sentry-Forwarded-For"] = clientIp;
for (const name of [...FORWARDED_CLIENT_IP_HEADERS, ...FORWARDED_CLIENT_HEADERS]) {
const value = request.headers.get(name);
if (value) headers[name] = value;
}
return headers;
}
export { forwardTunnelRequest, handleServedNodeTunnelRequest, handleTunnelRequest, handleTunnelRequestIfMatched, pickForwardedHeaders };
//# sourceMappingURL=tunnelForward.js.map