Unverified Commit 3b47db01 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Improve Request Insights request and fetch details

Co-authored-by: 's avatarDavid Ilie <david@davidilie.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 7e01b92f
import { getFetchUrlPresentation, truncateMiddle } from './fetch-label'
describe('request insight fetch labels', () => {
it('classifies same-origin and external fetches by full web origin', () => {
expect(
getFetchUrlPresentation('/api/items?token=redacted', 'https://app.test')
).toEqual({
fullUrl: 'https://app.test/api/items?token=redacted',
path: '/api/items?token=redacted',
originKind: 'same-origin',
originLabel: 'Same origin',
})
expect(
getFetchUrlPresentation('https://api.test:445/items', 'https://app.test')
).toEqual({
fullUrl: 'https://api.test:445/items',
path: '/items',
originKind: 'external',
originLabel: 'External origin · api.test:445',
})
expect(
getFetchUrlPresentation('http://app.test/items', 'https://app.test')
).toEqual({
fullUrl: 'http://app.test/items',
path: '/items',
originKind: 'external',
originLabel: 'External origin · http://app.test',
})
})
it('does not guess origin semantics without a usable browser origin', () => {
expect(
getFetchUrlPresentation('https://api.test/items', undefined)
).toEqual({
fullUrl: 'https://api.test/items',
path: '/items',
originKind: 'unknown',
originLabel: 'https://api.test',
})
expect(getFetchUrlPresentation('/api/items', undefined)).toEqual({
fullUrl: '/api/items',
path: '/api/items',
originKind: 'unknown',
originLabel: 'Origin unavailable',
})
})
it('middle-truncates labels while retaining their distinguishing suffix', () => {
const value = '/api/a/very/long/path/to/tail-marker?token=redacted'
const truncated = truncateMiddle(value, 28)
expect(truncated).toHaveLength(28)
expect(truncated).toContain('…')
expect(truncated).toMatch(/token=redacted$/)
expect(truncateMiddle('😀abc', 3)).toBe('😀…c')
expect(truncateMiddle('secret', 1)).toBe('…')
expect(truncateMiddle('secret', 0)).toBe('')
})
})
export type FetchOriginKind = 'same-origin' | 'external' | 'unknown'
export type FetchUrlPresentation = {
fullUrl: string
path: string
originKind: FetchOriginKind
originLabel: string
}
const DEFAULT_PATH_LENGTH = 48
const DEFAULT_ORIGIN_LENGTH = 36
export function getFetchUrlPresentation(
url: string | undefined,
currentOrigin: string | undefined,
pathLength = DEFAULT_PATH_LENGTH,
originLength = DEFAULT_ORIGIN_LENGTH
): FetchUrlPresentation {
if (!url) {
return {
fullUrl: 'Unknown URL',
path: 'Unknown URL',
originKind: 'unknown',
originLabel: 'Origin unavailable',
}
}
const baseUrl = parseHttpUrl(currentOrigin)
try {
const parsedUrl = baseUrl ? new URL(url, baseUrl) : new URL(url)
if (!isHttpUrl(parsedUrl)) {
return {
fullUrl: url,
path: truncateMiddle(url, pathLength),
originKind: 'unknown',
originLabel: 'Origin unavailable',
}
}
const sameOrigin = baseUrl?.origin === parsedUrl.origin
const originKind = baseUrl
? sameOrigin
? 'same-origin'
: 'external'
: 'unknown'
const compactOrigin =
baseUrl?.protocol === parsedUrl.protocol
? parsedUrl.host
: parsedUrl.origin
return {
fullUrl: parsedUrl.href,
path: truncateMiddle(
`${parsedUrl.pathname}${parsedUrl.search}`,
pathLength
),
originKind,
originLabel:
originKind === 'same-origin'
? 'Same origin'
: originKind === 'external'
? `External origin · ${truncateMiddle(compactOrigin, originLength)}`
: truncateMiddle(parsedUrl.origin, originLength),
}
} catch {
return {
fullUrl: url,
path: truncateMiddle(url, pathLength),
originKind: 'unknown',
originLabel: 'Origin unavailable',
}
}
}
export function truncateMiddle(value: string, maxLength: number): string {
if (maxLength <= 0) {
return ''
}
const characters = Array.from(value)
if (characters.length <= maxLength) {
return value
}
if (maxLength === 1) {
return '…'
}
const availableLength = maxLength - 1
const prefixLength = Math.floor(availableLength / 2)
const suffixLength = availableLength - prefixLength
return `${characters.slice(0, prefixLength).join('')}…${characters
.slice(-suffixLength)
.join('')}`
}
function parseHttpUrl(value: string | undefined): URL | undefined {
if (!value) {
return undefined
}
try {
const url = new URL(value)
return isHttpUrl(url) ? url : undefined
} catch {
return undefined
}
}
function isHttpUrl(url: URL): boolean {
return url.protocol === 'http:' || url.protocol === 'https:'
}
.request-insights-panel-container {
container-type: inline-size;
height: 100%;
min-height: 0;
}
.request-insights-panel {
display: grid;
grid-template-columns: minmax(210px, 320px) minmax(420px, 1fr);
......@@ -22,6 +28,7 @@
.request-insights-list {
border-right: 1px solid var(--color-gray-400);
overflow: auto;
overscroll-behavior: contain;
min-width: 0;
}
......@@ -414,6 +421,7 @@
min-width: 0;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
}
.request-insights-summary {
......@@ -464,15 +472,63 @@
}
.request-insights-overview span {
overflow: hidden;
max-width: 100%;
min-width: 0;
border: 1px solid var(--color-gray-400);
border-radius: 4px;
padding: 2px 6px;
color: var(--color-gray-900);
font-size: var(--size-12);
text-overflow: ellipsis;
white-space: nowrap;
}
.request-insights-overview .request-insights-route-template {
border-style: dashed;
font-family: var(--font-mono);
}
.request-insights-params-trigger {
border: 0;
padding: 0;
background: transparent;
color: inherit;
cursor: help;
font: inherit;
}
.request-insights-params-trigger:focus-visible {
outline: var(--focus-ring);
outline-offset: 2px;
}
.request-insights-params-tooltip,
.request-insights-fetch-tooltip,
.request-insights-trace-tooltip {
--tooltip-background: var(--color-background-100);
border: 1px solid var(--color-gray-alpha-400);
box-shadow: 0 4px 14px rgb(0 0 0 / 16%);
color: var(--color-gray-1000);
}
.request-insights-params-tooltip {
max-width: min(420px, calc(100vw - 32px));
font-family: var(--font-mono);
overflow-wrap: anywhere;
text-align: left;
white-space: pre-wrap;
}
.request-insights-fetch-tooltip,
.request-insights-trace-tooltip {
max-width: min(640px, calc(100vw - 32px));
font-family: var(--font-mono);
overflow-wrap: anywhere;
white-space: normal;
}
.request-insights-error {
padding: 8px 16px;
border-bottom: 1px solid var(--color-gray-400);
......@@ -598,11 +654,20 @@
flex-direction: column;
}
.request-insights-trace-rows:focus-visible {
outline: var(--focus-ring);
outline-offset: -1px;
}
.request-insights-span-row {
min-height: 28px;
border-bottom: 1px solid var(--color-gray-300);
}
.request-insights-span-row[data-active='true'] {
background: var(--color-gray-200);
}
.request-insights-span-row:last-child {
border-bottom: 0;
}
......@@ -644,7 +709,6 @@
background: var(--color-red-800);
}
.request-insights-fetch-host,
.request-insights-cache-reason {
min-width: 0;
overflow: hidden;
......@@ -722,7 +786,52 @@
gap: 8px;
}
@media (max-width: 900px) {
.request-insights-fetch-url-trigger {
display: flex;
min-width: 0;
align-items: center;
gap: 8px;
cursor: help;
}
.request-insights-fetch-path,
.request-insights-fetch-origin {
min-width: 0;
overflow: hidden;
white-space: nowrap;
}
.request-insights-fetch-path {
color: var(--color-gray-1000);
text-overflow: ellipsis;
}
.request-insights-fetch-origin {
max-width: 240px;
flex-shrink: 0;
border: 1px solid var(--color-gray-400);
border-radius: 999px;
padding: 0 5px;
color: var(--color-gray-800);
font-family: inherit;
font-size: var(--size-10);
text-overflow: ellipsis;
}
.request-insights-fetch-origin[data-origin='external'] {
border-color: var(--color-purple-500);
color: var(--color-purple-900);
}
@media (forced-colors: active) {
.request-insights-trace-rows:focus-visible,
.request-insights-span-row[data-active='true'] {
outline: 1px solid Highlight;
outline-offset: -1px;
}
}
@container (width <= 900px) {
.request-insights-summary {
align-items: flex-start;
}
......@@ -732,7 +841,7 @@
}
}
@media (max-width: 700px) {
@container (width < 630px) {
.request-insights-panel {
grid-template-columns: 1fr;
}
......
import {
formatRequestRouteParams,
getRequestDisplayUrl,
getRequestListDisplayUrl,
getRequestRouteParams,
} from './request-label'
describe('request insight request labels', () => {
it('prefers the concrete URL and hides the transport-only RSC query', () => {
const request = {
requestId: 'request-1',
route: '/products/[id]',
url: '/products/blue?tab=details&_rsc=redacted#summary',
}
expect(getRequestDisplayUrl(request)).toBe(
'/products/blue?tab=details&_rsc=redacted#summary'
)
expect(getRequestListDisplayUrl(request, true)).toBe(
'/products/blue?tab=details#summary'
)
expect(getRequestListDisplayUrl(request, false)).toBe(
'/products/blue?tab=details&_rsc=redacted#summary'
)
expect(
getRequestListDisplayUrl(
{
requestId: 'request-2',
route: '/products/[id]',
url: '//example.test/products/blue?_rsc=redacted',
},
true
)
).toBe('//example.test/products/blue')
})
it('extracts dynamic, catch-all, and optional catch-all parameters', () => {
expect(
getRequestRouteParams({
route: '/products/[category]/[...slug]',
url: '/products/widgets/blue/large?sort=redacted',
})
).toEqual([
{ name: 'category', value: 'widgets' },
{ name: 'slug', value: ['blue', 'large'] },
])
expect(
getRequestRouteParams({
route: '/docs/[[...slug]]',
url: '/docs',
})
).toEqual([{ name: 'slug', value: [] }])
})
it('handles base paths and encoded route values', () => {
const params = getRequestRouteParams(
{
route: '/products/[category]/[...slug]',
url: '/shop/products/home%20goods/blue%2Flarge',
},
'/shop'
)
expect(params).toEqual([
{ name: 'category', value: 'home goods' },
{ name: 'slug', value: ['blue/large'] },
])
expect(formatRequestRouteParams(params!)).toBe(
'{\n "category": "home goods",\n "slug": [\n "blue/large"\n ]\n}'
)
})
it('does not guess parameters from malformed or mismatched routes', () => {
expect(
getRequestRouteParams({ route: '/products/[id]', url: '/users/1' })
).toBeUndefined()
expect(
getRequestRouteParams({ route: '/products/[id]', url: '/products/%zz' })
).toBeUndefined()
expect(
getRequestRouteParams({
route: '/products/[id]/[id]',
url: '/products/one/two',
})
).toBeUndefined()
})
})
import type { RequestInsight } from '../../../shared/request-insights'
import { removePathPrefix } from '../../../../shared/lib/router/utils/remove-path-prefix'
type RequestIdentity = Pick<RequestInsight, 'requestId' | 'route' | 'url'>
export type RequestRouteParam = {
name: string
value: string | string[]
}
export function getRequestDisplayUrl(request: RequestIdentity): string {
return request.url ?? request.route ?? request.requestId
}
export function getRequestListDisplayUrl(
request: RequestIdentity,
rscRequest: boolean
): string {
const displayUrl = getRequestDisplayUrl(request)
if (!rscRequest) {
return displayUrl
}
try {
const protocolRelative = displayUrl.startsWith('//')
const rootRelative = !protocolRelative && displayUrl.startsWith('/')
const parsed = new URL(displayUrl, 'http://next.local')
if (!parsed.searchParams.has('_rsc')) {
return displayUrl
}
parsed.searchParams.delete('_rsc')
return protocolRelative
? `//${parsed.host}${parsed.pathname}${parsed.search}${parsed.hash}`
: rootRelative
? `${parsed.pathname}${parsed.search}${parsed.hash}`
: parsed.toString()
} catch {
return displayUrl
}
}
export function getRequestRouteParams(
request: Pick<RequestIdentity, 'route' | 'url'>,
basePath = process.env.__NEXT_ROUTER_BASEPATH || ''
): RequestRouteParam[] | undefined {
if (!request.route || !request.url) {
return undefined
}
const pathname = getPathname(request.url)
if (!pathname) {
return undefined
}
const routeSegments = splitPathname(request.route)
const pathnameSegments = splitPathname(removePathPrefix(pathname, basePath))
if (!routeSegments || !pathnameSegments) {
return undefined
}
const params: RequestRouteParam[] = []
const names = new Set<string>()
let pathnameIndex = 0
for (const routeSegment of routeSegments) {
const dynamicSegment = parseDynamicSegment(routeSegment)
if (!dynamicSegment) {
if (
routeSegment.includes('[') ||
routeSegment.includes(']') ||
pathnameSegments[pathnameIndex] !== routeSegment
) {
return undefined
}
pathnameIndex += 1
continue
}
if (names.has(dynamicSegment.name)) {
return undefined
}
names.add(dynamicSegment.name)
if (dynamicSegment.catchAll) {
const value = pathnameSegments.slice(pathnameIndex)
if (value.length === 0 && !dynamicSegment.optional) {
return undefined
}
params.push({ name: dynamicSegment.name, value })
pathnameIndex = pathnameSegments.length
continue
}
const value = pathnameSegments[pathnameIndex]
if (value === undefined) {
return undefined
}
params.push({ name: dynamicSegment.name, value })
pathnameIndex += 1
}
return pathnameIndex === pathnameSegments.length ? params : undefined
}
export function formatRequestRouteParams(params: RequestRouteParam[]): string {
return JSON.stringify(
Object.fromEntries(params.map(({ name, value }) => [name, value])),
null,
2
)
}
function getPathname(url: string): string | undefined {
try {
if (url.startsWith('/')) {
return new URL(url, 'http://next.local').pathname
}
const parsed = new URL(url)
return parsed.protocol === 'http:' || parsed.protocol === 'https:'
? parsed.pathname
: undefined
} catch {
return undefined
}
}
function splitPathname(pathname: string): string[] | undefined {
if (!pathname.startsWith('/')) {
return undefined
}
const segments = pathname.split('/').slice(1)
if (segments.at(-1) === '') {
segments.pop()
}
const decoded: string[] = []
for (const segment of segments) {
const value = decodeSegment(segment)
if (value === undefined) {
return undefined
}
decoded.push(value)
}
return decoded
}
function decodeSegment(segment: string): string | undefined {
try {
return decodeURIComponent(segment)
} catch {
return undefined
}
}
function parseDynamicSegment(segment: string):
| {
name: string
catchAll: boolean
optional: boolean
}
| undefined {
const optionalCatchAll = segment.match(/^\[\[\.\.\.([^[/\]]+)\]\]$/)
const catchAll = segment.match(/^\[\.\.\.([^[/\]]+)\]$/)
const dynamic = segment.match(/^\[([^[/\]]+)\]$/)
const match = optionalCatchAll ?? catchAll ?? dynamic
if (!match) {
return undefined
}
return {
name: match[1],
catchAll: optionalCatchAll !== null || catchAll !== null,
optional: optionalCatchAll !== null,
}
}
......@@ -9,7 +9,12 @@ import {
getRequestListEntries,
isPageLoadRequest,
} from './request-list'
import { getTraceItems, getTracePosition, getTraceRange } from './trace-viewer'
import {
getTraceItems,
getTraceNavigationIndex,
getTracePosition,
getTraceRange,
} from './trace-viewer'
function createRequest(
overrides: Partial<RequestInsight> = {}
......@@ -28,6 +33,18 @@ function createRequest(
}
describe('request insights trace viewer', () => {
it('moves the active trace row without leaving the listbox', () => {
expect(getTraceNavigationIndex(0, 3, 'ArrowDown')).toBe(1)
expect(getTraceNavigationIndex(2, 3, 'ArrowDown')).toBe(2)
expect(getTraceNavigationIndex(2, 3, 'ArrowUp')).toBe(1)
expect(getTraceNavigationIndex(1, 3, 'Home')).toBe(0)
expect(getTraceNavigationIndex(1, 3, 'End')).toBe(2)
expect(getTraceNavigationIndex(1, 3, 'ArrowRight')).toBeUndefined()
expect(getTraceNavigationIndex(1, 3, 'ArrowLeft')).toBeUndefined()
expect(getTraceNavigationIndex(0, 0, 'ArrowDown')).toBeUndefined()
expect(getTraceNavigationIndex(0, 3, 'Enter')).toBeUndefined()
})
it('keeps the active request selected when newer requests arrive', () => {
const selectedRequest = createRequest({ requestId: 'selected' })
const newerRequest = createRequest({ requestId: 'newer' })
......@@ -287,6 +304,40 @@ describe('request insights trace viewer', () => {
)
})
it('distinguishes same-origin and external fetches in the trace', () => {
const request = createRequest({
fetches: [
{
method: 'GET',
url: 'https://app.test/api/data?token=%3Credacted%3E',
startTime: 110,
durationMs: 10,
},
{
method: 'POST',
url: 'https://api.example.test/api/data',
startTime: 120,
durationMs: 20,
},
],
})
expect(
getTraceItems(request, true, 'https://app.test').map(
({ label, fullLabel }) => ({ label, fullLabel })
)
).toEqual([
{
label: 'GET /api/data?token=%3Credacted%3E · Same origin',
fullLabel: 'GET https://app.test/api/data?token=%3Credacted%3E',
},
{
label: 'POST /api/data · External origin · api.example.test',
fullLabel: 'POST https://api.example.test/api/data',
},
])
})
it('orders spans by their recorded parent-child hierarchy', () => {
const request = createRequest({
spans: [
......
......@@ -3,6 +3,7 @@ import type {
RequestInsightFetch,
RequestInsightSpan,
} from '../../../shared/request-insights'
import { getFetchUrlPresentation } from './fetch-label'
export type TraceItem = {
id: string
......@@ -11,6 +12,7 @@ export type TraceItem = {
spanType?: string
category: 'nextjs' | 'application'
label: string
fullLabel?: string
startTime: number
durationMs?: number
status: 'ok' | 'error' | 'pending'
......@@ -23,6 +25,32 @@ export type TraceRange = {
durationMs: number
}
export function getTraceNavigationIndex(
currentIndex: number,
itemCount: number,
key: string
): number | undefined {
if (itemCount <= 0) {
return undefined
}
const lastIndex = itemCount - 1
const safeCurrentIndex = Math.min(Math.max(currentIndex, 0), lastIndex)
switch (key) {
case 'ArrowDown':
return Math.min(safeCurrentIndex + 1, lastIndex)
case 'ArrowUp':
return Math.max(safeCurrentIndex - 1, 0)
case 'Home':
return 0
case 'End':
return lastIndex
default:
return undefined
}
}
type UnnestedTraceItem = Omit<TraceItem, 'depth'>
const FETCH_SPAN_TYPE = 'AppRender.fetch'
......@@ -77,7 +105,8 @@ const SPAN_WORD_CASE: Record<string, string> = {
export function getTraceItems(
request: RequestInsight,
verbose: boolean
verbose: boolean,
currentOrigin?: string
): TraceItem[] {
const fetchSpansByIndex = new Map<number, RequestInsightSpan>()
......@@ -111,7 +140,7 @@ export function getTraceItems(
request.fetches.forEach((fetch, index) => {
const matchingSpan =
fetch.index === undefined ? undefined : fetchSpansByIndex.get(fetch.index)
const item = getFetchTraceItem(fetch, index, matchingSpan)
const item = getFetchTraceItem(fetch, index, matchingSpan, currentOrigin)
if (item) {
items.push(item)
}
......@@ -174,20 +203,25 @@ function getSpanTraceItem(
function getFetchTraceItem(
fetch: RequestInsightFetch,
index: number,
matchingSpan: RequestInsightSpan | undefined
matchingSpan: RequestInsightSpan | undefined,
currentOrigin: string | undefined
): UnnestedTraceItem | null {
const startTime = fetch.startTime ?? matchingSpan?.startTime
if (startTime === undefined) {
return null
}
const method = fetch.method ?? 'GET'
const url = getFetchUrlPresentation(fetch.url, currentOrigin)
return {
id: `fetch:${matchingSpan?.spanId ?? fetch.index ?? index}:${startTime}`,
spanId: matchingSpan?.spanId,
parentSpanId: matchingSpan?.parentSpanId,
spanType: FETCH_SPAN_TYPE,
category: matchingSpan ? getSpanCategory(matchingSpan) : 'application',
label: `${fetch.method ?? 'GET'} ${getUrlPath(fetch.url)}`,
label: `${method} ${url.path}${currentOrigin ? ` · ${url.originLabel}` : ''}`,
fullLabel: `${method} ${url.fullUrl}`,
startTime,
durationMs: fetch.durationMs ?? matchingSpan?.durationMs,
status:
......@@ -395,16 +429,3 @@ function getSpanLabel(span: RequestInsightSpan): string {
return words.join(' ')
}
function getUrlPath(url: string | undefined): string {
if (!url) {
return 'Unknown URL'
}
try {
const parsedUrl = new URL(url, 'http://localhost')
return `${parsedUrl.pathname}${parsedUrl.search}`
} catch {
return url
}
}
......@@ -5,6 +5,8 @@
}
.tooltip {
--tooltip-background: var(--color-gray-1000);
position: relative;
padding: 6px 12px;
border-radius: 8px;
......@@ -12,7 +14,7 @@
line-height: 1.4;
pointer-events: none;
color: var(--color-gray-100);
background-color: var(--color-gray-1000);
background-color: var(--tooltip-background);
}
.tooltip-arrow {
......@@ -27,7 +29,7 @@
.tooltip-arrow--top {
border-width: var(--arrow-size, 6px) var(--arrow-size, 6px) 0
var(--arrow-size, 6px);
border-top-color: var(--color-gray-1000);
border-top-color: var(--tooltip-background);
bottom: 0;
transform: translateY(100%);
}
......@@ -35,7 +37,7 @@
.tooltip-arrow--bottom {
border-width: 0 var(--arrow-size, 6px) var(--arrow-size, 6px)
var(--arrow-size, 6px);
border-bottom-color: var(--color-gray-1000);
border-bottom-color: var(--tooltip-background);
top: 0;
transform: translateY(-100%);
}
......@@ -43,7 +45,7 @@
.tooltip-arrow--left {
border-width: var(--arrow-size, 6px) 0 var(--arrow-size, 6px)
var(--arrow-size, 6px);
border-left-color: var(--color-gray-1000);
border-left-color: var(--tooltip-background);
right: 0;
transform: translateX(100%);
}
......@@ -51,7 +53,7 @@
.tooltip-arrow--right {
border-width: var(--arrow-size, 6px) var(--arrow-size, 6px)
var(--arrow-size, 6px) 0;
border-right-color: var(--color-gray-1000);
border-right-color: var(--tooltip-background);
left: 0;
transform: translateX(-100%);
}
......
import { forwardRef } from 'react'
import { forwardRef, isValidElement } from 'react'
import { Tooltip as BaseTooltip } from '@base-ui-components/react/tooltip'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { cx } from '../../utils/cx'
......@@ -9,72 +9,84 @@ type TooltipDirection = 'top' | 'bottom' | 'left' | 'right'
interface TooltipProps {
children: React.ReactNode
title: string | null
open?: React.ComponentProps<typeof BaseTooltip.Root>['open']
onOpenChange?: React.ComponentProps<typeof BaseTooltip.Root>['onOpenChange']
anchor?: React.ComponentProps<typeof BaseTooltip.Positioner>['anchor']
asChild?: boolean
direction?: TooltipDirection
arrowSize?: number
offset?: number
className?: string
}
export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
function Tooltip(
{
className,
children,
title,
direction = 'top',
arrowSize = 6,
offset = 8,
},
ref
) {
const { shadowRoot } = useDevOverlayContext()
if (!title) {
return children
}
return (
<BaseTooltip.Provider>
<BaseTooltip.Root delay={400}>
<BaseTooltip.Trigger
ref={ref}
render={(triggerProps) => {
return <span {...triggerProps}>{children}</span>
}}
/>
export const Tooltip = forwardRef<HTMLElement, TooltipProps>(function Tooltip(
{
className,
children,
title,
open,
onOpenChange,
anchor,
asChild = false,
direction = 'top',
arrowSize = 6,
offset = 8,
},
ref
) {
const { shadowRoot } = useDevOverlayContext()
if (!title) {
return children
}
return (
<BaseTooltip.Provider>
<BaseTooltip.Root delay={400} onOpenChange={onOpenChange} open={open}>
<BaseTooltip.Trigger
ref={ref}
render={
asChild && isValidElement<Record<string, unknown>>(children)
? children
: (triggerProps) => {
return <span {...triggerProps}>{children}</span>
}
}
/>
<BaseTooltip.Portal container={shadowRoot}>
<BaseTooltip.Positioner
side={direction}
sideOffset={offset + arrowSize}
className="tooltip-positioner"
<BaseTooltip.Portal container={shadowRoot}>
<BaseTooltip.Positioner
anchor={anchor}
positionMethod={anchor ? 'fixed' : undefined}
side={direction}
sideOffset={offset + arrowSize}
className="tooltip-positioner"
style={
{
'--anchor-width': `${arrowSize}px`,
'--anchor-height': `${arrowSize}px`,
} as React.CSSProperties
}
>
<BaseTooltip.Popup
className={cx('tooltip', className)}
style={
{
'--anchor-width': `${arrowSize}px`,
'--anchor-height': `${arrowSize}px`,
'--arrow-size': `${arrowSize}px`,
} as React.CSSProperties
}
>
<BaseTooltip.Popup
className={cx('tooltip', className)}
{title}
<BaseTooltip.Arrow
className={cx('tooltip-arrow', `tooltip-arrow--${direction}`)}
style={
{
'--arrow-size': `${arrowSize}px`,
} as React.CSSProperties
}
>
{title}
<BaseTooltip.Arrow
className={cx('tooltip-arrow', `tooltip-arrow--${direction}`)}
style={
{
'--arrow-size': `${arrowSize}px`,
} as React.CSSProperties
}
/>
</BaseTooltip.Popup>
</BaseTooltip.Positioner>
</BaseTooltip.Portal>
</BaseTooltip.Root>
</BaseTooltip.Provider>
)
}
)
/>
</BaseTooltip.Popup>
</BaseTooltip.Positioner>
</BaseTooltip.Portal>
</BaseTooltip.Root>
</BaseTooltip.Provider>
)
})
......@@ -374,6 +374,7 @@ export const PanelRouter = () => {
{isAppRouter && !!process.env.__NEXT_REQUEST_INSIGHTS && (
<PanelRoute name="request-insights">
<DynamicPanel
containerProps={{ className: 'request-insights-panel-container' }}
sharePanelSizeGlobally={false}
sharePanelPositionGlobally={false}
draggable
......
......@@ -612,17 +612,18 @@ describe('request insights', () => {
it('redacts sensitive request insight payload fields', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const secret = 'Q2_SECRET_SENTINEL'
recordSpan({
name: 'fetch GET https://example.vercel.sh/api',
name: `fetch GET https://example.vercel.sh/api?token=${secret}`,
startTime: 100,
durationMs: 10,
requestId: 'req_4',
route: '/account',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url':
'https://user:pass@example.vercel.sh/api?access_token=abc&delay=1&signature=sig',
'http.url': `https://user:pass@example.vercel.sh/api?access_token=${secret}&delay=1&signature=sig`,
'http.method': 'GET',
'next.span_name': `fetch GET https://user:pass@example.vercel.sh/api?access_token=${secret}`,
'custom.secret': 'should not be exposed',
},
events: [
......@@ -662,11 +663,13 @@ describe('request insights', () => {
expect.objectContaining({
spans: [
expect.objectContaining({
name: 'fetch GET https://example.vercel.sh/api?query=redacted',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url':
'https://example.vercel.sh/api?access_token=redacted&delay=1&signature=redacted',
'http.url': 'https://example.vercel.sh/api?query=redacted',
'http.method': 'GET',
'next.span_name':
'fetch GET https://example.vercel.sh/api?query=redacted',
},
events: [
{
......@@ -688,13 +691,95 @@ describe('request insights', () => {
],
fetches: [
expect.objectContaining({
url: 'https://example.vercel.sh/api?access_token=redacted&delay=1&signature=redacted',
url: 'https://example.vercel.sh/api?query=redacted',
}),
expect.objectContaining({
url: 'https://example.vercel.sh/api?token=redacted&keep=1',
url: 'https://example.vercel.sh/api?query=redacted',
}),
],
})
)
expect(JSON.stringify(getRequestInsightsSnapshot())).not.toContain(secret)
})
it('only exposes bounded URLs without query payloads', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const cases = [
{
requestId: 'relative',
input: '/products/blue?sort=price#details',
expected: '/products/blue?query=redacted',
},
{
requestId: 'protocol-relative',
input: '//example.com/items?cursor=secret',
expected: '//example.com/items?query=redacted',
},
{
requestId: 'absolute',
input: 'https://user:password@example.com/items?visible=value#details',
expected: 'https://example.com/items?query=redacted',
},
{
requestId: 'opaque',
input: 'data:text/plain,secret',
expected: 'data:redacted',
},
{
requestId: 'untrusted-relative',
input: 'items?token=secret',
expected: undefined,
},
] as const
for (const testCase of cases) {
recordRequestInsightFetch(
{ requestId: testCase.requestId },
{ url: testCase.input, startTime: 100, durationMs: 1 }
)
}
const requests = new Map(
getRequestInsightsSnapshot().requests.map((request) => [
request.requestId,
request,
])
)
for (const testCase of cases) {
expect(requests.get(testCase.requestId)?.fetches[0]?.url).toBe(
testCase.expected
)
}
recordRequestInsightFetch(
{ requestId: 'oversized' },
{
url: `https://example.com/${'x'.repeat(64 * 1024)}`,
startTime: 100,
durationMs: 1,
}
)
expect(
getRequestInsightsSnapshot().requests.find(
(request) => request.requestId === 'oversized'
)?.fetches[0]?.url
).toBeUndefined()
recordRequestInsightFetch(
{ requestId: 'query-name' },
{
url: 'https://example.com/items?sk_live_SENTINEL',
startTime: 100,
durationMs: 1,
}
)
expect(
JSON.stringify(
getRequestInsightsSnapshot().requests.find(
(request) => request.requestId === 'query-name'
)
)
).not.toContain('sk_live_SENTINEL')
})
})
......@@ -29,6 +29,8 @@ import { reparentLocalSpans } from './local-span-recorder'
export { isRequestInsightsEnabled } from './span-store'
const MAX_REQUEST_INSIGHTS = 100
const MAX_REQUEST_INSIGHT_URL_LENGTH = 2048
const MAX_REQUEST_INSIGHT_RAW_URL_LENGTH = 64 * 1024
const REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')
const CLIENT_COMPONENT_LOADING_SPAN_TYPE =
'NextNodeServer.clientComponentLoading'
......@@ -63,9 +65,6 @@ const SAFE_SPAN_ATTRIBUTE_KEYS = new Set([
'next.span_name',
'next.span_type',
])
const SENSITIVE_PARAM_NAME_RE =
/(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i
class InMemoryRequestInsightsStore {
private readonly requests = new Map<string, RequestInsight>()
private readonly requestTimings = new Map<
......@@ -123,7 +122,7 @@ class InMemoryRequestInsightsStore {
: insight.status
insight.spans.push({
name: span.name,
name: sanitizeSpanName(span),
startTime: spanStartTime,
durationMs: span.durationMs,
status: span.status,
......@@ -510,17 +509,45 @@ function sanitizeSpanAttributes(
}
const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}
const sanitizedFetchSpanName =
attributes['next.span_type'] === 'AppRender.fetch'
? getSanitizedFetchSpanName(attributes)
: undefined
for (const [key, value] of Object.entries(attributes)) {
if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {
continue
}
sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value
sanitized[key] =
key === 'http.url'
? sanitizeUrlAttribute(value)
: key === 'next.span_name' && sanitizedFetchSpanName
? sanitizedFetchSpanName
: value
}
return Object.keys(sanitized).length > 0 ? sanitized : undefined
}
function sanitizeSpanName(span: SpanStoreRecord): string {
if (span.attributes?.['next.span_type'] !== 'AppRender.fetch') {
return span.name
}
return getSanitizedFetchSpanName(span.attributes, span.url)
}
function getSanitizedFetchSpanName(
attributes: NonNullable<SpanStoreRecord['attributes']>,
fallbackUrl?: string
): string {
const method = getStringAttribute(attributes['http.method'])
const url = sanitizeUrl(
getStringAttribute(attributes['http.url']) ?? fallbackUrl
)
return ['fetch', method, url].filter(Boolean).join(' ')
}
function sanitizeSpanEvents(
events: SpanStoreRecord['events']
): SpanStoreRecord['events'] {
......@@ -548,24 +575,67 @@ function sanitizeUrl(value: string | undefined): string | undefined {
return value
}
const isRelativeUrl = value.startsWith('/')
if (value.length > MAX_REQUEST_INSIGHT_RAW_URL_LENGTH) {
return undefined
}
const isProtocolRelativeUrl = value.startsWith('//')
const isRootRelativeUrl = !isProtocolRelativeUrl && value.startsWith('/')
const hasProtocol = /^[a-z][a-z\d+.-]*:/i.test(value)
if (!isProtocolRelativeUrl && !isRootRelativeUrl && !hasProtocol) {
return undefined
}
try {
const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)
const url =
isProtocolRelativeUrl || isRootRelativeUrl
? new URL(value, 'http://n')
: new URL(value)
if (
url.protocol !== 'http:' &&
url.protocol !== 'https:' &&
!isProtocolRelativeUrl &&
!isRootRelativeUrl
) {
return `${url.protocol}${REDACTED_VALUE}`
}
url.username = ''
url.password = ''
url.hash = ''
for (const name of Array.from(url.searchParams.keys())) {
if (SENSITIVE_PARAM_NAME_RE.test(name)) {
url.searchParams.set(name, REDACTED_VALUE)
}
}
const hasApplicationQuery = Array.from(url.searchParams.keys()).some(
(name) => name !== '_rsc'
)
url.search = hasApplicationQuery ? `?query=${REDACTED_VALUE}` : ''
const sanitizedUrl = isProtocolRelativeUrl
? `//${url.host}${url.pathname}${url.search}`
: isRootRelativeUrl
? `${url.pathname}${url.search}`
: url.href
return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href
return truncateText(sanitizedUrl, MAX_REQUEST_INSIGHT_URL_LENGTH)
} catch {
return undefined
}
}
function truncateText(value: string, maxLength: number): string {
if (value.length <= maxLength) {
return value
}
let end = Math.max(0, maxLength - 1)
if (end > 0) {
const lastCharCode = value.charCodeAt(end - 1)
if (lastCharCode >= 0xd800 && lastCharCode <= 0xdbff) {
end--
}
}
return `${value.slice(0, end)}…`
}
function getStringAttribute(value: AttributeValue | undefined) {
......
import { EmitRequestInsightsSnapshot } from './snapshot-button'
export const instant = { level: 'experimental-error' }
export default function Page() {
return <p>instant insights</p>
return (
<>
<p>instant insights</p>
<EmitRequestInsightsSnapshot />
</>
)
}
'use client'
import { dispatcher } from 'next/dist/compiled/next-devtools'
export function EmitRequestInsightsSnapshot() {
return (
<button
id="emit-request-insights-snapshot"
onClick={() => {
const startTime = Date.now()
dispatcher.onRequestInsightsSnapshot({
requests: [
...Array.from({ length: 40 }, (_, index) => ({
requestId: `synthetic-request-${index}`,
kind: 'request' as const,
source: 'page' as const,
htmlRequestId: `synthetic-document-${index}`,
route: `/synthetic-${index}`,
url: `/synthetic-${index}`,
startTime: startTime + index,
durationMs: index + 1,
status: 'ok' as const,
spans: [],
fetches: [],
})),
{
requestId: 'synthetic-internal-request',
kind: 'instant-insights',
source: 'instant-insights',
htmlRequestId: 'synthetic-internal-document',
route: '/synthetic-internal',
url: '/synthetic-internal',
startTime: startTime + 40,
durationMs: 1,
status: 'ok',
spans: [
{
name: 'Run validation',
startTime: startTime + 40,
durationMs: 1,
status: 'ok',
attributes: {
'next.span_type': 'AppRender.instantInsights.runValidation',
'next.request_insights.omitted_spans': 3,
},
},
],
fetches: [],
},
],
})
}}
type="button"
>
Emit Request Insights snapshot
</button>
)
}
import { headers } from 'next/headers'
import { connection } from 'next/server'
export const instant = false
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
await connection()
const { id } = await params
const host = (await headers()).get('host')
if (!host) {
throw new Error('Missing request host')
}
await fetch(`http://${host}/api/source?token=Q2_SECRET_SENTINEL`, {
cache: 'no-store',
})
return <p id="product-id">{id}</p>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment