@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
190 lines (189 loc) • 8.27 kB
JavaScript
import { getClient } from "../currentScopes.js";
import { DEBUG_BUILD } from "../debug-build.js";
import { escapeStringForRegex } from "../vendor/escapeStringForRegex.js";
import { debug } from "./debug-logger.js";
import { dsnToString, makeDsn } from "./dsn.js";
import { fnv1a32 } from "./hash.js";
import { getClientTunnel, setClientTunnel } from "./tunnelStore.js";
import { parseUrl } from "./url.js";
import { URL_PATH } from "@sentry/conventions/attributes";
// src/utils/tunnel.ts
/**
* Computes a server client's served tunnel from its resolved options, and stores it.
*/
function setServedTunnel(client, tunnelOptions, forward) {
const allowedDsns = resolveAllowedDsns(tunnelOptions.allowedDsns, client.getDsn());
const servedTunnel = {
paths: resolveTunnelPaths(tunnelOptions, allowedDsns),
basePath: tunnelOptions.basePath,
allowedDsns,
forward,
intercept: tunnelOptions.intercept !== false
};
setClientTunnel(client, { served: servedTunnel });
return servedTunnel;
}
/**
* The active client's served tunnel. It lives in the tunnel store, so a copy of this module that didn't set it up,
* like the one a bundler gives Next.js's middleware next to its `instrumentation`, still finds it.
*/
function getServedTunnel(client = getClient()) {
return client && getClientTunnel(client)?.served;
}
/**
* Fills in framework defaults (like the base path) for a managed tunnel on the DSN-derived path. User options win.
* A path the user wrote, as a string or `path`, is used as written, so a tunnel served outside the app keeps working.
* The base path is normalized, and a root one is no default at all.
*/
function applyBrowserTunnelDefaults(tunnel, defaults) {
if (!tunnel || typeof tunnel === "string" || tunnel !== true && tunnel.path) return tunnel;
const { basePath, ...rest } = defaults ?? {};
const normalizedBasePath = normalizeTunnelBasePath(basePath);
const resolvedDefaults = normalizedBasePath ? {
...rest,
basePath: normalizedBasePath
} : rest;
if (!Object.keys(resolvedDefaults).length) return tunnel;
return {
...resolvedDefaults,
...tunnel === true ? {} : tunnel
};
}
/**
* Returns the same-origin tunnel path for a DSN, e.g. `/k3x9q2a`, by default the active client's. Browser and server
* derive it independently, and as a hash it gives ad-blocker filter lists nothing to match.
*/
function getTunnelPath(dsn) {
const components = dsn ? makeDsn(dsn) : getClient()?.getDsn();
return components ? `/${fnv1a32(dsnToString(components))}` : void 0;
}
/**
* Returns the active server client's tunnel paths, relative to its base path. For frameworks that can only register
* routes; everything else uses {@link handleTunnelRequestIfMatched}.
*/
function getTunnelPaths() {
return getServedTunnel()?.paths ?? [];
}
/**
* The paths a managed tunnel is served at: the fixed `path`, or else one per allowed DSN.
*/
function resolveTunnelPaths(tunnelOptions, allowedDsns) {
const fixedPath = tunnelOptions.path?.replace(/\/$/, "");
if (fixedPath) return [fixedPath];
const paths = allowedDsns.map((dsn) => getTunnelPath(dsn));
return [...new Set(paths.filter((path) => !!path))];
}
/**
* `ignoreSpans` filters for the server spans of tunnel requests. They match `url.path` and the legacy `http.url`,
* which some framework spans start with (SvelteKit's `sveltekit.handle.root`).
*/
function getTunnelIgnoreSpanFilters(tunnelOptions, paths) {
if (!paths.length) return [];
const pathPattern = `${escapeStringForRegex(normalizeTunnelBasePath(tunnelOptions.basePath))}(?:${paths.map(escapeStringForRegex).join("|")})/?`;
return [{ attributes: { [URL_PATH]: new RegExp(`^${pathPattern}$`) } }, { attributes: { "http.url": new RegExp(`^[a-z][a-z\\d+.-]*://[^/]+${pathPattern}(?:[?#].*)?$`) } }];
}
/**
* Normalizes a base path to `/app`, or `''` for the root.
*/
function normalizeTunnelBasePath(basePath) {
const path = (basePath?.startsWith("./") ? basePath.slice(1) : basePath ?? "").replace(/\/$/, "");
return !path || path.startsWith("/") ? path : `/${path}`;
}
/**
* Resolves the tunnel the public helpers match: `options`, else the one `serveTunnelIntegration` serves, else the
* path of the active client's own DSN.
*/
function resolveTunnelMatch(options) {
const servedTunnel = !options && getServedTunnel();
if (servedTunnel) return servedTunnel;
const allowedDsns = resolveAllowedDsns(options?.allowedDsns, getClient()?.getDsn());
return {
paths: resolveTunnelPaths(options ?? {}, allowedDsns),
basePath: options?.basePath,
allowedDsns
};
}
/**
* Returns true if the request is a POST to one of the tunnel's paths.
*/
function matchesTunnel(request, tunnel) {
if (request.method !== "POST" || !request.url) return false;
const path = stripBasePath(parseUrl(request.url).path || "/", tunnel.basePath);
return path !== void 0 && tunnel.paths.includes(path.replace(/\/$/, ""));
}
/**
* Returns true if the request is a POST to the managed tunnel. The tunnel comes from `options`, else from
* `serveTunnelIntegration`, else it's the path of the active client's own DSN.
*/
function isTunnelRequest(request, options) {
return matchesTunnel(request, resolveTunnelMatch(options));
}
/**
* Returns true if the request targets the tunnel `serveTunnelIntegration` serves, whether the SDK answers it or the
* app does with `intercept: false`. The server SDKs record no session or span for these. Unlike
* {@link isTunnelRequest}, there's no fallback, so the framework SDKs serve nothing without the integration. `client`
* defaults to the active one.
*/
function isServedTunnelRequest(request, client) {
try {
return !!matchServedTunnel(request, client);
} catch (error) {
DEBUG_BUILD && debug.error("Sentry tunnel: failed to match a request", error);
return false;
}
}
/**
* The served tunnel, if the SDK answers this request on it. `client` defaults to the active one.
*/
function getServedTunnelMatch(request, client) {
const servedTunnel = matchServedTunnel(request, client);
return servedTunnel?.intercept ? servedTunnel : void 0;
}
/**
* The served tunnel, if this request targets it.
*/
function matchServedTunnel(request, client) {
const servedTunnel = getServedTunnel(client);
return servedTunnel?.allowedDsns.length && matchesTunnel(request, servedTunnel) ? servedTunnel : void 0;
}
/**
* Forwards the request if it targets the tunnel `serveTunnelIntegration` serves, otherwise returns `undefined`. The
* runtime and framework SDKs answer tunnel requests with it, ahead of the app.
*
* It never throws, since a throw here would break the app's own requests. 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 instead. `client` defaults to
* the active one.
*/
function handleServedTunnelRequest(request, client) {
let servedTunnel;
try {
servedTunnel = request.body && getServedTunnelMatch(request, client);
if (!servedTunnel) return;
} catch (error) {
DEBUG_BUILD && debug.error("Sentry tunnel: failed to match a request", error);
return;
}
const { forward, allowedDsns } = servedTunnel;
return Promise.resolve().then(() => forward(request, allowedDsns)).catch((error) => {
DEBUG_BUILD && debug.error("Sentry tunnel: failed to forward a request", error);
return new Response(null, { status: 502 });
});
}
/**
* `allowedDsns` plus the server's own DSN, which is always allowed.
*/
function resolveAllowedDsns(allowedDsns, ownDsn) {
const dsns = /* @__PURE__ */ new Set();
for (const components of [...(allowedDsns ?? []).map((dsn) => makeDsn(dsn)), ownDsn]) if (components) dsns.add(dsnToString(components));
return [...dsns];
}
/**
* Returns the path below `basePath`, or `undefined` outside it.
*/
function stripBasePath(pathname, basePath) {
const base = normalizeTunnelBasePath(basePath);
if (!base) return pathname;
return pathname === base || pathname.startsWith(`${base}/`) ? pathname.slice(base.length) : void 0;
}
export { applyBrowserTunnelDefaults, getServedTunnel, getServedTunnelMatch, getTunnelIgnoreSpanFilters, getTunnelPath, getTunnelPaths, handleServedTunnelRequest, isServedTunnelRequest, isTunnelRequest, matchesTunnel, normalizeTunnelBasePath, resolveAllowedDsns, resolveTunnelMatch, resolveTunnelPaths, setServedTunnel };
//# sourceMappingURL=tunnel.js.map