Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Weekly dependency and GitHub Actions updates (JS-SEC-026).
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 10
groups:
opentelemetry:
patterns: ["@opentelemetry/*"]
traceloop:
patterns: ["@traceloop/*"]
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
81 changes: 81 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
name: CI

# Type-checks, tests and builds every change, and checks that the CommonJS
# build loads with require() on the oldest Node versions `engines` allows
# (JS-SEC-020, JS-SEC-026, JS-PERF-004).

on:
pull_request:
push:
branches: [main, dev]

permissions:
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
test:
name: Test (Node ${{ matrix.node }})
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
node: [20, 22, 24]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: npm
- run: npm ci
- run: npx tsc --noEmit -p .
- run: npx vitest run
- run: npm run build
- name: Upload build
if: matrix.node == 22
uses: actions/upload-artifact@v4
with:
name: dist
path: dist
retention-days: 1

require-cjs:
name: require() on Node ${{ matrix.node }}
needs: test
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
# Versions without require(esm): an ESM-only runtime dependency makes
# require("netra-sdk") throw ERR_REQUIRE_ESM here.
node: ["18", "20.18.0", "22.11.0"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- uses: actions/download-artifact@v4
with:
name: dist
path: dist
- run: npm ci --omit=dev --ignore-scripts --no-audit --no-fund
- run: node -e "const { Netra } = require('./dist/index.cjs'); if (typeof Netra?.init !== 'function') process.exit(1); console.log('require() ok')"

audit:
name: npm audit (production dependencies)
runs-on: ubuntu-latest
timeout-minutes: 5
# Reported, not blocking: some advisories come in through
# @traceloop/node-server-sdk with no fix available yet (JS-SEC-019).
continue-on-error: true
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm audit --omit=dev --audit-level=high
47 changes: 47 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,53 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- **`Netra.withSession()` and `Netra.clearSession()`**: `Netra.withSession({ userId, sessionId, tenantId }, fn)` applies the identity to every span started inside `fn`. `Netra.clearSession()` clears the identity set for the current request or async flow.

### Changed

- **Identity Stays in Your Process**: `setSessionId`, `setUserId` and `setTenantId` no longer write W3C baggage, so the values are no longer sent in the `baggage` header of every outgoing HTTP and `fetch` request, for example to AI providers (JS-SEC-002). The values apply to the current request or async flow only. A value set in one request no longer shows up on later requests that set none (JS-SEC-003). Calling a setter before `Netra.init()`, or with a context manager other than Netra's registered first, now prints a one-time warning, and the value applies only to the active span.
- **Incoming Baggage Is No Longer Trusted**: `user_id`, `session_id`, `tenant_id` and `custom_keys` in an incoming `baggage` header no longer set the identity or custom attributes of the request's spans. `netra.*` baggage keys are dropped on incoming and outgoing requests, so a caller can no longer hide its requests by sending `netra.local_blocked_spans` (JS-SEC-001). `withBlockedSpansLocal` and `startSpan`'s `blockedSpans` still work, and their patterns are no longer sent to downstream services.
- **`traceContent: false` Applies Everywhere**: Function arguments and return values from `@workflow`, `@agent`, `@task` and `@span`, LangGraph graph state, node and tool input and output, and OpenAI Agents prompts, instructions, completions, tool input and output, MCP data and custom span data are no longer recorded when content tracing is off. Explicit `setInput`, `setOutput`, `setRootInput`, `setRootOutput` and `addConversation` calls are also dropped. Content keys are filtered centrally, so no integration can record them. This includes the OpenTelemetry GenAI keys (`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.call.arguments`/`result`) that Traceloop's LangChain integration kept writing with content off (JS-SEC-004).
- **Tool Definitions Are Redacted**: Credentials in tool definitions, such as remote MCP `headers`, connector `authorization` and `authorization_token`, are recorded as `[REDACTED]`. With content tracing off, only each tool's type and name are recorded (JS-SEC-005).
- **Database Query Parameters Are Opt-In**: TypeORM spans no longer record query parameter values such as emails and reset tokens. They record `db.statement.parameters.count` instead. Set `NETRA_TRACE_DB_PARAMETERS=true` to record the values; it takes effect only while content capture is on (JS-SEC-016).
- **The API Key Only Goes to Netra**: Whether an endpoint belongs to Netra is now decided by its host (`getnetra.ai` and its subdomains), not by `getnetra` appearing anywhere in the URL. When the endpoint comes only from `OTEL_EXPORTER_OTLP_ENDPOINT` and is not a Netra host, `NETRA_API_KEY` is no longer sent to it, by the span exporter or the API clients, and a warning says so. An explicit `NETRA_OTLP_ENDPOINT`, including a self-hosted Netra, still receives the key (JS-SEC-006).
- **No Secrets or Shared Settings in `process.env`**: `Netra.init()` no longer copies the API key, the export headers or the endpoint into `TRACELOOP_API_KEY`, `TRACELOOP_HEADERS` and `TRACELOOP_BASE_URL`, which every child process inherited, and no longer overwrites `TRACELOOP_TRACE_CONTENT`. `OTEL_RESOURCE_ATTRIBUTES` is set only while the tracer starts and is then restored. The `headers` object passed to `Netra.init()` is no longer modified (JS-SEC-007, JS-SEC-022).
- **Span Uploads Are Bounded and Retried**: Each batch has a time limit of 10 s, retries included, set with `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` or `OTEL_EXPORTER_OTLP_TIMEOUT`. Connection errors, timeouts, 408, 429 and 502/503/504 are retried up to 5 times with jittered backoff, honouring `Retry-After`. At most 16 uploads run at once; further batches wait in a queue of up to 1,024 and are dropped only when it is full. Only the first 64 KiB of an error response is read (JS-MEM-002, JS-PERF-006).
- **Only `QUOTA_EXCEEDED` Pauses Uploads**: The 15-minute export pause now starts only when the backend reports exhausted quota (`errorCode: "QUOTA_EXCEEDED"`, or a "usage quota exceeded" message). An ordinary 429 rate limit is retried instead. Trace ids remembered during a pause now expire after 30 minutes, at most 10,000 are kept, and they are cleared on shutdown (JS-MEM-004).
- **Faster Startup**: The Traceloop SDK and its dependency tree now load on the first `Netra.init()` instead of when `netra-sdk` is imported. Loading the package took about 610 ms and now takes about 140 ms (JS-PERF-007).
- **Nothing Global Until `Netra.init()`**: Importing the SDK no longer registers a global propagator. Netra's propagator is registered when tracing starts. If the app registered its own `TracerProvider` first, Netra now prints a warning and leaves that provider alone, instead of adding its processors to it and rewriting the app's own spans (JS-SEC-011).
- **Lazy Query Builders Are Not Run Early**: A traced function that returns a thenable that is not a real Promise, such as a Knex, Prisma or Mongoose query builder, gets it back untouched; the SDK no longer calls `then()`, which ran the query early and outside the caller's transaction. Such spans end without an output (JS-SEC-010).
- **Scrubbing Covers More and Matches Keys Exactly**: With `enableScrubbing`, attributes passed when a span starts, span events (including recorded exceptions), status messages and span names are scrubbed too. Sensitive attribute names are matched by whole name parts, so keys such as `netra.span.type` or `gen_ai.request.max_tokens` are no longer replaced. The email pattern no longer backtracks on crafted input, which could block the app for seconds (JS-SEC-009, JS-SEC-021).
- **Per-Chunk Stream Events Only in Debug Mode**: OpenAI, Groq and Mistral streams record an `llm.content.completion.chunk` event per chunk only in debug mode, as Anthropic and Google GenAI already did (JS-PERF-014).
- **Bounded Simulations and Evaluations**: A simulated conversation stops after 100 turns (`NETRA_SIMULATION_MAX_TURNS`). Simulation attachments must use https, may not point to private or local addresses, follow at most 3 redirects and are limited to 50 MiB (`NETRA_SIMULATION_MAX_FILE_BYTES`). Evaluator runs share the test run's `maxConcurrency` instead of all starting at once. Session-stats iteration stops when a page reports more results without a new cursor (JS-SEC-017, JS-PERF-010, JS-PERF-011).
- **More Robust API Clients**: Netra API calls have one time limit covering the response body, read at most 10 MiB, retry GET requests on network errors, 429 and 502/503/504, and follow redirects only within the API's own origin, so `x-api-key` is never sent to another host (JS-PERF-009, JS-SEC-017).
- **Smaller Package and Dependency Upkeep**: The published package no longer includes source maps (765 kB to 255 kB packed). A CI workflow type-checks, tests and builds every change, checks that `require("netra-sdk")` works on Node 18, 20.18 and 22.11, and reports `npm audit` results; Dependabot keeps dependencies and actions current. `follow-redirects` and `zod` are updated past their advisories (JS-SEC-020, JS-SEC-026).

### Fixed

- **Memory Leak Behind Gateways and Service Meshes**: Every request that arrived with a `traceparent` header and made an LLM call left a trace id in memory that was never freed. The first span of a trace in this process now counts as its root even when its parent is remote. As a result, `netra.trace.llm.call` and `setRootInput`/`setRootOutput` now also work for such requests (JS-MEM-001).
- **No Crash or API Key Leak Without an Endpoint**: Without `NETRA_OTLP_ENDPOINT`, the underlying Traceloop SDK fetched prompts from `api.traceloop.com` in the background, sending the Netra API key there. If the host could not be reached, the app crashed with an unhandled rejection. This prompt sync is now off (JS-PERF-001).
- **CommonJS on Node 18, 20 < 20.19 and 22 < 22.12**: `require("netra-sdk")` threw `ERR_REQUIRE_ESM` because of the ESM-only `p-limit` dependency. It is replaced by an internal concurrency limiter (JS-PERF-004).
- **Concurrent Requests No Longer Share Workflow, Agent and Task Names**: Decorated functions pushed their names onto one process-wide stack, so under concurrency spans got another request's `netra.workflow.name`, `netra.agent.name` and `netra.task.name`. Each decorated call now runs in its own entity scope (JS-SEC-018).
- **Unfinished Spans No Longer Stay in Memory**: The span-name registry is kept per entity scope instead of in a module global, and at most 10,000 root spans are tracked, so spans that never end are no longer held for the life of the process (JS-MEM-005).
- **Scripts Exit When Netra Hangs**: When the flush in `Netra.shutdown()` does not finish within 5 s, uploads still in flight are aborted, so an endpoint that accepts connections but never answers no longer keeps a finished script, job or serverless handler running (JS-PERF-003).
- **Streams Read Other Ways End Their Span**: The span of an Anthropic `create({ stream: true })` call now ends when the stream comes from `.withResponse()`, and when the raw response is read through `.asResponse()`. A LangGraph `stream()` read with `getReader()`, or cancelled, ends its span too. A stream the app drops without reading or cancelling has its span ended once the stream is garbage-collected. These spans were never exported and stayed in memory (JS-MEM-003).
- **`%` in `OTEL_RESOURCE_ATTRIBUTES` No Longer Breaks `init()`**: A raw `%`, as in `team=R%D`, made `Netra.init()` throw `URIError`. The value is now kept as written (JS-PERF-008).
- **Long Chat Histories No Longer Block the App**: Each prompt or completion message used to rebuild and re-stringify the whole history; a 1,000-message prompt took about 2.7 s and over 3,700 `JSON.stringify` calls. The history is now rebuilt once, and each stored message is cut to `NETRA_SPAN_ATTRIBUTE_MAX_SIZE` (JS-PERF-002, JS-MEM-006).
- **Large Inputs Are Not Serialized in Full**: Traced function arguments and results, and LangGraph state, are serialized up to twice the attribute size limit instead of in full before truncation. Buffers and typed arrays are recorded as `[Buffer N bytes]` instead of an array with one number per byte (JS-MEM-007, JS-PERF-012).
- **Recording Never Breaks the App's Call**: LangGraph state, Groq and Mistral requests, and request `reasoning` settings that cannot be turned into JSON (circular, `BigInt`) no longer make the call fail (JS-PERF-005).
- **Re-initializing Replaces Netra's Processors**: Each `Netra.init()` after `Netra.shutdown()` added another full set of span processors. The previous set is now replaced. The `LocalFilteringSpanProcessor` registered on the provider is now the one configured with `blockedSpans` and shared with the exporter, so blocked spans' children are reparented as intended (JS-MEM-008).
- **Bounded Streamed Choices**: A streamed `choice.index` of 128 or more, or an invalid one, is ignored instead of growing the choices array up to it (JS-MEM-009).
- **Google GenAI Chat History Read Only With Content Tracing**: `Chat.getHistory()`, which may copy the whole history, is no longer called when content tracing is off (JS-PERF-013).
- **Prompt Cache**: Names and labels containing `:` no longer share a cache entry, and concurrent `getPrompt` calls for a missing entry share one request (JS-SEC-023, JS-PERF-015).
- **Safe Export Error Logs**: Error text from the trace endpoint is capped at 200 characters and its control characters are escaped, so a collector cannot inject or flood log lines (JS-SEC-024).
- **Fewer Side Effects in Other Libraries**: The filter that removes Traceloop's LangChain callback is installed only when Traceloop patched LangChain, and the Mistral instrumentation no longer passes the app's `MISTRAL_API_KEY` to the throwaway client it builds to find constructors (JS-SEC-025).
- **Evaluation Session ID**: `Evaluation.runTestSuite` reads the session id from the value set with `Netra.setSessionId()`/`Netra.withSession()`, now that session values are no longer kept in baggage.

## [1.12.2] - 2026-11-04

### Changed
Expand Down
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,10 +300,34 @@ You can configure the SDK using environment variables:
| Variable | Description |
|----------|-------------|
| `NETRA_OTLP_ENDPOINT` | Netra endpoint: `https://api.getnetra.ai/telemetry` (US) or `https://api.eu.getnetra.ai/telemetry` (EU). Required to send traces to Netra; falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`, and if neither is set, spans are printed to the console |
| `NETRA_API_KEY` | API Key for Netra Platform |
| `NETRA_API_KEY` | API Key for Netra Platform. Not sent to an endpoint that comes only from `OTEL_EXPORTER_OTLP_ENDPOINT` unless it is a Netra host (`*.getnetra.ai`) |
| `NETRA_APP_NAME` | Name of your application |
| `NETRA_ENV` | Environment (e.g., prod, dev) |
| `NETRA_TRACE_CONTENT` | Capture prompt/completion content (default: true) |
| `NETRA_TRACE_DB_PARAMETERS` | Record database query parameter values on TypeORM spans (default: false). Takes effect only while content capture is on; otherwise only the parameter count is recorded |
| `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` | Time limit in ms for sending one batch of spans, retries included (default: 10000; falls back to `OTEL_EXPORTER_OTLP_TIMEOUT`) |
| `NETRA_SIMULATION_MAX_TURNS` | Most turns one simulated conversation may take before it is marked failed (default: 100) |
| `NETRA_SIMULATION_MAX_FILE_BYTES` | Largest simulation attachment downloaded, in bytes (default: 52428800, 50 MiB). Attachments must use https and may not point to private or local addresses |

## 🔒 Security Notes

**Pin patched OpenTelemetry packages in your app.** `@traceloop/node-server-sdk` (a dependency of this SDK) still depends on `@opentelemetry/sdk-node` 0.203, which brings in OpenTelemetry packages with published advisories. npm does not apply a library's own `overrides` to your install, so add them to your application's `package.json`:

```json
{
"overrides": {
"@opentelemetry/sdk-node": "^0.222.0",
"@opentelemetry/core": "^2.11.0",
"@opentelemetry/propagator-jaeger": "^2.11.0",
"@opentelemetry/exporter-prometheus": "^0.222.0"
}
}
```

**Call `Netra.init()` before other OpenTelemetry setup.** If another `TracerProvider` is registered first, Netra prints a warning, does not add its processors to that provider, and receives no spans.

**OpenAI Agents native tracing.** By default (`netra-strict`), Netra replaces the Agents SDK's trace processors so traces are not also sent to OpenAI. Processors your app adds with `addTraceProcessor()` before `Netra.init()` are replaced too; add them after `Netra.init()`, or set `NATIVE_TRACING_MODE=netra` or `both` to keep them.


## 🤝 License

Expand Down
8 changes: 6 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
}
},
"files": [
"dist"
"dist",
"!dist/**/*.map"
],
"scripts": {
"build": "tsup",
Expand Down
9 changes: 9 additions & 0 deletions src/api/dashboard/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ async getSessionStats(
break;
}

// A page that claims more without a new cursor would request the same
// page again forever (JS-PERF-011).
if (!result.nextCursor || result.nextCursor === cursor) {
NetraLogger.warn(
"netra.dashboard: session stats reported more pages without a new cursor; stopping",
);
break;
}

cursor = result.nextCursor;
}
}
Expand Down
Loading
Loading