Medium severity5.3NVD Advisory· Published Apr 9, 2026· Updated Apr 15, 2026
CVE-2026-35633
CVE-2026-35633
Description
OpenClaw before 2026.3.22 contains an unbounded memory allocation vulnerability in remote media HTTP error handling that allows attackers to trigger excessive memory consumption. Attackers can send crafted HTTP error responses with large bodies to remote media endpoints, causing the application to allocate unbounded memory before failure handling occurs.
Affected packages
Versions sourced from the GitHub Security Advisory.
| Package | Affected versions | Patched versions |
|---|---|---|
openclawnpm | < 2026.3.22 | 2026.3.22 |
Affected products
1Patches
2630f1479c44fbuild: prepare 2026.3.23-2
3 files changed · +26 −24
CHANGELOG.md+24 −22 modified@@ -8,45 +8,47 @@ Docs: https://docs.openclaw.ai ### Changes -- ModelStudio/Qwen: add standard (pay-as-you-go) DashScope endpoints for China and global Qwen API keys alongside the existing Coding Plan endpoints, and relabel the provider group to `Qwen (Alibaba Cloud Model Studio)`. (#43878) -- UI/clarity: consolidate button primitives (`btn--icon`, `btn--ghost`, `btn--xs`), refine the Knot theme to a black-and-red palette with WCAG 2.1 AA contrast, add config icons for Diagnostics/CLI/Secrets/ACP/MCP sections, replace the roundness slider with discrete stops, and improve accessibility with aria-labels across usage filters. (#53272) Thanks @BunsDev. -- CSP/Control UI: compute SHA-256 hashes for inline `<script>` blocks in the served `index.html` and include them in the `script-src` CSP directive, keeping inline scripts blocked by default while allowing explicitly hashed bootstrap code. (#53307) Thanks @BunsDev. - ### Fixes -- Plugins/ClawHub: resolve plugin API compatibility against the active runtime version at install time, and add regression coverage for current `>=2026.3.22` ClawHub package checks so installs no longer fail behind the stale `1.2.0` constant. (#53157) Thanks @futhgar. -- CLI/channel auth: auto-select the single login-capable configured channel for `channels login`/`logout` instead of relying on the outbound message-channel resolver, so env-only or non-auth channels no longer cause false ambiguity errors. (#53254) Thanks @BunsDev. -- Control UI/auth: preserve operator scopes through the device-auth bypass path, ignore cached under-scoped operator tokens, and show a clear `operator.read` fallback message when a connection really lacks read scope, so operator sessions stop failing or blanking on read-backed pages. (#53110) Thanks @BunsDev. -- Plugins/uninstall: accept installed `clawhub:` specs and versionless ClawHub package names as uninstall targets, so `openclaw plugins uninstall clawhub:<package>` works again even when the recorded install was pinned to a version. -- Auth/OpenAI tokens: stop live gateway auth-profile writes from reverting freshly saved credentials back to stale in-memory values, and make `models auth paste-token` write to the resolved agent store, so Configure, Onboard, and token-paste flows stop snapping back to expired OpenAI tokens. Fixes #53207. Related to #45516. -- Agents/failover: classify generic `api_error` payloads as retryable only when they include transient failure signals, so MiniMax-style backend failures still trigger model fallback without misclassifying billing, auth, or format/context errors. (#49611) Thanks @ayushozha. -- Diagnostics/cache trace: strip credential fields from cache-trace JSONL output while preserving non-sensitive diagnostic fields and image redaction metadata. -- Docs/Feishu: replace `botName` with `name` in the channel config examples so the docs match the strict account schema for per-account display names. (#52753) Thanks @haroldfabla2-hue. -- Doctor/plugins: make `openclaw doctor --fix` remove stale `plugins.allow` and `plugins.entries` refs left behind after plugin removal. Thanks @sallyom -- Agents/replay: canonicalize malformed assistant transcript content before session-history sanitization so legacy or corrupted assistant turns stop crashing Pi replay and subagent recovery paths. -- ClawHub/skills: keep updating already-tracked legacy Unicode slugs after the ASCII-only slug hardening, so older installs do not get stuck behind `Invalid skill slug` errors during `openclaw skills update`. (#53206) Thanks @drobison00. -- Infra/exec trust: preserve shell-multiplexer wrapper binaries for policy checks without breaking approved-command reconstruction, so BusyBox/ToyBox allowlist and audit flows bind to the real wrapper while execution plans stay coherent. (#53134) Thanks @vincentkoc. -- LINE/runtime-api: pre-export overlapping runtime symbols before the `line-runtime` star export so jiti no longer throws `TypeError: Cannot redefine property` on startup. (#53221) Thanks @Drickon. -- CLI/cron: make `openclaw cron add|edit --at ... --tz <iana>` honor the requested local wall-clock time for offset-less one-shot datetimes, including DST boundaries, and keep `--tz` rejected for `--every`. (#53224) Thanks @RolfHegr. -- Commands/auth: stop slash-command authorization from crashing or dropping valid allowlists when channel `allowFrom` resolution hits unresolved SecretRef-backed accounts, and fail closed only for the affected provider inference path. (#52791) Thanks @Lukavyi. - ## 2026.3.23 ### Breaking ### Changes +- ModelStudio/Qwen: add standard (pay-as-you-go) DashScope endpoints for China and global Qwen API keys alongside the existing Coding Plan endpoints, and relabel the provider group to `Qwen (Alibaba Cloud Model Studio)`. (#43878) +- UI/clarity: consolidate button primitives (`btn--icon`, `btn--ghost`, `btn--xs`), refine the Knot theme to a black-and-red palette with WCAG 2.1 AA contrast, add config icons for Diagnostics/CLI/Secrets/ACP/MCP sections, replace the roundness slider with discrete stops, and improve accessibility with aria-labels across usage filters. (#53272) Thanks @BunsDev. +- CSP/Control UI: compute SHA-256 hashes for inline `<script>` blocks in the served `index.html` and include them in the `script-src` CSP directive, keeping inline scripts blocked by default while allowing explicitly hashed bootstrap code. (#53307) Thanks @BunsDev. + ### Fixes +- Plugins/bundled runtimes: ship bundled plugin runtime sidecars like WhatsApp `light-runtime-api.js`, Matrix `runtime-api.js`, and other plugin runtime entry files in the npm package again, so global installs stop failing on missing bundled plugin runtime surfaces. +- CLI/channel auth: auto-select the single configured login-capable channel for `channels login`/`logout`, harden channel ids against prototype-chain and control-character abuse, and fall back cleanly to catalog-backed channel installs, so channel auth works again for single-channel setups and on-demand channel installs. (#53254) Thanks @BunsDev. +- Auth/OpenAI tokens: stop live gateway auth-profile writes from reverting freshly saved credentials back to stale in-memory values, and make `models auth paste-token` write to the resolved agent store, so Configure, Onboard, and token-paste flows stop snapping back to expired OpenAI tokens. Fixes #53207. Related to #45516. +- Control UI/auth: preserve operator scopes through the device-auth bypass path, ignore cached under-scoped operator tokens, and show a clear `operator.read` fallback message when a connection really lacks read scope, so operator sessions stop failing or blanking on read-backed pages. (#53110) Thanks @BunsDev. +- Plugins/ClawHub: resolve plugin API compatibility against the active runtime version at install time, and add regression coverage for current `>=2026.3.22` ClawHub package checks so installs no longer fail behind the stale `1.2.0` constant. (#53157) Thanks @futhgar. +- Plugins/uninstall: accept installed `clawhub:` specs and versionless ClawHub package names as uninstall targets, so `openclaw plugins uninstall clawhub:<package>` works again even when the recorded install was pinned to a version. - Browser/Chrome MCP: wait for existing-session browser tabs to become usable after attach instead of treating the initial Chrome MCP handshake as ready, which reduces user-profile timeouts and repeated consent churn on macOS Chrome attach flows. Fixes #52930. Thanks @vincentkoc. - Browser/CDP: reuse an already-running loopback browser after a short initial reachability miss instead of immediately falling back to relaunch detection, which fixes second-run browser start/open regressions on slower headless Linux setups. Fixes #53004. Thanks @vincentkoc. +- Agents/web_search: use the active runtime `web_search` provider instead of stale/default selection, so agent turns keep hitting the provider you actually configured. Fixes #53020. Thanks @jzakirov. +- Mistral/models: lower bundled Mistral max-token defaults to safe output budgets and teach `openclaw doctor --fix` to repair old persisted Mistral provider configs that still carry context-sized output limits, avoiding deterministic Mistral 422 rejects on fresh and existing setups. Fixes #52599. Thanks @vincentkoc. - ClawHub/macOS auth: honor macOS auth config and XDG auth paths for saved ClawHub credentials, so `openclaw skills ...` and gateway skill browsing keep using the signed-in auth state instead of silently falling back to unauthenticated mode. Fixes #53034. - ClawHub/macOS: read the local ClawHub login from the macOS Application Support path and still honor XDG config on macOS, so skill browsing uses the logged-in token on both default and XDG-style setups. Fixes #52949. Thanks @scoootscooob. - ClawHub/skills: resolve the local ClawHub auth token for gateway skill browsing and switch browse-all requests to search so ClawControl stops falling into unauthenticated 429s and empty authenticated skill lists. Fixes #52949. Thanks @vincentkoc. +- Config/warnings: suppress the confusing “newer OpenClaw” warning when a config written by a same-base correction release like `2026.3.23-2` is read by `2026.3.23`, while still warning for truly newer or incompatible versions. +- CLI/cron: make `openclaw cron add|edit --at ... --tz <iana>` honor the requested local wall-clock time for offset-less one-shot datetimes, including DST boundaries, and keep `--tz` rejected for `--every`. (#53224) Thanks @RolfHegr. +- Commands/auth: stop slash-command authorization from crashing or dropping valid allowlists when channel `allowFrom` resolution hits unresolved SecretRef-backed accounts, and fail closed only for the affected provider inference path. (#52791) Thanks @Lukavyi. +- Agents/failover: classify generic `api_error` payloads as retryable only when they include transient failure signals, so MiniMax-style backend failures still trigger model fallback without misclassifying billing, auth, or format/context errors. (#49611) Thanks @ayushozha. +- LINE/runtime-api: pre-export overlapping runtime symbols before the `line-runtime` star export so jiti no longer throws `TypeError: Cannot redefine property` on startup. (#53221) Thanks @Drickon. +- Telegram/threading: populate `currentThreadTs` in the threading tool-context fallback for Telegram DM topics so thread-aware tools still receive the active topic context when the main thread metadata is missing. (#52217) +- Diagnostics/cache trace: strip credential fields from cache-trace JSONL output while preserving non-sensitive diagnostic fields and image redaction metadata. +- Docs/Feishu: replace `botName` with `name` in the channel config examples so the docs match the strict account schema for per-account display names. (#52753) Thanks @haroldfabla2-hue. +- Doctor/plugins: make `openclaw doctor --fix` remove stale `plugins.allow` and `plugins.entries` refs left behind after plugin removal. Thanks @sallyom +- Agents/replay: canonicalize malformed assistant transcript content before session-history sanitization so legacy or corrupted assistant turns stop crashing Pi replay and subagent recovery paths. +- ClawHub/skills: keep updating already-tracked legacy Unicode slugs after the ASCII-only slug hardening, so older installs do not get stuck behind `Invalid skill slug` errors during `openclaw skills update`. (#53206) Thanks @drobison00. +- Infra/exec trust: preserve shell-multiplexer wrapper binaries for policy checks without breaking approved-command reconstruction, so BusyBox/ToyBox allowlist and audit flows bind to the real wrapper while execution plans stay coherent. (#53134) Thanks @vincentkoc. - Plugins/message tool: make Discord `components` and Slack `blocks` optional again, and route Feishu `message(..., media=...)` sends through the outbound media path, so pin/unpin/react flows stop failing schema validation and Feishu file/image attachments actually send. Fixes #52970 and #52962. Thanks @vincentkoc. - Gateway/model pricing: stop `openrouter/auto` pricing refresh from recursing indefinitely during bootstrap, so OpenRouter auto routes can populate cached pricing and `usage.cost` again. Fixes #53035. Thanks @vincentkoc. -- Mistral/models: lower bundled Mistral max-token defaults to safe output budgets and teach `openclaw doctor --fix` to repair old persisted Mistral provider configs that still carry context-sized output limits, avoiding deterministic Mistral 422 rejects on fresh and existing setups. Fixes #52599. Thanks @vincentkoc. -- Agents/web_search: use the active runtime `web_search` provider instead of stale/default selection, so agent turns keep hitting the provider you actually configured. Fixes #53020. Thanks @jzakirov. - Models/OpenAI Codex OAuth: bootstrap the env-configured HTTP/HTTPS proxy dispatcher on the stored-credential refresh path before token renewal runs, so expired Codex OAuth profiles can refresh successfully in proxy-required environments instead of locking users out after the first token expiry. - Models/OpenAI Codex OAuth and Plugins/MiniMax OAuth: ensure env-configured HTTP/HTTPS proxy dispatchers are initialized before OAuth preflight and token exchange requests so proxy-required environments can complete MiniMax and OpenAI Codex sign-in flows again. (#52228; fixes #51619, #51569) Thanks @openperf. - Plugins/memory-lancedb: bootstrap LanceDB into plugin runtime state on first use when the bundled npm install does not already have it, so `plugins.slots.memory="memory-lancedb"` works again after global npm installs without moving LanceDB into OpenClaw core dependencies. Fixes #26100.
docs/.generated/plugin-sdk-api-baseline.json+1 −1 modified@@ -2620,7 +2620,7 @@ "exportName": "resolveCommandAuthorization", "kind": "function", "source": { - "line": 303, + "line": 440, "path": "src/auto-reply/command-auth.ts" } },
docs/.generated/plugin-sdk-api-baseline.jsonl+1 −1 modified@@ -287,7 +287,7 @@ {"declaration":"export function parseCommandArgs(command: ChatCommandDefinition, raw?: string | undefined): CommandArgs | undefined;","entrypoint":"command-auth","exportName":"parseCommandArgs","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":254,"sourcePath":"src/auto-reply/commands-registry.ts"} {"declaration":"export function resolveCommandArgChoices(params: { command: ChatCommandDefinition; arg: CommandArgDefinition; cfg?: OpenClawConfig | undefined; provider?: string | undefined; model?: string | undefined; }): ResolvedCommandArgChoice[];","entrypoint":"command-auth","exportName":"resolveCommandArgChoices","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":316,"sourcePath":"src/auto-reply/commands-registry.ts"} {"declaration":"export function resolveCommandArgMenu(params: { command: ChatCommandDefinition; args?: CommandArgs | undefined; cfg?: OpenClawConfig | undefined; }): { arg: CommandArgDefinition; choices: ResolvedCommandArgChoice[]; title?: string | undefined; } | null;","entrypoint":"command-auth","exportName":"resolveCommandArgMenu","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":346,"sourcePath":"src/auto-reply/commands-registry.ts"} -{"declaration":"export function resolveCommandAuthorization(params: { ctx: MsgContext; cfg: OpenClawConfig; commandAuthorized: boolean; }): CommandAuthorization;","entrypoint":"command-auth","exportName":"resolveCommandAuthorization","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":303,"sourcePath":"src/auto-reply/command-auth.ts"} +{"declaration":"export function resolveCommandAuthorization(params: { ctx: MsgContext; cfg: OpenClawConfig; commandAuthorized: boolean; }): CommandAuthorization;","entrypoint":"command-auth","exportName":"resolveCommandAuthorization","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":440,"sourcePath":"src/auto-reply/command-auth.ts"} {"declaration":"export function resolveCommandAuthorizedFromAuthorizers(params: { useAccessGroups: boolean; authorizers: CommandAuthorizer[]; modeWhenAccessGroupsOff?: CommandGatingModeWhenAccessGroupsOff | undefined; }): boolean;","entrypoint":"command-auth","exportName":"resolveCommandAuthorizedFromAuthorizers","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":8,"sourcePath":"src/channels/command-gating.ts"} {"declaration":"export function resolveControlCommandGate(params: { useAccessGroups: boolean; authorizers: CommandAuthorizer[]; allowTextCommands: boolean; hasControlCommand: boolean; modeWhenAccessGroupsOff?: CommandGatingModeWhenAccessGroupsOff | undefined; }): { ...; };","entrypoint":"command-auth","exportName":"resolveControlCommandGate","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":31,"sourcePath":"src/channels/command-gating.ts"} {"declaration":"export function resolveDirectDmAuthorizationOutcome(params: { isGroup: boolean; dmPolicy: string; senderAllowedForCommands: boolean; }): \"disabled\" | \"unauthorized\" | \"allowed\";","entrypoint":"command-auth","exportName":"resolveDirectDmAuthorizationOutcome","importSpecifier":"openclaw/plugin-sdk/command-auth","kind":"function","recordType":"export","sourceLine":120,"sourcePath":"src/plugin-sdk/command-auth.ts"}
81445a901091fix(media): bound remote error-body snippet reads
5 files changed · +167 −38
CHANGELOG.md+1 −0 modified@@ -118,6 +118,7 @@ Docs: https://docs.openclaw.ai - CLI: avoid loading provider discovery during startup model normalization. (#46522) Thanks @ItsAditya-xyz and @vincentkoc. - CLI/status: keep `status --json` stdout clean by skipping plugin compatibility scans that were not rendered in the JSON payload. (#52449) Thanks @cgdusek. - Agents/Telegram: avoid rebuilding the full model catalog on ordinary inbound replies so Telegram message handling no longer pays multi-second core startup latency before reply generation. Thanks @vincentkoc. +- Media/security: bound remote-media error-body snippets with the same streaming caps and idle timeouts as successful downloads, so malicious HTTP error responses cannot force unbounded buffering before OpenClaw throws. - Gateway/Discord startup: load only configured channel plugins during gateway boot, and lazy-load Discord provider/session runtime setup so startup stops importing unrelated providers and trims cold-start delay. Thanks @vincentkoc. - Security/exec: harden macOS allowlist resolution against wrapper and `env` spoofing, require fresh approval for inline interpreter eval with `tools.exec.strictInlineEval`, wrap Discord guild message bodies as untrusted external content, and add audit findings for risky exec approval and open-channel combinations. - Agents/inbound: lazy-load media and link understanding for plain-text turns and cache synced auth stores by auth-file state so ordinary inbound replies avoid unnecessary startup churn. Thanks @vincentkoc.
src/media/fetch.test.ts+24 −0 modified@@ -186,6 +186,30 @@ describe("fetchRemoteMedia", () => { }); }); + it("bounds error-body snippets instead of reading the full response", async () => { + const hiddenTail = `${" ".repeat(9_000)}BAD`; + const fetchImpl = vi.fn( + async () => + new Response(makeStream([new TextEncoder().encode(hiddenTail)]), { + status: 400, + statusText: "Bad Request", + }), + ); + + const result = await fetchRemoteMedia({ + url: "https://example.com/file.bin", + fetchImpl, + maxBytes: 1024, + }).catch((err: unknown) => err); + + expect(result).toBeInstanceOf(Error); + if (!(result instanceof Error)) { + expect.unreachable("expected fetchRemoteMedia to reject"); + } + expect(result.message).not.toContain("BAD"); + expect(result.message).not.toContain("body:"); + }); + it("blocks private IP literals before fetching", async () => { const fetchImpl = vi.fn(); await expect(
src/media/fetch.ts+14 −15 modified@@ -4,7 +4,7 @@ import { fetchWithSsrFGuard, withStrictGuardedFetchMode } from "../infra/net/fet import type { LookupFn, PinnedDispatcherPolicy, SsrFPolicy } from "../infra/net/ssrf.js"; import { redactSensitiveText } from "../logging/redact.js"; import { detectMime, extensionForMime } from "./mime.js"; -import { readResponseWithLimit } from "./read-response-with-limit.js"; +import { readResponseTextSnippet, readResponseWithLimit } from "./read-response-with-limit.js"; type FetchMediaResult = { buffer: Buffer; @@ -71,20 +71,19 @@ function parseContentDispositionFileName(header?: string | null): string | undef return undefined; } -async function readErrorBodySnippet(res: Response, maxChars = 200): Promise<string | undefined> { +async function readErrorBodySnippet( + res: Response, + opts?: { + maxChars?: number; + chunkTimeoutMs?: number; + }, +): Promise<string | undefined> { try { - const text = await res.text(); - if (!text) { - return undefined; - } - const collapsed = text.replace(/\s+/g, " ").trim(); - if (!collapsed) { - return undefined; - } - if (collapsed.length <= maxChars) { - return collapsed; - } - return `${collapsed.slice(0, maxChars)}…`; + return await readResponseTextSnippet(res, { + maxBytes: 8 * 1024, + maxChars: opts?.maxChars, + chunkTimeoutMs: opts?.chunkTimeoutMs, + }); } catch { return undefined; } @@ -185,7 +184,7 @@ export async function fetchRemoteMedia(options: FetchMediaOptions): Promise<Fetc if (!res.body) { detail = `HTTP ${res.status}${statusText}; empty response body`; } else { - const snippet = await readErrorBodySnippet(res); + const snippet = await readErrorBodySnippet(res, { chunkTimeoutMs: readIdleTimeoutMs }); if (snippet) { detail += `; body: ${snippet}`; }
src/media/read-response-with-limit.test.ts+36 −1 modified@@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { readResponseWithLimit } from "./read-response-with-limit.js"; +import { readResponseTextSnippet, readResponseWithLimit } from "./read-response-with-limit.js"; function makeStream(chunks: Uint8Array[], delayMs?: number) { return new ReadableStream<Uint8Array>({ @@ -81,3 +81,38 @@ describe("readResponseWithLimit", () => { } }); }); + +describe("readResponseTextSnippet", () => { + beforeEach(() => { + vi.useRealTimers(); + }); + + it("returns collapsed text within the limit", async () => { + const res = new Response(makeStream([new TextEncoder().encode("hello \n world")])); + await expect(readResponseTextSnippet(res, { maxBytes: 64, maxChars: 50 })).resolves.toBe( + "hello world", + ); + }); + + it("truncates to the byte limit without reading the full body", async () => { + const res = new Response( + makeStream([new TextEncoder().encode("12345"), new TextEncoder().encode("67890")]), + ); + await expect(readResponseTextSnippet(res, { maxBytes: 7, maxChars: 50 })).resolves.toBe( + "1234567…", + ); + }); + + it("applies the idle timeout while reading snippets", async () => { + vi.useFakeTimers(); + try { + const res = new Response(makeStallingStream([new Uint8Array([65, 66])])); + const readPromise = readResponseTextSnippet(res, { maxBytes: 64, chunkTimeoutMs: 50 }); + const rejection = expect(readPromise).rejects.toThrow(/stalled/i); + await vi.advanceTimersByTimeAsync(60); + await rejection; + } finally { + vi.useRealTimers(); + } + }, 5_000); +});
src/media/read-response-with-limit.ts+92 −22 modified@@ -37,59 +37,129 @@ async function readChunkWithIdleTimeout( }); } -export async function readResponseWithLimit( +type ReadResponsePrefixResult = { + buffer: Buffer; + size: number; + truncated: boolean; +}; + +async function readResponsePrefix( res: Response, maxBytes: number, opts?: { - onOverflow?: (params: { size: number; maxBytes: number; res: Response }) => Error; chunkTimeoutMs?: number; }, -): Promise<Buffer> { - const onOverflow = - opts?.onOverflow ?? - ((params: { size: number; maxBytes: number }) => - new Error(`Content too large: ${params.size} bytes (limit: ${params.maxBytes} bytes)`)); +): Promise<ReadResponsePrefixResult> { const chunkTimeoutMs = opts?.chunkTimeoutMs; - const body = res.body; if (!body || typeof body.getReader !== "function") { const fallback = Buffer.from(await res.arrayBuffer()); if (fallback.length > maxBytes) { - throw onOverflow({ size: fallback.length, maxBytes, res }); + return { + buffer: fallback.subarray(0, maxBytes), + size: fallback.length, + truncated: true, + }; } - return fallback; + return { buffer: fallback, size: fallback.length, truncated: false }; } const reader = body.getReader(); const chunks: Uint8Array[] = []; let total = 0; + let size = 0; + let truncated = false; try { while (true) { const { done, value } = chunkTimeoutMs ? await readChunkWithIdleTimeout(reader, chunkTimeoutMs) : await reader.read(); if (done) { + size = total; break; } - if (value?.length) { - total += value.length; - if (total > maxBytes) { - try { - await reader.cancel(); - } catch {} - throw onOverflow({ size: total, maxBytes, res }); + if (!value?.length) { + continue; + } + const nextTotal = total + value.length; + if (nextTotal > maxBytes) { + const remaining = maxBytes - total; + if (remaining > 0) { + chunks.push(value.subarray(0, remaining)); + total += remaining; } - chunks.push(value); + size = nextTotal; + truncated = true; + try { + await reader.cancel(); + } catch {} + break; } + chunks.push(value); + total = nextTotal; + size = total; } } finally { try { reader.releaseLock(); } catch {} } - return Buffer.concat( - chunks.map((chunk) => Buffer.from(chunk)), - total, - ); + return { + buffer: Buffer.concat( + chunks.map((chunk) => Buffer.from(chunk)), + total, + ), + size, + truncated, + }; +} + +export async function readResponseWithLimit( + res: Response, + maxBytes: number, + opts?: { + onOverflow?: (params: { size: number; maxBytes: number; res: Response }) => Error; + chunkTimeoutMs?: number; + }, +): Promise<Buffer> { + const onOverflow = + opts?.onOverflow ?? + ((params: { size: number; maxBytes: number }) => + new Error(`Content too large: ${params.size} bytes (limit: ${params.maxBytes} bytes)`)); + const prefix = await readResponsePrefix(res, maxBytes, { chunkTimeoutMs: opts?.chunkTimeoutMs }); + if (prefix.truncated) { + throw onOverflow({ size: prefix.size, maxBytes, res }); + } + return prefix.buffer; +} + +export async function readResponseTextSnippet( + res: Response, + opts?: { + maxBytes?: number; + maxChars?: number; + chunkTimeoutMs?: number; + }, +): Promise<string | undefined> { + const maxBytes = opts?.maxBytes ?? 8 * 1024; + const maxChars = opts?.maxChars ?? 200; + const prefix = await readResponsePrefix(res, maxBytes, { chunkTimeoutMs: opts?.chunkTimeoutMs }); + if (prefix.buffer.length === 0) { + return undefined; + } + + const text = new TextDecoder().decode(prefix.buffer); + if (!text) { + return undefined; + } + + const collapsed = text.replace(/\s+/g, " ").trim(); + if (!collapsed) { + return undefined; + } + if (collapsed.length > maxChars) { + return `${collapsed.slice(0, maxChars)}…`; + } + return prefix.truncated ? `${collapsed}…` : collapsed; }
Vulnerability mechanics
Generated by null/stub on May 9, 2026. Inputs: CWE entries + fix-commit diffs from this CVE's patches. Citations validated against bundle.
References
6- github.com/openclaw/openclaw/commit/630f1479c44f78484dfa21bb407cbe6f171dac87nvdPatchWEB
- github.com/openclaw/openclaw/commit/81445a901091a5d27ef0b56fceedbe4724566438nvdPatchWEB
- github.com/advisories/GHSA-4qwc-c7g9-4xcwghsaADVISORY
- github.com/openclaw/openclaw/security/advisories/GHSA-4qwc-c7g9-4xcwnvdVendor AdvisoryWEB
- nvd.nist.gov/vuln/detail/CVE-2026-35633ghsaADVISORY
- www.vulncheck.com/advisories/openclaw-unbounded-memory-allocation-via-remote-media-error-responsesnvdThird Party AdvisoryWEB
News mentions
0No linked articles in our index yet.