From e3ae2c68398a24a270f0c03a88dd07b67a9bd5b6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:57:28 +0000 Subject: [PATCH 1/3] fix(cli): Verify only on telemetry that matches the filters `local run --verify` passed on the first envelope of any kind, so an app that only called Sentry.init() verified from its session envelope, and `-f error` verified without any error. Count an envelope only when it holds an item the active filters show, through the same filter check the tail uses. With no filters, only telemetry counts: errors, transactions, spans, logs and replays, not sessions or client reports. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/cli-docs/src/fragments/commands/local.md | 2 +- .../skills/sentry-cli/references/local.md | 2 +- packages/cli/src/commands/local/run.ts | 13 ++++- packages/cli/src/lib/formatters/local.ts | 31 +++++++++++ packages/cli/test/commands/local/run.test.ts | 55 +++++++++++++++++++ 5 files changed, 98 insertions(+), 5 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index a40d0a970..043a901ed 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -46,7 +46,7 @@ When `local run` sees `wrangler dev` and a `wrangler.json`, `wrangler.jsonc`, or ### Check your setup with `--verify` -`sentry local run --verify -- ` starts your app, waits for its first event, then stops it. It exits 0 once an event arrives. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout `). When port 8969 is busy, it verifies on a free port. +`sentry local run --verify -- ` starts your app, waits for its first event, then stops it. It exits 0 once an error, transaction, span, log or replay arrives, or, with `--filter`, an item of those types. Sessions and client reports alone don't count. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout `). When port 8969 is busy, it verifies on a free port. A Cloudflare Worker sends nothing until it handles a request, so send one to it while `--verify` waits. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md index b648fa4bc..936723518 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md @@ -192,7 +192,7 @@ Run a command with the local dev server enabled - `-p, --port - Port for the local server (default: 8969)` - `--host - Hostname for the local server - (default: "localhost")` - `-f, --filter ... - Only show items of this type (repeatable: error, transaction, log, ai)` -- `-V, --verify - Verify SDK sends events, then exit` +- `-V, --verify - Wait for the app's first event (of the --filter types, if set), then exit` - `-t, --timeout - Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode) - (default: "0")` - `-F, --format - Output format: human (default) or json (NDJSON on stdout) - (default: "human")` - `-a, --attributes - Also show SDK attributes, under each transaction, span and log or in JSON` diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 3e0586f03..086470b7b 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -51,6 +51,7 @@ import { type FilterValue, FORMAT_VALUES, createReplayTracker, + envelopeHasTelemetry, formatEnvelopeLines, formatEnvelopeLinesJson, type FormatValue, @@ -585,7 +586,8 @@ export const runCommand = buildCommand({ }, verify: { kind: "boolean", - brief: "Verify SDK sends events, then exit", + brief: + "Wait for the app's first event (of the --filter types, if set), then exit", default: false, }, timeout: { @@ -1040,10 +1042,15 @@ async function* runWithVerify( const spotlightUrl = `${url}/stream`; + // Only telemetry the active filters show counts: an SDK sends sessions and + // client reports even when nothing else reaches Sentry Local. + const activeFilters = new Set(flags.filter); let subscriptionId: string | undefined; const envelopeReceived = new Promise((resolveEnvelope) => { - subscriptionId = buffer.subscribe(() => { - resolveEnvelope(); + subscriptionId = buffer.subscribe((container) => { + if (envelopeHasTelemetry(container, activeFilters)) { + resolveEnvelope(); + } }); }); diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index 2f4eae0d3..f72dbce01 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -1525,6 +1525,37 @@ function transactionHasAiActivity(payload: Record): boolean { return false; } +/** Item types an SDK sends as telemetry, unlike `session` or `client_report`. */ +const TELEMETRY_ITEM_TYPES = new Set([ + ...ERROR_TYPES, + "transaction", + "span", + "log", + "replay_event", + "replay_recording", + "replay_video", +]); + +/** + * Whether an envelope shows the app is set up: it holds an item the active + * filters let through, or, with no filters, any telemetry item. + */ +export function envelopeHasTelemetry( + container: { + getParsedEnvelope: () => { + envelope: [Record, [{ type?: string }, unknown][]]; + } | null; + }, + activeFilters: ReadonlySet, +): boolean { + const items = container.getParsedEnvelope()?.envelope[1] ?? []; + return items.some(([{ type }, payload]) => + activeFilters.size > 0 + ? isItemIncluded(type, activeFilters, payload as Record) + : TELEMETRY_ITEM_TYPES.has(type ?? ""), + ); +} + /** * Format a freshly received envelope as NDJSON lines. * diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index c657437f0..86c96d921 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1233,6 +1233,16 @@ const SEND_ONE_EVENT = [ ].join(" "), ]; +/** Node `-e` args for an app that posts one envelope per item type, in order. */ +function sendItems(...types: string[]): string[] { + return [ + "-e", + `const id = "b".repeat(32); +const send = (type) => fetch(process.env.SENTRY_SPOTLIGHT, { method: "POST", headers: { "content-type": "application/x-sentry-envelope" }, body: [JSON.stringify({ event_id: id }), JSON.stringify({ type }), JSON.stringify({ event_id: id, type, message: "verify me" })].join(String.fromCharCode(10)) }); +(async () => { for (const type of ${JSON.stringify(types)}) await send(type); setTimeout(() => {}, 30000); })();`, + ]; +} + /** Hold `port` on `host`; resolves undefined when something already holds it. */ async function holdPort( port: number, @@ -1307,6 +1317,51 @@ describe("sentry local run --verify receiver", () => { } }); + test.each([ + { sent: ["session", "client_report"], filter: [] }, + { sent: ["transaction", "log"], filter: ["error" as const] }, + ])( + "times out when only $sent arrive (filter: $filter)", + async ({ sent, filter }) => { + const func = (await runCommand.loader()) as unknown as RunFunc; + const error = await func + .call( + makeContext(), + { port: 0, host: "127.0.0.1", verify: true, timeout: 2, filter }, + process.execPath, + ...sendItems(...sent), + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as CliError).message).toContain("Verification timed out"); + expect((error as CliError).exitCode).toBe(64); + }, + ); + + test.each([ + { sent: ["session", "log"], filter: [] }, + { sent: ["transaction", "event"], filter: ["error" as const] }, + ])( + "verifies once $sent arrive (filter: $filter)", + async ({ sent, filter }) => { + const info = vi.spyOn(logger, "info").mockImplementation(() => {}); + try { + const func = (await runCommand.loader()) as unknown as RunFunc; + await func.call( + makeContext(), + { port: 0, host: "127.0.0.1", verify: true, timeout: 20, filter }, + process.execPath, + ...sendItems(...sent), + ); + expect(info.mock.calls.map((c) => String(c[0]))).toContain( + "Setup verified — your app is sending events to Sentry Local", + ); + } finally { + info.mockRestore(); + } + }, + ); + test("verifies on a free port when the default port is busy", async () => { const busy = makeDefaultPortBusy(); const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); From dcc147c9563d2f78d32aac68aa7928197fdcd9b1 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:54:07 +0000 Subject: [PATCH 2/3] fix(cli): Count any non-housekeeping item and say when the SDK connected Treat every item type except session, sessions and client_report as telemetry for --verify, so check-ins, feedback, metrics and profiles verify a setup, and item types that SDKs add later count too. When only uncounted items arrived, the timeout and early-exit errors now say the SDK connected and what it sent, instead of "no events received" and the DSN and port hints, which don't apply then. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/cli-docs/src/content/docs/exit-codes.md | 2 +- apps/cli-docs/src/fragments/commands/local.md | 2 +- packages/cli/src/commands/local/run.ts | 32 +++++++- packages/cli/src/lib/formatters/local.ts | 23 +++--- packages/cli/test/commands/local/run.test.ts | 78 ++++++++++++++----- .../cli/test/lib/formatters/local.test.ts | 66 ++++++++++++++++ 6 files changed, 169 insertions(+), 34 deletions(-) diff --git a/apps/cli-docs/src/content/docs/exit-codes.md b/apps/cli-docs/src/content/docs/exit-codes.md index b3beeaedd..4c1e4bb0d 100644 --- a/apps/cli-docs/src/content/docs/exit-codes.md +++ b/apps/cli-docs/src/content/docs/exit-codes.md @@ -44,7 +44,7 @@ react to failure categories without parsing stderr. | 50 | Upgrade Error | CLI upgrade operation failed | | 51 | Device Flow Error | OAuth device authorization flow failed | | 60 | Output Error | Command produced output but the operation failed | -| 64 | Verify Failed | `sentry local run --verify` received no events from the SDK | +| 64 | Verify Failed | `sentry local run --verify` received no matching events from the SDK | | 252 | Invalid Argument | An argument could not be parsed — see [Argument errors](#argument-errors) | ## Scripting Examples diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index 043a901ed..aed760381 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -46,7 +46,7 @@ When `local run` sees `wrangler dev` and a `wrangler.json`, `wrangler.jsonc`, or ### Check your setup with `--verify` -`sentry local run --verify -- ` starts your app, waits for its first event, then stops it. It exits 0 once an error, transaction, span, log or replay arrives, or, with `--filter`, an item of those types. Sessions and client reports alone don't count. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout `). When port 8969 is busy, it verifies on a free port. +`sentry local run --verify -- ` starts your app, waits for its first event, then stops it. It exits 0 once the SDK sends telemetry: any item other than a session or client report or, with `--filter`, an item that `--filter` would show in the tail. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout `). When port 8969 is busy, it verifies on a free port. A Cloudflare Worker sends nothing until it handles a request, so send one to it while `--verify` waits. diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 086470b7b..d04e960a0 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -1043,16 +1043,32 @@ async function* runWithVerify( const spotlightUrl = `${url}/stream`; // Only telemetry the active filters show counts: an SDK sends sessions and - // client reports even when nothing else reaches Sentry Local. + // client reports even when nothing else reaches Sentry Local. Remember what + // did arrive, so a timeout can say the SDK connected. const activeFilters = new Set(flags.filter); + const uncountedTypes = new Set(); let subscriptionId: string | undefined; const envelopeReceived = new Promise((resolveEnvelope) => { subscriptionId = buffer.subscribe((container) => { if (envelopeHasTelemetry(container, activeFilters)) { resolveEnvelope(); + return; + } + for (const [{ type }] of container.getParsedEnvelope()?.envelope[1] ?? + []) { + if (type) { + uncountedTypes.add(type); + } } }); }); + const connectedNote = (): string | undefined => { + if (uncountedTypes.size === 0) { + return; + } + const filters = [...activeFilters].map((f) => `-f ${f}`).join(" "); + return `the SDK connected but sent only ${[...uncountedTypes].join(", ")}${filters ? ` (nothing matching ${filters})` : ""}`; + }; const childEnv = buildChildEnv(spotlightUrl, commandSource, cwd); const wrangler = await injectWranglerSpotlightBinding( @@ -1183,6 +1199,13 @@ async function* runWithVerify( return; } case "timeout": { + const connected = connectedNote(); + if (connected) { + // The SDK reached this receiver, so the DSN and port hints don't apply. + throw new VerifyFailedError( + `Verification timed out after ${verifyTimeout}s: ${connected}`, + ); + } if (wrangler.injected) { logger.warn( `A Worker sends nothing until it handles a request, so send one to it while --verify waits. ${wranglerSetupHint()}`, @@ -1209,7 +1232,12 @@ async function* runWithVerify( throw spawnFailureError(wrangler.args[0] ?? "", spawnError, cwd); } if (outcome.code === 0) { - throw new VerifyFailedError("Process exited before sending any events"); + const connected = connectedNote(); + throw new VerifyFailedError( + connected + ? `Process exited before verifying: ${connected}` + : "Process exited before sending any events", + ); } throw new VerifyFailedError( `Process crashed with code ${outcome.code}`, diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index f72dbce01..5140c67bb 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -1525,20 +1525,21 @@ function transactionHasAiActivity(payload: Record): boolean { return false; } -/** Item types an SDK sends as telemetry, unlike `session` or `client_report`. */ -const TELEMETRY_ITEM_TYPES = new Set([ - ...ERROR_TYPES, - "transaction", - "span", - "log", - "replay_event", - "replay_recording", - "replay_video", +/** + * Housekeeping item types an SDK sends on its own, even when nothing else + * reaches Sentry Local. Every other type counts as telemetry, so item types + * that SDKs add later count without a change here. + */ +const NOT_TELEMETRY_ITEM_TYPES = new Set([ + "session", + "sessions", + "client_report", ]); /** * Whether an envelope shows the app is set up: it holds an item the active - * filters let through, or, with no filters, any telemetry item. + * filters let through, or, with no filters, any item that is not + * housekeeping. */ export function envelopeHasTelemetry( container: { @@ -1552,7 +1553,7 @@ export function envelopeHasTelemetry( return items.some(([{ type }, payload]) => activeFilters.size > 0 ? isItemIncluded(type, activeFilters, payload as Record) - : TELEMETRY_ITEM_TYPES.has(type ?? ""), + : type !== undefined && !NOT_TELEMETRY_ITEM_TYPES.has(type), ); } diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index 86c96d921..d7892d91b 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1233,13 +1233,16 @@ const SEND_ONE_EVENT = [ ].join(" "), ]; -/** Node `-e` args for an app that posts one envelope per item type, in order. */ -function sendItems(...types: string[]): string[] { +/** + * Node `-e` args for an app that posts one envelope per item type, in order, + * then stays up (or exits 0 with `thenExit`). + */ +function sendItems(types: string[], thenExit = false): string[] { return [ "-e", `const id = "b".repeat(32); const send = (type) => fetch(process.env.SENTRY_SPOTLIGHT, { method: "POST", headers: { "content-type": "application/x-sentry-envelope" }, body: [JSON.stringify({ event_id: id }), JSON.stringify({ type }), JSON.stringify({ event_id: id, type, message: "verify me" })].join(String.fromCharCode(10)) }); -(async () => { for (const type of ${JSON.stringify(types)}) await send(type); setTimeout(() => {}, 30000); })();`, +(async () => { for (const type of ${JSON.stringify(types)}) await send(type); ${thenExit ? "process.exit(0);" : "setTimeout(() => {}, 30000);"} })();`, ]; } @@ -1318,28 +1321,65 @@ describe("sentry local run --verify receiver", () => { }); test.each([ - { sent: ["session", "client_report"], filter: [] }, - { sent: ["transaction", "log"], filter: ["error" as const] }, + { + sent: ["session", "client_report"], + filter: [], + message: + "Verification timed out after 2s: the SDK connected but sent only session, client_report", + }, + { + sent: ["transaction", "log"], + filter: ["error" as const], + message: + "Verification timed out after 2s: the SDK connected but sent only transaction, log (nothing matching -f error)", + }, ])( "times out when only $sent arrive (filter: $filter)", - async ({ sent, filter }) => { - const func = (await runCommand.loader()) as unknown as RunFunc; - const error = await func - .call( - makeContext(), - { port: 0, host: "127.0.0.1", verify: true, timeout: 2, filter }, - process.execPath, - ...sendItems(...sent), - ) - .catch((err: unknown) => err); - expect(error).toBeInstanceOf(VerifyFailedError); - expect((error as CliError).message).toContain("Verification timed out"); - expect((error as CliError).exitCode).toBe(64); + async ({ sent, filter, message }) => { + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + try { + const func = (await runCommand.loader()) as unknown as RunFunc; + const error = await func + .call( + makeContext(), + { port: 0, host: "127.0.0.1", verify: true, timeout: 2, filter }, + process.execPath, + ...sendItems(sent), + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as CliError).message).toBe(message); + expect((error as CliError).exitCode).toBe(64); + // The SDK reached the receiver, so the DSN hint would mislead. + expect( + warn.mock.calls.map((c) => String(c[0])).join("\n"), + ).not.toContain("SENTRY_DSN"); + } finally { + warn.mockRestore(); + } }, ); + test("says the SDK connected when the app exits after only a session", async () => { + const func = (await runCommand.loader()) as unknown as RunFunc; + const error = await func + .call( + makeContext(), + { port: 0, host: "127.0.0.1", verify: true, timeout: 20, filter: [] }, + process.execPath, + ...sendItems(["session"], true), + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as CliError).message).toBe( + "Process exited before verifying: the SDK connected but sent only session", + ); + expect((error as CliError).exitCode).toBe(64); + }); + test.each([ { sent: ["session", "log"], filter: [] }, + { sent: ["session", "check_in"], filter: [] }, { sent: ["transaction", "event"], filter: ["error" as const] }, ])( "verifies once $sent arrive (filter: $filter)", @@ -1351,7 +1391,7 @@ describe("sentry local run --verify receiver", () => { makeContext(), { port: 0, host: "127.0.0.1", verify: true, timeout: 20, filter }, process.execPath, - ...sendItems(...sent), + ...sendItems(sent), ); expect(info.mock.calls.map((c) => String(c[0]))).toContain( "Setup verified — your app is sending events to Sentry Local", diff --git a/packages/cli/test/lib/formatters/local.test.ts b/packages/cli/test/lib/formatters/local.test.ts index c20e90e1a..ddf85cb06 100644 --- a/packages/cli/test/lib/formatters/local.test.ts +++ b/packages/cli/test/lib/formatters/local.test.ts @@ -9,6 +9,7 @@ import { describe, expect, test } from "vitest"; import type { FilterValue } from "../../../src/lib/formatters/local.js"; import { + envelopeHasTelemetry, extractTraceId, formatAttributeTable, formatErrorItem, @@ -1497,3 +1498,68 @@ describe("sentry-python ISO 8601 timestamps", () => { ); }); }); + +describe("envelopeHasTelemetry", () => { + const envelope = (...items: [string, unknown][]) => ({ + getParsedEnvelope: () => ({ + envelope: [{}, items.map(([type, payload]) => [{ type }, payload])] as [ + Record, + [{ type?: string }, unknown][], + ], + }), + }); + const emptyLogBatch: [string, unknown] = ["log", { items: [] }]; + + test.each<{ + items: [string, unknown][]; + filters: FilterValue[]; + counts: boolean; + }>([ + { items: [["session", {}]], filters: [], counts: false }, + { items: [["sessions", {}]], filters: [], counts: false }, + { items: [["client_report", {}]], filters: [], counts: false }, + { + items: [ + ["session", {}], + ["client_report", {}], + ], + filters: [], + counts: false, + }, + { items: [["event", {}]], filters: [], counts: true }, + { items: [["check_in", {}]], filters: [], counts: true }, + { items: [["feedback", {}]], filters: [], counts: true }, + { items: [["trace_metric", {}]], filters: [], counts: true }, + { items: [["profile_chunk", {}]], filters: [], counts: true }, + { + items: [ + ["session", {}], + ["transaction", {}], + ], + filters: [], + counts: true, + }, + { items: [emptyLogBatch], filters: [], counts: true }, + { items: [emptyLogBatch], filters: ["log"], counts: true }, + { items: [emptyLogBatch], filters: ["error"], counts: false }, + { items: [["transaction", {}]], filters: ["error"], counts: false }, + { items: [["session", {}]], filters: ["error"], counts: false }, + { items: [["event", {}]], filters: ["error"], counts: true }, + { items: [["check_in", {}]], filters: ["transaction"], counts: false }, + { items: [["span", {}]], filters: ["transaction"], counts: true }, + { items: [["transaction", {}]], filters: ["ai"], counts: false }, + ])( + "$items with filters $filters counts: $counts", + ({ items, filters, counts }) => { + expect(envelopeHasTelemetry(envelope(...items), new Set(filters))).toBe( + counts, + ); + }, + ); + + test("an unparseable envelope does not count", () => { + expect( + envelopeHasTelemetry({ getParsedEnvelope: () => null }, new Set()), + ).toBe(false); + }); +}); From 63850ced56afaf371ac850975fe3cf238b57a95c Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:37:30 +0000 Subject: [PATCH 3/3] fix(cli): Sanitize item types in the --verify diagnostic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Envelope item types come from untrusted HTTP input. Run them through the same sanitize helper the Local tail uses before they reach the "SDK connected but sent only …" error, so ANSI/OSC escapes, control characters, BiDi controls and newlines can't reach the terminal. --- packages/cli/src/commands/local/run.ts | 7 +++++-- packages/cli/test/commands/local/run.test.ts | 22 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index d04e960a0..2bec86043 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -56,6 +56,7 @@ import { formatEnvelopeLinesJson, type FormatValue, printLocalViewerHint, + sanitize, } from "../../lib/formatters/local.js"; import { logger, printJsonLine, printLine } from "../../lib/logger.js"; import { spawnFailureError } from "../../lib/spawn-failure.js"; @@ -1056,8 +1057,10 @@ async function* runWithVerify( } for (const [{ type }] of container.getParsedEnvelope()?.envelope[1] ?? []) { - if (type) { - uncountedTypes.add(type); + // Item types are untrusted input that ends up in the terminal. + const safeType = type ? sanitize(type).trim() : ""; + if (safeType) { + uncountedTypes.add(safeType); } } }); diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index d7892d91b..3744339d3 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1360,6 +1360,28 @@ describe("sentry local run --verify receiver", () => { }, ); + test("strips terminal escapes and line breaks from item types in the error", async () => { + const func = (await runCommand.loader()) as unknown as RunFunc; + const error = await func + .call( + makeContext(), + { + port: 0, + host: "127.0.0.1", + verify: true, + timeout: 2, + filter: ["error" as const], + }, + process.execPath, + ...sendItems(["\u001b[31mevil\u001b[0m\nError: forged \u202eline"]), + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as CliError).message).toBe( + "Verification timed out after 2s: the SDK connected but sent only evil Error: forged line (nothing matching -f error)", + ); + }); + test("says the SDK connected when the app exits after only a session", async () => { const func = (await runCommand.loader()) as unknown as RunFunc; const error = await func