The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
tech(W-T3): Dev-Server typisieren, testen — und sieben Loecher schliessen
David25408c8a0982
diff --git a/src/dev/__tests__/console-strip.test.ts b/src/dev/__tests__/console-strip.test.tsnew file mode 100644index 00000000..75967060--- /dev/null+++ b/src/dev/__tests__/console-strip.test.ts@@ -0,0 +1,240 @@+/**+ * §1.6 — `console.log/info/debug` aus dem Produktions-Build entfernen.+ *+ * Dieses Plugin schreibt Produktionscode um und war ungetestet. Die Tests+ * gehen den ganzen Weg: echter Quelltext → vites `parseAst` (derselbe+ * oxc-Parser wie im Build) → Bereiche sammeln → anwenden → das Ergebnis muss+ * WIEDER PARSEBAR sein. Ein Umschreiber, der syntaktisch kaputten Code+ * ausspuckt, fällt sonst erst im Build auf.+ *+ * BEFUND beim Herauslösen: der Sonderfall für `switch`-Zweige prüfte+ * `parentKey === 'consequent'`. An der Stelle, an der er geprüft wurde, steht+ * der Schlüssel aber immer auf `'expression'` — es ist der Schlüssel des+ * Aufrufs in SEINEM Elternknoten (dem ExpressionStatement), nicht der des+ * Statements in der `switch`-Liste. Der Zweig konnte nie auslösen, und+ * `case 1: console.log(x)` wurde zu `case 1: void 0` statt gelöscht zu werden.+ * Das Ergebnis war gültig, die Absicht nicht erfüllt.+ *+ * NEGATIVE CONTROL (von Hand geprüft):+ * • 'SwitchCase' aus STATEMENT_LIST_PARENTS entfernen (= der alte Zustand)+ * → "eine Anweisung in einem switch-Zweig fällt weg" wird rot.+ * • in `collectConsoleRemovals` das `return` nach dem Treffer streichen+ * → "verschachtelte Aufrufe überlappen nicht" wird rot.+ * • in `applyConsoleRemovals` von vorn nach hinten sortieren+ * → "mehrere Aufrufe in einer Datei" wird rot.+ * • in `isStrippableModule` die logger-Zeile entfernen+ * → "der strukturierte Logger bleibt unangetastet" wird rot.+ *+ * Run: npx vitest run src/dev/__tests__/console-strip.test.ts+ */+import { describe, expect, it } from 'vitest'+import { parseAst } from 'vite'+import {+ applyConsoleRemovals,+ collectConsoleRemovals,+ isStrippableConsoleCall,+ isStrippableModule,+} from '../console-strip'++/** Den kompletten Plugin-Durchlauf auf einem Stück Quelltext. */+function strip(code: string): string {+ const removals = collectConsoleRemovals(parseAst(code, { sourceType: 'module' }))+ return applyConsoleRemovals(code, removals)+}++/** Bleibt das Ergebnis parsebar? Das ist die eigentliche Zusicherung. */+function stillParses(code: string): boolean {+ try {+ parseAst(code, { sourceType: 'module' })+ return true+ } catch {+ return false+ }+}++describe('isStrippableModule', () => {+ it('nimmt normale Quelldateien', () => {+ expect(isStrippableModule('/p/src/app.tsx', 'console.log(1)')).toBe(true)+ expect(isStrippableModule('/p/src/a.mjs?v=1', 'console.log(1)')).toBe(true)+ })++ it('lässt virtuelle Module und node_modules aus', () => {+ expect(isStrippableModule('\0virtual:x', 'console.log(1)')).toBe(false)+ expect(isStrippableModule('/p/node_modules/lib/x.js', 'console.log(1)')).toBe(false)+ })++ it('der strukturierte Logger bleibt unangetastet', () => {+ // In Produktion serialisiert src/lib/logger.ts jedes Ereignis über+ // console.log. Neutralisiert das Plugin diesen Aufruf, ist JEDES+ // log.info/log.debug stumm.+ expect(isStrippableModule('/p/src/lib/logger.ts', 'console.log(line)')).toBe(false)+ expect(isStrippableModule('C:\\p\\src\\lib\\logger.ts', 'console.log(line)')).toBe(false)+ // Eine andere Datei namens logger in einem anderen Ordner ist nicht gemeint.+ expect(isStrippableModule('/p/src/api/logger.ts', 'console.log(1)')).toBe(true)+ })++ it('spart sich die Arbeit, wenn kein console darin vorkommt', () => {+ expect(isStrippableModule('/p/src/app.ts', 'const a = 1')).toBe(false)+ })++ it('lässt Nicht-Quelldateien aus', () => {+ expect(isStrippableModule('/p/src/style.css', 'console.log(1)')).toBe(false)+ })+})++describe('isStrippableConsoleCall', () => {+ const callOf = (code: string): unknown => {+ const ast = parseAst(code, { sourceType: 'module' }) as { body: { expression: unknown }[] }+ return ast.body[0].expression+ }++ it('trifft die drei lauten Methoden', () => {+ for (const m of ['log', 'info', 'debug']) {+ expect(isStrippableConsoleCall(callOf(`console.${m}(1)`)), m).toBe(true)+ }+ })++ it('lässt warn und error stehen', () => {+ for (const m of ['warn', 'error', 'trace', 'table']) {+ expect(isStrippableConsoleCall(callOf(`console.${m}(1)`)), m).toBe(false)+ }+ })++ it('trifft nur das blanke console', () => {+ expect(isStrippableConsoleCall(callOf('myLogger.log(1)'))).toBe(false)+ expect(isStrippableConsoleCall(callOf('foo.console.log(1)'))).toBe(false)+ expect(isStrippableConsoleCall(callOf("console['log'](1)"))).toBe(false)+ })++ it('sagt zu allem anderen nein, ohne zu werfen', () => {+ for (const value of [null, undefined, 42, 'x', {}, { type: 'CallExpression' }]) {+ expect(isStrippableConsoleCall(value)).toBe(false)+ }+ })+})++describe('der Umschreiber', () => {+ it('löscht eine Anweisung in einem Block', () => {+ const out = strip('function f() {\n console.log("x")\n return 1\n}\n')+ expect(out).not.toContain('console.log')+ expect(out).toContain('return 1')+ expect(out).not.toContain('void 0')+ expect(stillParses(out)).toBe(true)+ })++ it('löscht eine Anweisung auf oberster Ebene', () => {+ const out = strip('const a = 1\nconsole.log(a)\nexport default a\n')+ expect(out).not.toContain('console.log')+ expect(stillParses(out)).toBe(true)+ })++ it('eine Anweisung in einem switch-Zweig fällt weg', () => {+ // Der tote Zweig von vorher: hier stand `case 1: void 0`.+ const out = strip('switch (x) {\n case 1:\n console.log(1)\n break\n}\n')+ expect(out).not.toContain('console.log')+ expect(out).not.toContain('void 0')+ expect(out).toContain('break')+ expect(stillParses(out)).toBe(true)+ })++ it('ein einziger Aufruf als ganzer switch-Zweig bleibt gültig', () => {+ const out = strip('switch (x) {\n case 1:\n console.log(1)\n}\n')+ expect(out).not.toContain('console.log')+ expect(stillParses(out)).toBe(true)+ })++ it('behält einen klammerlosen else-Zweig als Anweisung', () => {+ // Genau der logger.ts-Fall, an dem die naive Fassung Code zerbrach.+ const out = strip('if (a) console.error(x)\nelse console.log(y)\n')+ expect(out).toContain('console.error(x)')+ expect(out).not.toContain('console.log')+ expect(out).toContain('void 0')+ expect(stillParses(out)).toBe(true)+ })++ it('behält klammerlose Schleifen- und Label-Rümpfe', () => {+ for (const code of [+ 'for (const x of xs) console.log(x)\n',+ 'while (a) console.log(1)\n',+ 'do console.log(1)\nwhile (a)\n',+ 'if (a) console.log(1)\n',+ 'lab: console.log(1)\n',+ ]) {+ const out = strip(code)+ expect(out, code).not.toContain('console.log')+ expect(stillParses(out), `${code} → ${out}`).toBe(true)+ }+ })++ it('neutralisiert einen Aufruf als Teilausdruck', () => {+ for (const code of [+ 'const a = b && console.log(1)\n',+ 'const a = c ? console.log(1) : 2\n',+ 'f(console.log(1))\n',+ 'const a = [console.log(1)]\n',+ 'const a = () => console.log(1)\n',+ ]) {+ const out = strip(code)+ expect(out, code).not.toContain('console.log')+ expect(out, code).toContain('void 0')+ expect(stillParses(out), `${code} → ${out}`).toBe(true)+ }+ })++ it('verschachtelte Aufrufe überlappen nicht', () => {+ // Der äussere Aufruf verschwindet ganz; der innere darf nicht ZUSÄTZLICH+ // geschnitten werden, sonst überlappen die Bereiche und der Text zerfällt.+ const out = strip('function f() {\n console.log(console.log(1))\n}\n')+ expect(out).not.toContain('console.log')+ expect(stillParses(out)).toBe(true)+ })++ it('mehrere Aufrufe in einer Datei', () => {+ const code = [+ 'function f() {',+ ' console.log("a")',+ ' console.warn("b")',+ ' console.debug("c")',+ ' return 1',+ '}',+ 'console.info("d")',+ 'export default f',+ '',+ ].join('\n')+ const out = strip(code)+ expect(out).toContain('console.warn("b")')+ expect(out).not.toContain('console.log')+ expect(out).not.toContain('console.debug')+ expect(out).not.toContain('console.info')+ expect(out).toContain('return 1')+ expect(out).toContain('export default f')+ expect(stillParses(out)).toBe(true)+ })++ it('fasst eine Datei ohne Treffer nicht an', () => {+ const code = 'console.warn("nur warn")\nconsole.error("und error")\n'+ expect(collectConsoleRemovals(parseAst(code, { sourceType: 'module' }))).toEqual([])+ })++ it('lässt eine zugewiesene Referenz auf console.log stehen', () => {+ const code = 'const l = console.log\nl(1)\n'+ expect(strip(code)).toBe(code)+ })+})++describe('applyConsoleRemovals', () => {+ it('wendet von hinten nach vorn an, damit frühere Offsets gültig bleiben', () => {+ const code = 'AAAABBBBCCCC'+ const out = applyConsoleRemovals(code, [+ { start: 0, end: 4, replacement: 'x' },+ { start: 8, end: 12, replacement: 'y' },+ ])+ expect(out).toBe('xBBBBy')+ })++ it('ändert die übergebene Liste nicht', () => {+ const removals = [{ start: 4, end: 8, replacement: '' }, { start: 0, end: 4, replacement: '' }]+ applyConsoleRemovals('AAAABBBB', removals)+ expect(removals[0].start).toBe(4)+ })+})diff --git a/src/dev/__tests__/dev-server-shape.test.ts b/src/dev/__tests__/dev-server-shape.test.tsnew file mode 100644index 00000000..c50352f1--- /dev/null+++ b/src/dev/__tests__/dev-server-shape.test.ts@@ -0,0 +1,105 @@+/**+ * Zusicherungen ÜBER `vite.config.ts` selbst — die Klammer zwischen den+ * herausgelösten Modulen und der Datei, die sie benutzen soll.+ *+ * Warum statisch: die Middlewares hängen an einem echten `ViteDevServer` mit+ * laufendem ComfyUI-Starter, Ollama-Spawn und Whisper-Prozess; sie im Test zu+ * instanziieren hiesse, den halben Rechner zu starten. Was hier geprüft wird,+ * ist deshalb nicht das Verhalten, sondern dass die FORM der Fehler, die in+ * `src/dev/` behoben sind, nicht in `vite.config.ts` zurückkommt. Das Verhalten+ * selbst steht in http-body.test.ts, ssrf-policy.test.ts und+ * model-paths.test.ts — diese Datei sagt nur: die Datei benutzt sie auch.+ *+ * Dieselbe Technik benutzt schon `src/lib/__tests__/app-identity.test.ts` auf+ * derselben Datei.+ *+ * NEGATIVE CONTROL (von Hand geprüft): einen der verbotenen Ausdrücke in+ * vite.config.ts wieder einsetzen (z. B. `const x = JSON.parse(body)`) → der+ * zugehörige Fall wird rot.+ *+ * Run: npx vitest run src/dev/__tests__/dev-server-shape.test.ts+ */+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++/**+ * `vite.config.ts` ohne reine Kommentarzeilen.+ *+ * Die Kommentare der Datei ZITIEREN die alten Fehlerformen, um zu erklären,+ * warum es die Module in `src/dev/` gibt — ein Grep über den Rohtext würde also+ * genau die Erklärung als Verstoss lesen. Nur ganze Kommentarzeilen fallen weg;+ * ein Verstoss im Code steht nie auf einer solchen Zeile.+ */+const viteConfig = readFileSync(resolve(process.cwd(), 'vite.config.ts'), 'utf8')+ .split('\n')+ .filter((line) => {+ const t = line.trim()+ return !(t.startsWith('//') || t.startsWith('*') || t.startsWith('/*'))+ })+ .join('\n')++describe('der Request-Körper', () => {+ it('wird nirgends mehr chunkweise zu einem String addiert', () => {+ // `body += chunk` dekodiert jeden Chunk einzeln; ein Zeichen auf der+ // Chunk-Grenze zerfällt. Siehe http-body.test.ts.+ expect(viteConfig).not.toMatch(/body \+= c\b/)+ expect(viteConfig.match(/=> \{ body \+= /g)).toBeNull()+ })++ it('wird nirgends mehr ungeschützt geparst', () => {+ // `JSON.parse(body)` in einem `end`-Handler: der Wurf kommt an, wenn die+ // Middleware längst zurückgekehrt ist, niemand fängt ihn, und der ganze+ // `npm run dev`-Prozess endet. Drei Endpunkte hatten genau das.+ expect(viteConfig).not.toContain('JSON.parse(body)')+ })++ it('geht durch den einen geprüften Leser', () => {+ // Zwanzig Handler, ein Einstieg. Sinkt diese Zahl deutlich, wurde wieder+ // von Hand gepuffert.+ const stellen = viteConfig.match(/withJsonBody\(req, res, \(body\) =>/g) ?? []+ expect(stellen.length).toBeGreaterThanOrEqual(20)+ })+})++describe('Pfade aus dem Request', () => {+ it('bauen den ComfyUI-Zielpfad nicht mehr von Hand zusammen', () => {+ // `join(comfyPath, 'models', subfolder)` mit `subfolder: '../../..'` schrieb+ // ausserhalb der Installation. Siehe model-paths.test.ts.+ expect(viteConfig).not.toContain("join(comfyPath, 'models', subfolder")+ expect(viteConfig).not.toContain("join(comfyPath, 'models', subfolder, id)")+ expect(viteConfig).not.toContain('join(destDir, filename)')+ expect(viteConfig).not.toContain('join(customNodesDir, node_name')+ })++ it('gehen durch den Käfig', () => {+ expect(viteConfig).toContain('comfyDestPath(')+ expect(viteConfig).toContain('downloadToPathDest(')+ expect(viteConfig).toContain('customNodeDir(')+ })+})++describe('Prozessaufrufe aus dem Request', () => {+ it('bauen keine Shell-Zeile mehr aus fremden Werten', () => {+ // `execSync(\`git clone "${repo_url}" "${targetDir}"\`)`: die+ // doppelten Anführungszeichen sind keine Grenze, `x"; …; echo "` war ein+ // zweites Kommando.+ expect(viteConfig).not.toContain('git clone "${')+ expect(viteConfig).not.toContain('pip install -r "${')+ expect(viteConfig).toContain("execFileSync('git', ['clone'")+ })+})++describe('der SSRF-Wächter', () => {+ it('entscheidet nicht mehr auf der Schreibweise der Adresse', () => {+ // Die alten Präfix-/Regex-Prüfungen sahen `0:0:0:0:0:ffff:127.0.0.1` nicht.+ // Siehe ssrf-policy.test.ts.+ expect(viteConfig).not.toContain("lc.startsWith('fe80')")+ expect(viteConfig).not.toContain("lc.startsWith('64:ff9b:')")+ expect(viteConfig).toContain('createSsrfPolicy(')+ })++ it('lässt net.isIP das Orakel bleiben, statt es nachzubauen', () => {+ expect(viteConfig).toContain('net.isIP(value)')+ })+})diff --git a/src/dev/__tests__/http-body.test.ts b/src/dev/__tests__/http-body.test.tsnew file mode 100644index 00000000..13410f5bBinary files /dev/null and b/src/dev/__tests__/http-body.test.ts differdiff --git a/src/dev/__tests__/model-paths.test.ts b/src/dev/__tests__/model-paths.test.tsnew file mode 100644index 00000000..c2dd7b34--- /dev/null+++ b/src/dev/__tests__/model-paths.test.ts@@ -0,0 +1,198 @@+/**+ * SICHERHEITSBEFUND: die Zielpfade der Modell-Download-Endpunkte kamen+ * ungeprüft aus dem Request-Körper.+ *+ * Vier Endpunkte in `vite.config.ts` bauten mit `node:path.join` einen Pfad+ * aus Feldern des Körpers und schrieben oder lasen dann mit echten fs-Aufrufen+ * darauf. `join` normalisiert `..` klaglos weg — es ist keine Grenze:+ *+ * POST /local-api/download-model+ * { "url": "http://…", "subfolder": "../../../../../..", "filename": ".ssh/authorized_keys" }+ * → schrieb die heruntergeladene Datei ausserhalb der ComfyUI-Installation.+ *+ * POST /local-api/install-custom-node { "nodeName": "../../../.." }+ * → `git clone` in ein beliebiges Verzeichnis.+ *+ * POST /local-api/check-model-sizes { "files": [{ "subfolder": "../../..", … }] }+ * → Existenz und Grösse beliebiger Dateien abtastbar.+ *+ * Diese Tests sind die Grenze. Die Wurzelregel ist dieselbe wie in+ * `src/lib/dev-fs-jail.ts`; nur die Wurzel ist die ComfyUI-Installation statt+ * des Agenten-Arbeitsordners.+ *+ * NEGATIVE CONTROL (von Hand geprüft):+ * • in `comfyDestPath` das `containWithin(root, …)` durch+ * `lexicalNormalize(`${root}/${subfolder}/${filename}`)` ersetzen+ * → jeder Ausbruchsfall unten wird rot.+ * • in `downloadToPathDest` dasselbe → "filename kann destDir nicht verlassen" rot.+ * • in `customNodeDir` das `containWithin` weglassen → "nodeName ist ein Name,+ * kein Pfad" wird rot.+ * • in `repoBasename` das `.git`-Abschneiden entfernen → "der letzte+ * Pfadteil der Repo-URL" wird rot.+ *+ * Run: npx vitest run src/dev/__tests__/model-paths.test.ts+ */+import { describe, expect, it } from 'vitest'+import { JailEscapeError } from '../../lib/dev-fs-jail'+import {+ comfyDestPath,+ customNodeDir,+ downloadToPathDest,+ modelDirCandidates,+ repoBasename,+} from '../model-paths'++const COMFY = '/Users/dev/ComfyUI'++describe('comfyDestPath — der gute Fall', () => {+ it('legt ein Modell unter models/ ab', () => {+ expect(comfyDestPath(COMFY, 'checkpoints', 'sd15.safetensors', 'separator'))+ .toBe(`${COMFY}/models/checkpoints/sd15.safetensors`)+ })++ it('erlaubt eine Unterebene im subfolder', () => {+ expect(comfyDestPath(COMFY, 'diffusion_models/wan', 'wan.gguf', 'separator'))+ .toBe(`${COMFY}/models/diffusion_models/wan/wan.gguf`)+ })++ it('kennt den custom_nodes-Zweig mit Trenner', () => {+ expect(comfyDestPath(COMFY, 'custom_nodes/ComfyUI-GGUF', 'x.py', 'separator'))+ .toBe(`${COMFY}/custom_nodes/ComfyUI-GGUF/x.py`)+ })++ it('die drei Endpunkte entscheiden custom_nodes verschieden — und das bleibt sichtbar', () => {+ // 'prefix' (check-model-sizes) zählt schon den blossen Präfix mit …+ expect(comfyDestPath(COMFY, 'custom_nodes_alt', 'x', 'prefix'))+ .toBe(`${COMFY}/custom_nodes_alt/x`)+ // … 'separator' (download-model) verlangt den Trenner …+ expect(comfyDestPath(COMFY, 'custom_nodes_alt', 'x', 'separator'))+ .toBe(`${COMFY}/models/custom_nodes_alt/x`)+ // … und 'never' (resume-download) kennt den Fall gar nicht.+ expect(comfyDestPath(COMFY, 'custom_nodes/x', 'y', 'never'))+ .toBe(`${COMFY}/models/custom_nodes/x/y`)+ })+})++describe('comfyDestPath — der Käfig', () => {+ const ausbrüche: [string, string][] = [+ ['../../../../../..', '.ssh/authorized_keys'],+ ['..', 'x'],+ ['checkpoints/../../..', 'x'],+ ['./../../etc', 'passwd'],+ ['..\\..\\..\\Windows', 'System32'],+ ]++ it.each(ausbrüche)('lehnt subfolder %j ab', (subfolder, filename) => {+ expect(() => comfyDestPath(COMFY, subfolder, filename, 'separator')).toThrow(JailEscapeError)+ })++ it('lehnt einen absoluten subfolder ab', () => {+ expect(() => comfyDestPath(COMFY, '/etc', 'passwd', 'separator')).toThrow(JailEscapeError)+ expect(() => comfyDestPath(COMFY, 'C:\\Windows', 'x', 'separator')).toThrow(JailEscapeError)+ })++ it('lehnt ein filename ab, das aus dem subfolder herausführt', () => {+ expect(() => comfyDestPath(COMFY, 'checkpoints', '../../../../../../etc/passwd', 'separator'))+ .toThrow(JailEscapeError)+ })++ it('ein absoluter filename bleibt im Käfig statt ihn zu ersetzen', () => {+ // node:path.join hätte hier `${COMFY}/models/checkpoints/etc/passwd`+ // gebaut — dasselbe Ergebnis, aber aus Versehen. Hier ist es die Regel.+ expect(comfyDestPath(COMFY, 'checkpoints', '/etc/passwd', 'separator'))+ .toBe(`${COMFY}/models/checkpoints/etc/passwd`)+ })++ it('ein Präfix ist kein Verzeichnis', () => {+ // `${COMFY}-evil` fängt mit `${COMFY}` an, liegt aber nicht darin.+ expect(() => comfyDestPath(COMFY, '../ComfyUI-evil', 'x', 'separator')).toThrow(JailEscapeError)+ })++ it('lässt einen Namen mit Punkten in Ruhe', () => {+ expect(comfyDestPath(COMFY, 'checkpoints', 'v1..5.safetensors', 'separator'))+ .toBe(`${COMFY}/models/checkpoints/v1..5.safetensors`)+ expect(comfyDestPath(COMFY, 'checkpoints', '.hidden', 'separator'))+ .toBe(`${COMFY}/models/checkpoints/.hidden`)+ })+})++describe('downloadToPathDest', () => {+ it('legt die Datei in das gewählte Verzeichnis', () => {+ expect(downloadToPathDest('/Users/dev/.lmstudio/models', 'q4.gguf'))+ .toBe('/Users/dev/.lmstudio/models/q4.gguf')+ })++ it('filename kann destDir nicht verlassen', () => {+ // destDir ist hier absichtlich frei (das ist der Zweck des Endpunkts);+ // filename hat damit nichts zu tun.+ expect(() => downloadToPathDest('/Users/dev/.lmstudio/models', '../../../.bashrc'))+ .toThrow(JailEscapeError)+ expect(() => downloadToPathDest('/Users/dev/.lmstudio/models', '/etc/cron.d/x'))+ .toThrow(JailEscapeError)+ })+})++describe('repoBasename', () => {+ it('nimmt den letzten Pfadteil der Repo-URL', () => {+ expect(repoBasename('https://github.com/city96/ComfyUI-GGUF.git')).toBe('ComfyUI-GGUF')+ expect(repoBasename('https://github.com/city96/ComfyUI-GGUF')).toBe('ComfyUI-GGUF')+ expect(repoBasename('https://github.com/city96/ComfyUI-GGUF/')).toBe('ComfyUI-GGUF')+ expect(repoBasename('[email protected]:city96/ComfyUI-GGUF.git')).toBe('ComfyUI-GGUF')+ // Auch der Rückwärts-Trenner zählt: der Dev-Server läuft auch auf Windows,+ // wo `node:path.basename` genauso trennt.+ expect(repoBasename('C:\\repos\\ComfyUI-GGUF.git')).toBe('ComfyUI-GGUF')+ })++ it('gibt für nichts nichts zurück', () => {+ expect(repoBasename('')).toBe('')+ expect(repoBasename('///')).toBe('')+ })+})++describe('customNodeDir', () => {+ it('benutzt den nodeName, wenn er da ist', () => {+ expect(customNodeDir(COMFY, 'ComfyUI-GGUF', 'https://github.com/city96/ComfyUI-GGUF.git'))+ .toBe(`${COMFY}/custom_nodes/ComfyUI-GGUF`)+ })++ it('fällt auf den letzten Teil der Repo-URL zurück', () => {+ expect(customNodeDir(COMFY, '', 'https://github.com/city96/ComfyUI-GGUF.git'))+ .toBe(`${COMFY}/custom_nodes/ComfyUI-GGUF`)+ expect(customNodeDir(COMFY, ' ', 'https://github.com/city96/ComfyUI-GGUF.git'))+ .toBe(`${COMFY}/custom_nodes/ComfyUI-GGUF`)+ })++ it('nodeName ist ein Name, kein Pfad', () => {+ for (const name of ['../../..', '../evil', '/etc/cron.d', '..\\..\\evil']) {+ expect(() => customNodeDir(COMFY, name, 'https://x/y.git'), name).toThrow(JailEscapeError)+ }+ })++ it('auch der Rückfall aus der Repo-URL geht durch den Käfig', () => {+ expect(() => customNodeDir(COMFY, '', 'https://evil/..')).toThrow()+ })++ it('ohne nodeName und ohne brauchbare URL wird nichts angelegt', () => {+ expect(() => customNodeDir(COMFY, '', '')).toThrow('Missing nodeName and unusable repoUrl')+ })+})++describe('modelDirCandidates', () => {+ it('gibt jedem Anbieter sein eigenes Verzeichnis', () => {+ // Vorher bekam JEDER Anbieter das von LM Studio zurück, auch Ollama.+ expect(modelDirCandidates('ollama')).toEqual([['.ollama', 'models']])+ expect(modelDirCandidates('jan')).toEqual([['.jan', 'models'], ['jan', 'models']])+ expect(modelDirCandidates('gpt4all')).toEqual([['.cache', 'gpt4all']])+ expect(modelDirCandidates('lm studio')[0]).toEqual(['.lmstudio', 'models'])+ })++ it('ist unabhängig von Gross-/Kleinschreibung und kennt beide LM-Studio-Schreibweisen', () => {+ expect(modelDirCandidates('Ollama')).toEqual(modelDirCandidates('ollama'))+ expect(modelDirCandidates('LMStudio')).toEqual(modelDirCandidates('lm studio'))+ })++ it('gibt für Unbekanntes nichts zurück, damit der Aufrufer sein Fallback nimmt', () => {+ expect(modelDirCandidates('')).toEqual([])+ expect(modelDirCandidates('irgendwas')).toEqual([])+ })+})diff --git a/src/dev/__tests__/ssrf-policy.test.ts b/src/dev/__tests__/ssrf-policy.test.tsnew file mode 100644index 00000000..0303c37c--- /dev/null+++ b/src/dev/__tests__/ssrf-policy.test.ts@@ -0,0 +1,258 @@+/**+ * Der SSRF-Wächter der Dev-Proxies — die Regeln, gegen echte Adressen.+ *+ * `/local-api/proxy-image` und `/local-api/proxy-download` holen eine URL, die+ * der Aufrufer bestimmt. Im gepackten Build steht davor `validate_public_url`+ * (Rust); unter `npm run dev` steht davor nur dieser Wächter.+ *+ * Der Befund, der diese Datei ausgelöst hat: die IPv6-Hälfte prüfte auf+ * SCHREIBWEISE, nicht auf Adresse. `lc.startsWith('fe80')`, `/::ffff:…$/` —+ * das trägt nur, solange der Text schon komprimiert vorliegt. Nachgemessen:+ *+ * - `0:0:0:0:0:ffff:127.0.0.1` ist gültiges IPv6 (`net.isIP` → 6) und+ * erreicht nachweislich einen Server auf 127.0.0.1; keine der alten+ * Regexen traf darauf.+ * - `::7f00:1` (IPv4-kompatibel), `ff02::1` (Multicast) und `fec0::1`+ * (site-local) kamen ebenfalls durch.+ *+ * Über die Proxy-Endpunkte rettete bisher der WHATWG-URL-Parser die Lage (er+ * komprimiert den Host, bevor der Wächter ihn sieht). Der Wächter läuft aber+ * AUCH über DNS-Antworten — dort normalisiert niemand. Deshalb wird hier+ * beides geprüft: `checkUrl` mit dem URL-Parser davor, und `isBlockedIp` roh,+ * so wie die DNS-Auflösung es aufruft.+ *+ * `net.isIP` ist auch im Test das Orakel, damit „ist das eine IP-Literal"+ * hier und in vite.config.ts nicht auseinanderlaufen kann.+ *+ * NEGATIVE CONTROL (von Hand geprüft):+ * • in `isBlockedIpv6` die Zeile `if (zeroPrefix(6)) return true` entfernen+ * → "::1", "::" und "::7f00:1" werden rot.+ * • die `zeroPrefix(5) && groups[5] === 0xffff`-Zeile entfernen+ * → jede IPv4-mapped-Schreibweise wird rot.+ * • in `parseIpv6Groups` die Zeile `if (fill < 1) return null` streichen+ * → "eine zu lange Adresse ist keine Adresse" wird rot.+ * • in `createSsrfPolicy` `groups === null ? true` zu `false` machen+ * → "unlesbares IPv6 wird gesperrt" wird rot.+ *+ * Run: npx vitest run src/dev/__tests__/ssrf-policy.test.ts+ */+import { describe, expect, it } from 'vitest'+import net from 'node:net'+import { createSsrfPolicy, parseIpv6Groups } from '../ssrf-policy'++const policy = createSsrfPolicy((value) => net.isIP(value))++/** Wie `assertPublicUrl` in vite.config.ts: der Host geht durch `new URL`. */+function hostOfUrl(urlStr: string): string {+ return new URL(urlStr).hostname.replace(/^\[|\]$/g, '')+}++describe('parseIpv6Groups', () => {+ it('zerlegt die volle Schreibweise', () => {+ expect(parseIpv6Groups('2606:4700:0:0:0:0:0:1111')).toEqual([0x2606, 0x4700, 0, 0, 0, 0, 0, 0x1111])+ })++ it('füllt die `::`-Kompression auf', () => {+ expect(parseIpv6Groups('::')).toEqual([0, 0, 0, 0, 0, 0, 0, 0])+ expect(parseIpv6Groups('::1')).toEqual([0, 0, 0, 0, 0, 0, 0, 1])+ expect(parseIpv6Groups('2606:4700::1111')).toEqual([0x2606, 0x4700, 0, 0, 0, 0, 0, 0x1111])+ })++ it('rechnet eine angehängte IPv4 in zwei Gruppen um', () => {+ expect(parseIpv6Groups('::ffff:127.0.0.1')).toEqual([0, 0, 0, 0, 0, 0xffff, 0x7f00, 1])+ // Genau die Schreibweise, die der alte Wächter nicht sah:+ expect(parseIpv6Groups('0:0:0:0:0:ffff:127.0.0.1')).toEqual([0, 0, 0, 0, 0, 0xffff, 0x7f00, 1])+ })++ it('ignoriert eine Zonen-ID und die Klammern', () => {+ expect(parseIpv6Groups('[fe80::1%en0]')).toEqual([0xfe80, 0, 0, 0, 0, 0, 0, 1])+ })++ it('eine zu lange Adresse ist keine Adresse', () => {+ expect(parseIpv6Groups('1:2:3:4:5:6:7:8:9')).toBeNull()+ expect(parseIpv6Groups('1:2:3:4:5:6:7:8::9')).toBeNull()+ expect(parseIpv6Groups('1:2:3')).toBeNull()+ expect(parseIpv6Groups('::1::2')).toBeNull()+ expect(parseIpv6Groups('gggg::1')).toBeNull()+ expect(parseIpv6Groups('::ffff:999.1.1.1')).toBeNull()+ })+})++describe('isBlockedIp — IPv4', () => {+ it('sperrt, was nicht öffentlich routbar ist', () => {+ for (const ip of [+ '0.0.0.0', '10.0.0.1', '127.0.0.1', '127.1.2.3',+ '169.254.169.254', // Cloud-Metadaten+ '172.16.0.1', '172.31.255.255', '192.168.1.1',+ '100.64.0.1', '100.127.0.1', // CGNAT+ '224.0.0.1', '255.255.255.255',+ ]) {+ expect(policy.isBlockedIp(ip), ip).toBe(true)+ }+ })++ it('lässt öffentliche Adressen durch', () => {+ for (const ip of ['1.1.1.1', '8.8.8.8', '172.15.0.1', '172.32.0.1', '100.63.255.255', '223.255.255.255']) {+ expect(policy.isBlockedIp(ip), ip).toBe(false)+ }+ })+})++describe('isBlockedIp — IPv6', () => {+ it('sperrt Loopback und die Unspecified-Adresse in jeder Schreibweise', () => {+ for (const ip of ['::1', '::', '0:0:0:0:0:0:0:1', '0000:0000:0000:0000:0000:0000:0000:0001']) {+ expect(policy.isBlockedIp(ip), ip).toBe(true)+ }+ })++ it('sperrt IPv4-mapped auch ungekürzt geschrieben', () => {+ // DER BEFUND: alle drei zeigen auf 127.0.0.1, der alte Wächter sah nur+ // die ersten beiden.+ for (const ip of ['::ffff:127.0.0.1', '::ffff:7f00:1', '0:0:0:0:0:ffff:127.0.0.1', '0:0:0:0:0:ffff:7f00:1']) {+ expect(net.isIP(ip), `${ip} muss eine gültige IPv6 sein`).toBe(6)+ expect(policy.isBlockedIp(ip), ip).toBe(true)+ }+ // ... und die Metadaten-Adresse ebenso.+ for (const ip of ['::ffff:169.254.169.254', '0:0:0:0:0:ffff:a9fe:a9fe']) {+ expect(policy.isBlockedIp(ip), ip).toBe(true)+ }+ })++ it('sperrt IPv4-kompatible Adressen (::/96)', () => {+ // `::127.0.0.1` — abgeschafft, aber `net.isIP` sagt 6 und der alte+ // Wächter liess sie durch.+ for (const ip of ['::127.0.0.1', '::7f00:1', '::a9fe:a9fe']) {+ expect(policy.isBlockedIp(ip), ip).toBe(true)+ }+ })++ it('sperrt link-local, ULA, site-local, NAT64 und Multicast', () => {+ for (const ip of [+ 'fe80::1', 'febf::1', // fe80::/10 — der alte `startsWith('fe80')` traf febf nicht+ 'fc00::1', 'fd12:3456::1', // ULA+ 'fec0::1', // site-local+ '64:ff9b::1.1.1.1', // NAT64+ 'ff02::1', 'ff00::1', // Multicast+ ]) {+ expect(policy.isBlockedIp(ip), ip).toBe(true)+ }+ })++ it('lässt öffentliche IPv6-Adressen durch', () => {+ for (const ip of ['2606:4700:4700::1111', '2001:4860:4860::8888', '2a00:1450:4001:81b::200e']) {+ expect(policy.isBlockedIp(ip), ip).toBe(false)+ }+ })++ it('was nicht als IP-Literal gilt, entscheidet der Aufrufer per DNS', () => {+ expect(policy.isBlockedIp('example.com')).toBe(false)+ expect(policy.isBlockedIp('0177.0.0.1')).toBe(false) // net.isIP → 0+ })++ it('was das Orakel IPv6 nennt, muss die Zerlegung auch lesen können', () => {+ // Die Zusicherung hinter der Bauart: `net.isIP` sagt, WAS eine Adresse+ // ist, dieses Modul sagt, ob sie gesperrt ist. Ein Loch zwischen den+ // beiden wäre genau die Lücke, die der alte Wächter hatte.+ for (const ip of [+ '::', '::1', '::ffff:1.2.3.4', '0:0:0:0:0:ffff:1.2.3.4', '::127.0.0.1',+ '1:2:3:4:5:6:7:8', 'fe80::1', 'fc00::1', 'ff02::1', '64:ff9b::1.1.1.1',+ '2606:4700:4700::1111', '2001:db8::', 'a:b:c:d:e:f:0:1',+ '0000:0000:0000:0000:0000:0000:0000:0000',+ ]) {+ expect(net.isIP(ip), ip).toBe(6)+ expect(parseIpv6Groups(ip), ip).not.toBeNull()+ }+ })++ it('unlesbares IPv6 wird gesperrt, nicht durchgewinkt', () => {+ // Sollte die Zerlegung doch einmal an einer Schreibweise scheitern, die+ // das Orakel akzeptiert, ist die Antwort "sperren". Hier lügt das Orakel+ // absichtlich, damit dieser Zweig überhaupt erreichbar ist.+ const lügendesOrakel = createSsrfPolicy(() => 6)+ expect(lügendesOrakel.isBlockedIp('gar keine adresse')).toBe(true)+ expect(lügendesOrakel.isBlockedIp('1:2:3')).toBe(true)+ expect(lügendesOrakel.checkResolved(['1:2:3'])).toEqual({ ok: false, reason: 'blocked resolved ip' })+ })+})++describe('checkUrl', () => {+ it('lehnt fremde Schemata ab', () => {+ for (const url of ['file:///etc/passwd', 'ftp://example.com/x', 'data:text/plain,x']) {+ expect(policy.checkUrl(url)).toEqual({ kind: 'deny', reason: 'scheme not allowed' })+ }+ })++ it('lehnt Unlesbares ab', () => {+ expect(policy.checkUrl('nicht mal eine url')).toEqual({ kind: 'deny', reason: 'invalid url' })+ })++ it('lehnt localhost und *.localhost ab', () => {+ for (const url of ['http://localhost:8188/x', 'http://evil.localhost/x']) {+ expect(policy.checkUrl(url)).toEqual({ kind: 'deny', reason: 'blocked host' })+ }+ })++ it('lehnt inet_aton-Schreibweisen ab', () => {+ // 2130706433 === 127.0.0.1, dasselbe hexadezimal und oktal.+ // BEFUND (kein Loch, aber gut zu wissen): der WHATWG-Parser rechnet diese+ // Formen SELBST in die punktierte Notation um, bevor der Wächter den Host+ // sieht — `new URL('http://2130706433/x').hostname` ist '127.0.0.1'. Der+ // `blocked numeric host`-Zweig kann über checkUrl also nie auslösen; die+ // Ablehnung kommt aus der IP-Tabelle. Der Zweig bleibt als Netz für einen+ // Aufrufer, der isBlockedIp ohne URL-Parser davor benutzt.+ for (const url of ['http://2130706433/x', 'http://0x7f000001/x', 'http://017700000001/x', 'http://3232235777/x']) {+ expect(policy.checkUrl(url), url).toEqual({ kind: 'deny', reason: 'blocked ip' })+ }+ expect(hostOfUrl('http://2130706433/x')).toBe('127.0.0.1')+ })++ it('lehnt interne IP-Literale ab', () => {+ for (const url of [+ 'http://127.0.0.1:8188/x',+ 'http://169.254.169.254/latest/meta-data/',+ 'http://[::1]:8188/x',+ 'http://[fe80::1]/x',+ 'http://[0:0:0:0:0:ffff:127.0.0.1]/x',+ 'http://[::127.0.0.1]/x',+ ]) {+ expect(policy.checkUrl(url), url).toEqual({ kind: 'deny', reason: 'blocked ip' })+ }+ })++ it('lässt eine öffentliche IP direkt durch, ohne DNS', () => {+ const verdict = policy.checkUrl('https://1.1.1.1/logo.png')+ expect(verdict.kind).toBe('allow')+ })++ it('schickt einen Namen zur Auflösung', () => {+ const verdict = policy.checkUrl('https://civitai.com/api/x.png')+ expect(verdict).toMatchObject({ kind: 'resolve', host: 'civitai.com' })+ })++ it('deckt sich mit isBlockedIp auf dem Host, den der URL-Parser liefert', () => {+ // Der Parser komprimiert `[0:0:0:0:0:ffff:127.0.0.1]` zu `::ffff:7f00:1` —+ // beide Wege müssen zum selben Urteil kommen, sonst hängt der Schutz an+ // einer Normalisierung, die der DNS-Pfad nicht hat.+ const raw = 'http://[0:0:0:0:0:ffff:127.0.0.1]/x'+ expect(policy.isBlockedIp(hostOfUrl(raw))).toBe(true)+ expect(policy.isBlockedIp('0:0:0:0:0:ffff:127.0.0.1')).toBe(true)+ })+})++describe('checkResolved', () => {+ it('eine leere DNS-Antwort ist kein Freibrief', () => {+ expect(policy.checkResolved([])).toEqual({ ok: false, reason: 'dns empty' })+ })++ it('EINE interne Adresse reicht zur Ablehnung', () => {+ // DNS-Rebinding-Nachbarschaft: ein Name, der A und AAAA hat.+ expect(policy.checkResolved(['93.184.216.34', '127.0.0.1']))+ .toEqual({ ok: false, reason: 'blocked resolved ip' })+ expect(policy.checkResolved(['93.184.216.34', '0:0:0:0:0:ffff:127.0.0.1']))+ .toEqual({ ok: false, reason: 'blocked resolved ip' })+ })++ it('lässt rein öffentliche Antworten durch', () => {+ expect(policy.checkResolved(['93.184.216.34', '2606:2800:220:1:248:1893:25c8:1946'])).toEqual({ ok: true })+ })+})diff --git a/src/dev/__tests__/web-search-parse.test.ts b/src/dev/__tests__/web-search-parse.test.tsnew file mode 100644index 00000000..ad7f7220--- /dev/null+++ b/src/dev/__tests__/web-search-parse.test.ts@@ -0,0 +1,203 @@+/**+ * `/local-api/web-search` wertet fünf FREMDE Antworten aus und reicht das+ * Ergebnis an das Modell weiter. Vorher lief jede davon durch ein+ * `(r: any) => ({ title: r.title || '', … })` — also ungeprüft.+ *+ * Was diese Tests festnageln, ist die Grenze: was hereinkommt, hat keine+ * zugesicherte Form, und was hinausgeht, hat drei Strings.+ *+ * NEGATIVE CONTROL (von Hand geprüft):+ * • in `listAt` das `.filter(isRecord)` streichen+ * → "verwirft Einträge, die keine Objekte sind" wird rot.+ * • in `text` das `asString(...) ?? ''` durch `String(record[key] ?? '')`+ * ersetzen → "eine Zahl im Titel ist kein Titel" wird rot.+ * • in `parseWikipediaResults` den `title === ''`-Zweig entfernen+ * → "ein Eintrag ohne Titel wirft nicht" wird rot (TypeError).+ * • in `parseDdgHtmlResults` `/^https?:\/\//i` durch `url.startsWith('http')`+ * ersetzen → "nur http(s) kommt durch" wird rot.+ *+ * Run: npx vitest run src/dev/__tests__/web-search-parse.test.ts+ */+import { describe, expect, it } from 'vitest'+import {+ parseBraveResults,+ parseDdgHtmlResults,+ parseSearxngResults,+ parseTavilyResults,+ parseWikipediaResults,+} from '../web-search-parse'++/** Die vier JSON-Auswerter, jeder mit seiner echten Antwortform. */+const jsonParsers = [+ {+ name: 'SearXNG',+ parse: parseSearxngResults,+ good: { results: [{ title: 'T', url: 'https://a.example/1', content: 'S' }] },+ withoutList: { results: 'nope' },+ },+ {+ name: 'Brave',+ parse: parseBraveResults,+ good: { web: { results: [{ title: 'T', url: 'https://a.example/1', description: 'S' }] } },+ withoutList: { web: {} },+ },+ {+ name: 'Tavily',+ parse: parseTavilyResults,+ good: { results: [{ title: 'T', url: 'https://a.example/1', content: 'S' }] },+ withoutList: {},+ },+] as const++describe.each(jsonParsers)('$name', ({ parse, good, withoutList }) => {+ it('nimmt die Treffer heraus', () => {+ expect(parse(good, 5)).toEqual([{ title: 'T', url: 'https://a.example/1', snippet: 'S' }])+ })++ it('kappt bei max', () => {+ const many = JSON.parse(JSON.stringify(good)) as Record<string, unknown>+ const list = (('web' in many ? (many.web as { results: unknown[] }).results : many.results) as unknown[])+ for (let i = 0; i < 20; i++) list.push({ ...(list[0] as object), url: `https://a.example/${i + 2}` })+ expect(parse(many, 3)).toHaveLength(3)+ })++ it('gibt für eine Antwort ohne Liste nichts zurück, statt zu werfen', () => {+ expect(parse(withoutList, 5)).toEqual([])+ expect(parse(undefined, 5)).toEqual([])+ expect(parse(null, 5)).toEqual([])+ expect(parse('ein String', 5)).toEqual([])+ expect(parse(42, 5)).toEqual([])+ })+})++describe('SearXNG im Einzelnen', () => {+ it('verwirft Einträge, die keine Objekte sind', () => {+ const data = {+ results: ['string', null, 42, { title: 'T', url: 'https://a.example/1', content: 'S' }],+ }+ expect(parseSearxngResults(data, 5)).toEqual([{ title: 'T', url: 'https://a.example/1', snippet: 'S' }])+ })++ it('eine Zahl im Titel ist kein Titel', () => {+ // Ein `String(r.title)` hätte hier "42" als Überschrift ans Modell gegeben.+ const data = { results: [{ title: 42, url: 'https://a.example/1', content: null }] }+ expect(parseSearxngResults(data, 5)).toEqual([{ title: '', url: 'https://a.example/1', snippet: '' }])+ })++ it('wirft einen Eintrag ohne Titel UND ohne URL weg', () => {+ const data = { results: [{ content: 'nur ein Schnipsel' }, { title: 'T', url: '', content: '' }] }+ expect(parseSearxngResults(data, 5)).toEqual([{ title: 'T', url: '', snippet: '' }])+ })+})++describe('Wikipedia', () => {+ const data = {+ query: {+ search: [+ { title: 'Ada Lovelace', snippet: 'Eine <span class="hit">Mathematikerin</span>' },+ { title: 'Grace Hopper', snippet: 'Konteradmiralin' },+ ],+ },+ }++ it('baut die Artikel-URL aus dem Titel', () => {+ expect(parseWikipediaResults(data, 5)).toEqual([+ {+ title: 'Ada Lovelace',+ url: 'https://en.wikipedia.org/wiki/Ada_Lovelace',+ snippet: 'Eine Mathematikerin',+ },+ {+ title: 'Grace Hopper',+ url: 'https://en.wikipedia.org/wiki/Grace_Hopper',+ snippet: 'Konteradmiralin',+ },+ ])+ })++ it('kodiert Sonderzeichen im Titel', () => {+ const result = parseWikipediaResults({ query: { search: [{ title: 'C++ (Sprache)' }] } }, 5)+ expect(result[0].url).toBe('https://en.wikipedia.org/wiki/C%2B%2B_(Sprache)')+ })++ it('ein Eintrag ohne Titel wirft nicht', () => {+ // Vorher: `title: r.title || ''` und direkt daneben `r.title.replace(…)`.+ // Ein Eintrag ohne Titel warf eine TypeError in der LETZTEN Ebene der+ // Suchkette — aus "keine Treffer" wurde "alle Ebenen fehlgeschlagen".+ const kaputt = { query: { search: [{ snippet: 'ohne Titel' }, { title: 'Da' }] } }+ expect(() => parseWikipediaResults(kaputt, 5)).not.toThrow()+ expect(parseWikipediaResults(kaputt, 5)).toEqual([+ { title: 'Da', url: 'https://en.wikipedia.org/wiki/Da', snippet: '' },+ ])+ })++ it('gibt für eine Antwort ohne query.search nichts zurück', () => {+ expect(parseWikipediaResults({ query: {} }, 5)).toEqual([])+ expect(parseWikipediaResults({}, 5)).toEqual([])+ })+})++describe('DuckDuckGo-HTML', () => {+ const page = [+ '<div class="result">',+ '<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fa.example%2F1&rut=x">Erster <b>Treffer</b></a>',+ '<a class="result__snippet" href="#">Ein Schnipsel & mehr</a>',+ '</div>',+ '<div class="result">',+ '<a class="result__a" href="https://b.example/2">Zweiter "Treffer"</a>',+ '<a class="result__snippet" href="#">Noch einer</a>',+ '</div>',+ ].join('\n')++ it('packt die DDG-Weiterleitung aus', () => {+ expect(parseDdgHtmlResults(page, 5)[0]).toEqual({+ title: 'Erster Treffer',+ url: 'https://a.example/1',+ snippet: 'Ein Schnipsel & mehr',+ })+ })++ it('nimmt auch direkte Links', () => {+ expect(parseDdgHtmlResults(page, 5)[1]).toEqual({+ title: 'Zweiter "Treffer"',+ url: 'https://b.example/2',+ snippet: 'Noch einer',+ })+ })++ it('kappt bei max', () => {+ expect(parseDdgHtmlResults(page, 1)).toHaveLength(1)+ })++ it('nur http(s) kommt durch', () => {+ // `startsWith('http')` liess `httpfoo://` und – über die uddg-Umleitung –+ // jedes Schema durch, das mit "http" anfängt.+ const böse = [+ '<a class="result__a" href="//duckduckgo.com/l/?uddg=javascript%3Aalert(1)">Klick</a>',+ '<a class="result__a" href="//duckduckgo.com/l/?uddg=data%3Atext%2Fhtml%2Cx">Auch</a>',+ '<a class="result__a" href="httpfoo://x/1">Fast</a>',+ '<a class="result__a" href="https://gut.example/1">Gut</a>',+ ].join('\n')+ expect(parseDdgHtmlResults(böse, 5)).toEqual([+ { title: 'Gut', url: 'https://gut.example/1', snippet: '' },+ ])+ })++ it('überlebt eine kaputte Prozent-Kodierung', () => {+ const kaputt = '<a class="result__a" href="//duckduckgo.com/l/?uddg=%E0%A4%A">Kaputt</a>'+ expect(() => parseDdgHtmlResults(kaputt, 5)).not.toThrow()+ expect(parseDdgHtmlResults(kaputt, 5)).toEqual([])+ })++ it('gibt für eine Seite ohne Treffer nichts zurück', () => {+ expect(parseDdgHtmlResults('<html><body>Kein Ergebnis</body></html>', 5)).toEqual([])+ expect(parseDdgHtmlResults('', 5)).toEqual([])+ })++ it('kommt ohne Schnipsel aus', () => {+ const ohne = '<a class="result__a" href="https://a.example/1">Nur Titel</a>'+ expect(parseDdgHtmlResults(ohne, 5)).toEqual([+ { title: 'Nur Titel', url: 'https://a.example/1', snippet: '' },+ ])+ })+})diff --git a/src/dev/console-strip.ts b/src/dev/console-strip.tsnew file mode 100644index 00000000..edd050cc--- /dev/null+++ b/src/dev/console-strip.ts@@ -0,0 +1,166 @@+/**+ * §1.6 — `console.log/info/debug` aus dem PRODUKTIONS-Build entfernen,+ * `warn`/`error` behalten. Der Entscheidungs- und Rechenteil des+ * vite-Plugins `lu-strip-console`, ohne vite.+ *+ * Warum von Hand statt per Minifier-Option: das vite 8 hier ist rolldown-basiert+ * und benutzt den oxc-Minifier — der alte `esbuild: { drop, pure }`-Block war+ * damit TOT und `console.*` ging mit ins Bündel. rolldowns oxc-`CompressOptions`+ * kennt nur ein Alles-oder-nichts-`dropConsole`, das `warn`/`error` mitnehmen+ * würde. Also entfernen wir die drei lauten Methoden selbst.+ *+ * Warum das hier steht und nicht mehr in `vite.config.ts`: dieses Plugin+ * schreibt Produktionscode um und war ungetestet. Beim Herauslösen fiel ein+ * toter Zweig auf — der Sonderfall für `switch`-Zweige prüfte+ * `parentKey === 'consequent'`, aber an der Stelle, an der er geprüft wurde,+ * steht der Schlüssel immer auf `'expression'` (der Schlüssel des Aufrufs in+ * SEINEM Elternknoten, dem ExpressionStatement). Der Zweig konnte nie+ * auslösen; `case 1: console.log(x)` wurde zu `case 1: void 0` statt gelöscht.+ * Falsch war nur die Aufräumung, nicht das Ergebnis — aber ein Zweig, der nie+ * läuft, ist keine Absicherung.+ *+ * Der AST kommt aus vites `parseAst` (oxc, ESTree mit Byte-Offsets) — fremde+ * Daten, also `unknown` plus Prüfung an der Grenze statt einer selbstgebauten+ * Knoten-Schnittstelle, die nur behauptet, was drinsteht.+ *+ * REIN, ABSICHTLICH: kein `node:*`- und kein `vite`-Import, damit das Modul in+ * `src` neben seinem Test liegen kann.+ */++import { asNumber, asString, isRecord, prop } from '../types/json-guards'++/** Die drei Methoden, die verschwinden. `warn`/`error` bleiben. */+const TARGETS = new Set(['log', 'info', 'debug'])++/** Dateiendungen, in denen überhaupt umgeschrieben wird. */+const STRIPPABLE = /\.[cm]?[jt]sx?$/++/**+ * Container, aus denen ein ExpressionStatement ersatzlos verschwinden darf:+ * die Geschwister (oder der leere Block) bleiben gültiger Code.+ *+ * `SwitchCase` gehört dazu — ein `case 1:` ohne Rumpf ist erlaubt.+ */+const STATEMENT_LIST_PARENTS = new Set(['BlockStatement', 'Program', 'StaticBlock', 'SwitchCase'])++/** Ein Textbereich, der durch `replacement` ersetzt wird. */+export interface ConsoleRemoval {+ start: number+ end: number+ /** `''` löscht, `'void 0'` neutralisiert und lässt einen Ausdruck stehen. */+ replacement: string+}++/** Der `type` eines ESTree-Knotens, oder `undefined` wenn es keiner ist. */+function nodeType(value: unknown): string | undefined {+ return isRecord(value) ? asString(value.type) : undefined+}++/**+ * Wird in dieser Datei überhaupt umgeschrieben?+ *+ * Der strukturierte Logger (`src/lib/logger.ts`) ist die EINE erlaubte+ * console-Senke: er serialisiert in Produktion jedes Ereignis als einzeilige+ * JSON-Zeile über `console.log`. Dieser Aufruf ist ein klammerloses+ * `else console.log(line)`; würde das Plugin ihn zu `void 0` machen, wäre jedes+ * `log.info`/`log.debug` in Produktion stumm. Also bleibt der Logger+ * unangetastet, wie `node_modules`.+ */+export function isStrippableModule(id: string, code: string): boolean {+ if (id.includes('\0')) return false // virtuelles Modul+ if (id.includes('node_modules')) return false+ const clean = id.split('?')[0]+ if (/[\\/]lib[\\/]logger\.[cm]?[jt]sx?$/.test(clean)) return false+ if (!STRIPPABLE.test(clean)) return false+ return code.includes('console.')+}++/**+ * True genau dann, wenn `node` ein `console.log(…)` / `.info` / `.debug` ist.+ *+ * Nur der blanke `console.<m>(…)`-Aufruf zählt — `foo.console.log`,+ * `myLogger.log` und ein zugewiesenes `const x = console.log` bleiben stehen.+ */+export function isStrippableConsoleCall(node: unknown): boolean {+ if (nodeType(node) !== 'CallExpression') return false+ const callee = prop(node, 'callee')+ if (nodeType(callee) !== 'MemberExpression') return false+ if (prop(callee, 'computed') === true) return false+ const object = prop(callee, 'object')+ const property = prop(callee, 'property')+ return (+ nodeType(object) === 'Identifier' &&+ asString(prop(object, 'name')) === 'console' &&+ nodeType(property) === 'Identifier' &&+ TARGETS.has(asString(prop(property, 'name')) ?? '')+ )+}++/**+ * Alle zu entfernenden Bereiche eines geparsten Moduls, in Quelltext-Reihenfolge+ * des Besuchs (die Anwendung sortiert selbst).+ *+ * • Ganzer Aufruf als eigene Anweisung in einer Anweisungsliste+ * → die Anweisung fällt weg.+ * • Ganzer Aufruf als klammerloser Rumpf eines if/else/for/while/do/label+ * → der AUFRUF wird `void 0`, damit der Zweig eine Anweisung behält+ * (`else void 0;`). Löschen würde das `else` verwaisen lassen.+ * • Aufruf als Teilausdruck (`a && console.log(b)`, Ternär-Arm, Argument)+ * → der Aufruf wird `void 0`.+ */+export function collectConsoleRemovals(ast: unknown): ConsoleRemoval[] {+ const removals: ConsoleRemoval[] = []++ const push = (node: unknown, replacement: string): void => {+ const start = asNumber(prop(node, 'start'))+ const end = asNumber(prop(node, 'end'))+ // Ohne Byte-Offsets lässt sich nichts schneiden — dann lieber den Aufruf+ // stehen lassen als an einer geratenen Stelle schneiden.+ if (start === undefined || end === undefined) return+ removals.push({ start, end, replacement })+ }++ const visit = (node: unknown, parent: unknown, grandparent: unknown): void => {+ if (nodeType(node) === undefined || !isRecord(node)) return++ if (isStrippableConsoleCall(node)) {+ const isOwnStatement =+ nodeType(parent) === 'ExpressionStatement' && prop(parent, 'expression') === node+ const container = nodeType(grandparent)+ if (isOwnStatement && container !== undefined && STATEMENT_LIST_PARENTS.has(container)) {+ push(parent, '') // inklusive des abschliessenden `;`+ } else {+ push(node, 'void 0')+ }+ return // nicht in die Argumente eines Aufrufs absteigen, der wegfällt+ }++ for (const key of Object.keys(node)) {+ if (key === 'start' || key === 'end' || key === 'parent') continue+ const child = node[key]+ if (Array.isArray(child)) {+ for (const item of child) {+ if (nodeType(item) !== undefined) visit(item, node, parent)+ }+ } else if (nodeType(child) !== undefined) {+ visit(child, node, parent)+ }+ }+ }++ visit(ast, undefined, undefined)+ return removals+}++/**+ * Die Bereiche auf den Quelltext anwenden — von hinten nach vorn, damit die+ * früheren Offsets gültig bleiben.+ */+export function applyConsoleRemovals(code: string, removals: readonly ConsoleRemoval[]): string {+ const ordered = [...removals].sort((a, b) => b.start - a.start)+ let out = code+ for (const removal of ordered) {+ out = out.slice(0, removal.start) + removal.replacement + out.slice(removal.end)+ }+ return out+}diff --git a/src/dev/http-body.ts b/src/dev/http-body.tsnew file mode 100644index 00000000..b424bf8a--- /dev/null+++ b/src/dev/http-body.ts@@ -0,0 +1,114 @@+/**+ * Der Request-Körper der `/local-api`-Endpunkte des Dev-Servers — Dekodierung+ * und Feldzugriff an der Grenze.+ *+ * Warum das eine eigene Datei ist: `vite.config.ts` hat diesen Block+ * zwanzigmal wortgleich stehen —+ *+ * let body = ''+ * req.on('data', (c) => { body += c })+ * req.on('end', () => { const { path } = JSON.parse(body) ... })+ *+ * — und darin stecken zwei Fehler, die zwanzigmal mitkopiert wurden:+ *+ * 1. `body += c` dekodiert JEDEN Chunk einzeln nach UTF-8. Ein Zeichen, das+ * über eine Chunk-Grenze fällt (Node schneidet bei ~64 KiB, mitten im+ * Zeichen), wird zweimal halb dekodiert und kommt als U+FFFD an. Für+ * `/local-api/file-write` heisst das: die Datei auf der Platte bekommt+ * kaputte Zeichen, sobald der Inhalt gross genug ist. `decodeBodyChunks`+ * dekodiert stattdessen EINMAL über die zusammengesetzten Bytes.+ *+ * 2. `JSON.parse(body)` ohne `try` in einem `end`-Handler. Der Handler läuft+ * lange nachdem die Middleware zurückgekehrt ist; niemand fängt den+ * Wurf mehr ab, und ein einziger POST mit kaputtem Körper beendet den+ * ganzen `npm run dev`-Prozess. `parseJsonBody` gibt ein Ergebnis zurück+ * statt zu werfen, damit es keinen Aufrufer mehr gibt, der es vergessen+ * kann.+ *+ * Fremde Daten → `unknown` plus Prüfung an der Grenze: der geparste Körper+ * verlässt dieses Modul als `unknown`, und die Feldleser darunter sind dünne+ * Hüllen um `src/types/json-guards.ts` — kein zweiter Werkzeugkasten, nur die+ * beiden Bequemlichkeiten (Feldname statt Wert, Alias-Namen), die die+ * Endpunkte tatsächlich brauchen.+ *+ * REINE STRINGS UND BYTES, ABSICHTLICH: kein `node:*`-Import. Das App-tsconfig+ * kennt keine Node-Typen, und ein Helfer, der sie bräuchte, könnte nicht in+ * `src` neben seinem Test liegen — dieselbe Regel, unter der schon+ * `src/lib/dev-fs-jail.ts` steht. `Uint8Array` reicht: ein Node-`Buffer` IST+ * ein `Uint8Array`.+ */++import { asNumber, asString, isRecord, prop } from '../types/json-guards'++/**+ * Die Chunks eines Requests zu einem String — EINE Dekodierung über alles.+ *+ * Genau das ist der Unterschied zu `body += chunk`: ein `TextDecoder` über+ * die Gesamtbytes sieht ein mehrbyte-Zeichen auch dann, wenn es in zwei+ * Chunks zerfällt.+ */+export function decodeBodyChunks(chunks: readonly Uint8Array[]): string {+ let total = 0+ for (const chunk of chunks) total += chunk.byteLength+ const joined = new Uint8Array(total)+ let at = 0+ for (const chunk of chunks) {+ joined.set(chunk, at)+ at += chunk.byteLength+ }+ return new TextDecoder().decode(joined)+}++/** Was `parseJsonBody` zurückgibt — nie ein Wurf, immer ein Ergebnis. */+export type JsonBodyResult =+ | { ok: true; value: unknown }+ | { ok: false; error: string }++/**+ * `JSON.parse` als Ergebnis statt als Wurf.+ *+ * Ein leerer Körper ist kein JSON und wird auch nicht so behandelt: die+ * Endpunkte, die ohne Felder auskommen, bekommen `undefined` als Wert und+ * kommen damit durch ihre eigenen Pflichtfeld-Prüfungen.+ */+export function parseJsonBody(raw: string): JsonBodyResult {+ if (raw.trim() === '') return { ok: true, value: undefined }+ try {+ return { ok: true, value: JSON.parse(raw) as unknown }+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) }+ }+}++/** Ein String-Feld des Körpers, oder `undefined`. Nichts wird gecastet. */+export function bodyString(body: unknown, ...keys: readonly string[]): string | undefined {+ for (const key of keys) {+ const value = asString(prop(body, key))+ if (value !== undefined) return value+ }+ return undefined+}++/** Ein endliches Zahlenfeld des Körpers, oder `undefined`. */+export function bodyNumber(body: unknown, ...keys: readonly string[]): number | undefined {+ for (const key of keys) {+ const value = asNumber(prop(body, key))+ if (value !== undefined) return value+ }+ return undefined+}++/** Ein Wahrheitsfeld des Körpers — alles Nicht-Boolesche gilt als `false`. */+export function bodyFlag(body: unknown, key: string): boolean {+ return prop(body, key) === true+}++/**+ * Ein Feld, dessen Wert selbst wieder eine Liste von Objekten ist —+ * `/local-api/check-model-sizes` bekommt so seine Dateiliste. Alles, was kein+ * Objekt ist, fällt heraus statt den Aufrufer zu überraschen.+ */+export function bodyRecords(body: unknown, key: string): Record<string, unknown>[] {+ const value = prop(body, key)+ return Array.isArray(value) ? value.filter(isRecord) : []+}diff --git a/src/dev/model-paths.ts b/src/dev/model-paths.tsnew file mode 100644index 00000000..748c5cb2--- /dev/null+++ b/src/dev/model-paths.ts@@ -0,0 +1,134 @@+/**+ * Zielpfade der Modell-Download-Endpunkte des Dev-Servers — mit Käfig.+ *+ * SICHERHEITSBEFUND, deshalb gibt es diese Datei. Vier Endpunkte in+ * `vite.config.ts` bauten einen Pfad aus Feldern des Request-Körpers und+ * schrieben oder lasen dann mit echten fs-Aufrufen darauf:+ *+ * POST /local-api/download-model { subfolder, filename }+ * POST /local-api/resume-download { subfolder, id }+ * POST /local-api/check-model-sizes { files: [{ subfolder, filename }] }+ * POST /local-api/install-custom-node { nodeName, repoUrl }+ *+ * Keiner davon prüfte den Wert. `join(comfyPath, 'models', subfolder)` mit+ *+ * { "url": "http://…/beliebig", "subfolder": "../../../../../..",+ * "filename": ".ssh/authorized_keys" }+ *+ * legt die heruntergeladene Datei irgendwo ausserhalb von ComfyUI ab —+ * `node:path.join` normalisiert `..` klaglos weg. Der Dev-Server ist kein+ * Entwickler-Spielzeug: `setup.sh`/`start.bat` liefern ihn als Laufzeit des+ * Benutzers aus.+ *+ * Die Regel ist dieselbe wie in `src/lib/dev-fs-jail.ts` (dem Port der+ * Rust-Grenze): ein Wurzelverzeichnis, und alles muss lexikalisch darin+ * liegen. Nur die Wurzel ist hier eine andere — nicht der Agenten-Arbeitsordner,+ * sondern die ComfyUI-Installation.+ *+ * REINE STRINGS, ABSICHTLICH: kein `node:path`, kein `node:fs` — dieselbe+ * Regel, unter der `dev-fs-jail.ts` steht, damit das Modul in `src` neben+ * seinem Test liegen kann.+ */++import { containWithin, lexicalNormalize } from '../lib/dev-fs-jail'++/**+ * Wann gilt ein `subfolder` als Pfad in `custom_nodes/` statt in `models/`?+ *+ * Die drei Endpunkte haben das nie gleich entschieden, und das bleibt hier+ * sichtbar statt stillschweigend vereinheitlicht zu werden:+ *+ * 'separator' — `/local-api/download-model`: nur mit Trenner dahinter+ * (`custom_nodes/foo`), so wie es dort stand.+ * 'prefix' — `/local-api/check-model-sizes`: schon der blosse Präfix+ * (`custom_nodes_alt` zählte dort mit).+ * 'never' — `/local-api/resume-download`: kannte den Fall gar nicht,+ * alles landete unter `models/`.+ */+export type CustomNodeRule = 'separator' | 'prefix' | 'never'++function isCustomNodeSubfolder(subfolder: string, rule: CustomNodeRule): boolean {+ if (rule === 'never') return false+ if (rule === 'prefix') return subfolder.startsWith('custom_nodes')+ return /^custom_nodes[/\\]/.test(subfolder)+}++/**+ * Der Zielpfad einer Modell-Datei innerhalb der ComfyUI-Installation.+ *+ * Wirft `JailEscapeError` (aus `dev-fs-jail`), sobald `subfolder` oder+ * `filename` aus der Wurzel herausführen — die Wurzel ist `<comfy>/models`+ * bzw. `<comfy>` für die `custom_nodes`-Zweige.+ */+export function comfyDestPath(+ comfyPath: string,+ subfolder: string,+ filename: string,+ rule: CustomNodeRule,+): string {+ const root = isCustomNodeSubfolder(subfolder, rule)+ ? lexicalNormalize(comfyPath)+ : lexicalNormalize(`${comfyPath}/models`)+ return containWithin(root, `${subfolder}/${filename}`)+}++/**+ * Der Zielpfad von `/local-api/download-model-to-path`.+ *+ * `destDir` ist hier ABSICHTLICH frei: der Endpunkt existiert, um ein GGUF+ * neben eine fremde Installation zu legen (LM Studio, Jan, …), und das+ * Verzeichnis kommt aus `/local-api/detect-model-path`. Was NICHT frei sein+ * muss, ist `filename` — ein `../` darin hat mit dem Zweck nichts zu tun.+ * Der Käfig ist deshalb `destDir` selbst.+ */+export function downloadToPathDest(destDir: string, filename: string): string {+ return containWithin(lexicalNormalize(destDir), filename)+}++/**+ * `basename(url, '.git')` ohne `node:path`: das letzte Segment hinter `/`+ * oder `\`, ohne die Endung `.git`.+ */+export function repoBasename(repoUrl: string): string {+ const last = repoUrl.split(/[/\\]/).filter((s) => s !== '').pop() ?? ''+ return last.endsWith('.git') ? last.slice(0, -4) : last+}++/**+ * Das Zielverzeichnis von `/local-api/install-custom-node`.+ *+ * `nodeName` kam ungeprüft aus dem Körper und wurde an `custom_nodes/`+ * angehängt; `nodeName: '../../..'` liess `git clone` ausserhalb von ComfyUI+ * landen. Fällt `nodeName` weg, entscheidet der letzte Pfadteil der Repo-URL —+ * der ist genauso fremd und wandert durch denselben Käfig.+ */+export function customNodeDir(comfyPath: string, nodeName: string, repoUrl: string): string {+ const root = lexicalNormalize(`${comfyPath}/custom_nodes`)+ const name = nodeName.trim() || repoBasename(repoUrl)+ if (!name) throw new Error('Missing nodeName and unusable repoUrl')+ return containWithin(root, name)+}++/**+ * Die Kandidaten-Verzeichnisse von `/local-api/detect-model-path`, als+ * Segmente RELATIV zum Home-Verzeichnis.+ *+ * Spiegelt die Verzweigung des Rust-Kommandos (`commands/download.rs`+ * `detect_model_path`). Ein unbekannter Anbieter bekommt eine leere Liste und+ * fällt beim Aufrufer in das app-eigene Modellverzeichnis — genau wie dort.+ */+export function modelDirCandidates(provider: string): string[][] {+ const asked = provider.toLowerCase()+ if (asked === 'ollama') return [['.ollama', 'models']]+ if (asked === 'lm studio' || asked === 'lmstudio') {+ return [+ ['.lmstudio', 'models'],+ ['.cache', 'lm-studio', 'models'],+ ['AppData', 'Local', 'LM Studio', 'models'],+ ['.local', 'share', 'lm-studio', 'models'],+ ]+ }+ if (asked === 'jan') return [['.jan', 'models'], ['jan', 'models']]+ if (asked === 'gpt4all') return [['.cache', 'gpt4all']]+ return []+}diff --git a/src/dev/ssrf-policy.ts b/src/dev/ssrf-policy.tsnew file mode 100644index 00000000..897504c6--- /dev/null+++ b/src/dev/ssrf-policy.ts@@ -0,0 +1,214 @@+/**+ * Der SSRF-Wächter der Dev-Proxies (`/local-api/proxy-image`,+ * `/local-api/proxy-download`) — die Entscheidung, ohne das Netz.+ *+ * Diese beiden Endpunkte holen eine URL, die der Aufrufer bestimmt. Im+ * gepackten Desktop-Build geht das durch `validate_public_url` in+ * `src-tauri/src/commands/proxy.rs`; unter `npm run dev` gibt es kein Rust,+ * und dieser Wächter ist die einzige Bremse zwischen einem Markdown-Bild und+ * `http://169.254.169.254/latest/meta-data/`.+ *+ * Warum die Regeln hier stehen und nicht mehr in `vite.config.ts`: sie waren+ * ungetestet, und die IPv6-Hälfte prüfte auf SCHREIBWEISE statt auf Adresse —+ * `lc.startsWith('fe80')`, `/::ffff:(…)$/`. Das trägt genau so lange, wie der+ * Text schon in der komprimierten Kanonform vorliegt:+ *+ * - `0:0:0:0:0:ffff:127.0.0.1` ist eine gültige IPv6-Adresse (node+ * `net.isIP` sagt 6), erreicht nachweislich den Loopback — und keine der+ * alten Regexen greift darauf.+ * - `::7f00:1` (IPv4-kompatibel, `::/96`), `ff02::1` (Multicast) und+ * `fec0::1` (site-local) kamen ebenfalls durch.+ *+ * Über die Proxy-Endpunkte rettete bisher der WHATWG-URL-Parser die Lage: er+ * komprimiert `[0:0:0:0:0:ffff:127.0.0.1]` zu `::ffff:7f00:1`, und DAS traf+ * die Regex. Der Wächter läuft aber auch über DNS-Antworten+ * (`dns.lookup(…, { all: true })`), und dort normalisiert niemand. Deshalb+ * parst dieses Modul die Adresse in ihre acht Gruppen und entscheidet auf+ * Zahlen statt auf Text.+ *+ * `net.isIP` bleibt das Orakel dafür, WAS eine IP-Literal ist — es wird+ * hereingereicht statt nachgebaut, damit die Grenze zwischen „ist eine+ * Adresse" und „ist gesperrt" nicht auseinanderlaufen kann. Deshalb auch kein+ * `node:*`-Import hier: das Modul bleibt rein und liegt neben seinem Test.+ */++/** `net.isIP`: 0 = keine IP-Literal, 4 = IPv4, 6 = IPv6. */+export type IpFamilyFn = (value: string) => number++/** Das Urteil über eine URL, bevor irgendetwas aufgelöst oder geholt wurde. */+export type UrlVerdict =+ /** IP-Literal im Host, geprüft und erlaubt — kein DNS nötig. */+ | { kind: 'allow'; url: URL }+ /** Name im Host: erlaubt, sobald `checkResolved` die Adressen freigibt. */+ | { kind: 'resolve'; url: URL; host: string }+ /** Abgelehnt; `reason` ist die Fehlermeldung, die der Aufrufer wirft. */+ | { kind: 'deny'; reason: string }++/**+ * Eine IPv6-Adresse in ihre acht 16-Bit-Gruppen, oder `null`.+ *+ * Verarbeitet die `::`-Kompression, die angehängte punktierte IPv4-Notation+ * (`::ffff:127.0.0.1`) und eine Zonen-ID (`%en0`). Exportiert, weil der Test+ * die Zerlegung selbst festnageln muss — an ihr hängt jede Regel darunter.+ */+export function parseIpv6Groups(raw: string): number[] | null {+ let text = raw.toLowerCase().replace(/^\[|\]$/g, '')+ const zone = text.indexOf('%')+ if (zone >= 0) text = text.slice(0, zone)++ // Angehängte IPv4 zu zwei Hex-Gruppen machen, dann ist der Rest rein hex.+ const dotted = /^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text)+ if (dotted) {+ const octets = dotted[2].split('.').map(Number)+ if (octets.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return null+ const hi = ((octets[0] << 8) | octets[1]).toString(16)+ const lo = ((octets[2] << 8) | octets[3]).toString(16)+ text = `${dotted[1]}${hi}:${lo}`+ }++ const halves = text.split('::')+ if (halves.length > 2) return null++ const toGroups = (part: string): number[] | null => {+ if (part === '') return []+ const out: number[] = []+ for (const seg of part.split(':')) {+ if (!/^[0-9a-f]{1,4}$/.test(seg)) return null+ out.push(parseInt(seg, 16))+ }+ return out+ }++ const head = toGroups(halves[0])+ if (head === null) return null+ if (halves.length === 1) return head.length === 8 ? head : null++ const tail = toGroups(halves[1])+ if (tail === null) return null+ const fill = 8 - head.length - tail.length+ if (fill < 1) return null+ return [...head, ...new Array<number>(fill).fill(0), ...tail]+}++/** Die letzten 32 Bit einer IPv6-Adresse als punktierte IPv4. */+function embeddedIpv4(groups: readonly number[]): string {+ const [hi, lo] = [groups[6], groups[7]]+ return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`+}++/**+ * IPv4-Sperrliste: alles, was nicht öffentlich routbar ist, plus die+ * Cloud-Metadaten-Adresse. Identisch zur Liste, die vorher in+ * `vite.config.ts` stand.+ */+function isBlockedIpv4(ip: string): boolean {+ const parts = ip.split('.').map(Number)+ if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true+ const [a, b] = parts+ if (a === 0) return true // 0.0.0.0/8 "this host"+ if (a === 10) return true // 10/8 privat+ if (a === 127) return true // Loopback+ if (a === 169 && b === 254) return true // link-local + 169.254.169.254 Cloud-Metadaten+ if (a === 172 && b >= 16 && b <= 31) return true // 172.16/12 privat+ if (a === 192 && b === 168) return true // 192.168/16 privat+ if (a === 100 && b >= 64 && b <= 127) return true // 100.64/10 CGNAT+ if (a >= 224) return true // Multicast + reserviert+ return false+}++/**+ * IPv6-Sperrliste auf den zerlegten Gruppen — Präfixe, keine Schreibweisen.+ *+ * `::/96` wird als Ganzes gesperrt: darin liegen `::`, `::1` und die+ * abgeschafften IPv4-kompatiblen Adressen, und eine öffentlich routbare+ * Adresse gibt es dort nicht.+ */+function isBlockedIpv6(groups: readonly number[]): boolean {+ const zeroPrefix = (n: number): boolean => groups.slice(0, n).every((g) => g === 0)++ // IPv4-mapped ::ffff:0:0/96 — die eingebettete IPv4 entscheidet.+ if (zeroPrefix(5) && groups[5] === 0xffff) return isBlockedIpv4(embeddedIpv4(groups))+ // NAT64 64:ff9b::/96 — komplett gesperrt, wie vorher. Dahinter steckt immer+ // eine IPv4, und der Übersetzer davor ist nichts, dem dieser Dev-Server+ // die Auswahl des Ziels überlassen sollte.+ if (groups[0] === 0x64 && groups[1] === 0xff9b && zeroPrefixFrom(groups, 2, 6)) return true+ if (zeroPrefix(6)) return true // ::/96 — unspecified, Loopback, IPv4-kompatibel+ if ((groups[0] & 0xffc0) === 0xfe80) return true // fe80::/10 link-local+ if ((groups[0] & 0xfe00) === 0xfc00) return true // fc00::/7 ULA+ if ((groups[0] & 0xffc0) === 0xfec0) return true // fec0::/10 site-local (abgeschafft)+ if ((groups[0] & 0xff00) === 0xff00) return true // ff00::/8 Multicast+ return false+}++/** Sind die Gruppen `from` bis `to` (exklusiv) alle null? */+function zeroPrefixFrom(groups: readonly number[], from: number, to: number): boolean {+ for (let i = from; i < to; i++) if (groups[i] !== 0) return false+ return true+}++export interface SsrfPolicy {+ /** True für jede Adresse, die der Dev-Server nicht anfassen darf. */+ isBlockedIp(ip: string): boolean+ /** Urteil über eine vom Aufrufer gelieferte URL, ohne Netzzugriff. */+ checkUrl(urlStr: string): UrlVerdict+ /** Urteil über die DNS-Antwort zu einem Namen aus `checkUrl`. */+ checkResolved(addresses: readonly string[]): { ok: true } | { ok: false; reason: string }+}++/**+ * Der Wächter, mit `net.isIP` als hereingereichtem Orakel.+ *+ * `vite.config.ts` ruft ihn mit `(v) => net.isIP(v)` auf; der Test benutzt+ * dieselbe Funktion, damit „was ist eine IP-Literal" auf beiden Seiten+ * dieselbe Antwort gibt.+ */+export function createSsrfPolicy(ipFamily: IpFamilyFn): SsrfPolicy {+ function isBlockedIp(ip: string): boolean {+ const family = ipFamily(ip)+ if (family === 4) return isBlockedIpv4(ip)+ if (family === 6) {+ const groups = parseIpv6Groups(ip)+ // `net.isIP` sagt 6, aber die Zerlegung scheitert: dann lieber sperren,+ // als eine Adresse durchzulassen, die niemand gelesen hat.+ return groups === null ? true : isBlockedIpv6(groups)+ }+ return false // keine IP-Literal — der Aufrufer löst auf und prüft erneut+ }++ function checkUrl(urlStr: string): UrlVerdict {+ let url: URL+ try {+ url = new URL(urlStr)+ } catch {+ return { kind: 'deny', reason: 'invalid url' }+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ return { kind: 'deny', reason: 'scheme not allowed' }+ }+ const host = url.hostname.replace(/^\[|\]$/g, '')+ if (!host) return { kind: 'deny', reason: 'no host' }+ if (host === 'localhost' || host.toLowerCase().endsWith('.localhost')) {+ return { kind: 'deny', reason: 'blocked host' }+ }+ // Rein dezimale / 0x-hexadezimale Hosts sind inet_aton-SSRF-Schreibweisen.+ if (/^\d+$/.test(host) || /^0x[0-9a-f]+$/i.test(host)) {+ return { kind: 'deny', reason: 'blocked numeric host' }+ }+ if (ipFamily(host) !== 0) {+ return isBlockedIp(host) ? { kind: 'deny', reason: 'blocked ip' } : { kind: 'allow', url }+ }+ return { kind: 'resolve', url, host }+ }++ function checkResolved(+ addresses: readonly string[],+ ): { ok: true } | { ok: false; reason: string } {+ if (addresses.length === 0) return { ok: false, reason: 'dns empty' }+ for (const address of addresses) {+ if (isBlockedIp(address)) return { ok: false, reason: 'blocked resolved ip' }+ }+ return { ok: true }+ }++ return { isBlockedIp, checkUrl, checkResolved }+}diff --git a/src/dev/web-search-parse.ts b/src/dev/web-search-parse.tsnew file mode 100644index 00000000..5371a92f--- /dev/null+++ b/src/dev/web-search-parse.ts@@ -0,0 +1,148 @@+/**+ * Die Antwort-Auswertung von `/local-api/web-search` — fünf fremde Formate,+ * ohne Netz.+ *+ * Der Endpunkt versucht der Reihe nach SearXNG, Brave, Tavily, DuckDuckGo und+ * Wikipedia und nimmt die erste Ebene, die etwas liefert. Jede dieser fünf+ * Antworten ist FREMD: SearXNG läuft in einem Container des Benutzers, Brave+ * und Tavily sind Fremd-APIs, und die DuckDuckGo-Ebene liest HTML, das sich+ * ohne Ankündigung ändern darf. Vorher wurde jede davon mit `(r: any) =>`+ * durchgereicht — also ungeprüft — und die daraus gebauten Ergebnisse gingen+ * direkt an das Modell.+ *+ * Hier ist alles `unknown` plus Prüfung an der Grenze; ein Eintrag ohne+ * brauchbaren Titel oder URL fällt heraus, statt als `undefined` weiterzureisen.+ *+ * REIN, ABSICHTLICH: kein `node:*`-Import — das Modul liegt neben seinem Test.+ */++import { asString, isRecord, prop, propPath } from '../types/json-guards'++/** Ein Treffer, wie ihn der Endpunkt an das Modell zurückgibt. */+export interface WebSearchResult {+ title: string+ url: string+ snippet: string+}++/** Ein Feld als String, oder `''` — die Form, die der Endpunkt versprochen hat. */+function text(record: Record<string, unknown>, key: string): string {+ return asString(record[key]) ?? ''+}++/** Die Liste unter `keys` als Datensätze, oder `[]`. */+function listAt(data: unknown, ...keys: readonly string[]): Record<string, unknown>[] {+ const value = keys.length === 1 ? prop(data, keys[0]) : propPath(data, ...keys)+ return Array.isArray(value) ? value.filter(isRecord) : []+}++/**+ * Einträge ohne Titel UND ohne URL sind für den Aufrufer wertlos — ein Modell,+ * das eine leere URL zitiert bekommt, halluziniert darauf weiter.+ */+function usable(result: WebSearchResult): boolean {+ return result.title !== '' || result.url !== ''+}++/** SearXNG (`/search?format=json`): `{ results: [{ title, url, content }] }`. */+export function parseSearxngResults(data: unknown, max: number): WebSearchResult[] {+ return listAt(data, 'results')+ .slice(0, max)+ .map((r) => ({ title: text(r, 'title'), url: text(r, 'url'), snippet: text(r, 'content') }))+ .filter(usable)+}++/** Brave: `{ web: { results: [{ title, url, description }] } }`. */+export function parseBraveResults(data: unknown, max: number): WebSearchResult[] {+ return listAt(data, 'web', 'results')+ .slice(0, max)+ .map((r) => ({ title: text(r, 'title'), url: text(r, 'url'), snippet: text(r, 'description') }))+ .filter(usable)+}++/** Tavily: `{ results: [{ title, url, content }] }`. */+export function parseTavilyResults(data: unknown, max: number): WebSearchResult[] {+ return listAt(data, 'results')+ .slice(0, max)+ .map((r) => ({ title: text(r, 'title'), url: text(r, 'url'), snippet: text(r, 'content') }))+ .filter(usable)+}++/**+ * Wikipedia (`action=query&list=search`): `{ query: { search: [{ title, snippet }] } }`.+ *+ * Die URL wird aus dem Titel gebaut. Vorher stand dort `r.title.replace(…)`+ * hinter einem `title: r.title || ''` — ein Eintrag ohne Titel warf also eine+ * TypeError mitten in der letzten Ebene der Suchkette und machte aus „keine+ * Treffer" ein „alle Ebenen fehlgeschlagen". Hier fällt er einfach heraus.+ */+export function parseWikipediaResults(data: unknown, max: number): WebSearchResult[] {+ return listAt(data, 'query', 'search')+ .slice(0, max)+ .map((r) => {+ const title = text(r, 'title')+ return {+ title,+ url: title === ''+ ? ''+ : `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`,+ snippet: text(r, 'snippet').replace(/<[^>]*>/g, ''),+ }+ })+ .filter((r) => r.url !== '')+}++/** HTML-Entities, die in den DDG-Treffern vorkommen. */+function decodeEntities(value: string): string {+ return value+ .replace(/<[^>]*>/g, '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/'/g, "'")+ .replace(/"/g, '"')+}++/**+ * DuckDuckGos HTML-Endpunkt (`html.duckduckgo.com/html/`).+ *+ * DDG verpackt die Ziel-URL in eine eigene Weiterleitung+ * (`//duckduckgo.com/l/?uddg=<encoded>`); die wird hier ausgepackt, damit nicht+ * jeder Treffer über DDG zurückzeigt. Nur `http(s)`-Ziele werden übernommen —+ * ein `javascript:`- oder `data:`-Ziel aus fremdem HTML hat in der Antwort an+ * das Modell nichts verloren.+ */+export function parseDdgHtmlResults(html: string, max: number): WebSearchResult[] {+ const linkRegex = /<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi+ const snippetRegex = /<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi++ const links: { title: string; url: string }[] = []+ let linkMatch: RegExpExecArray | null+ while ((linkMatch = linkRegex.exec(html)) !== null) {+ let url = linkMatch[1]+ if (url.includes('uddg=')) {+ const uddg = url.split('uddg=')[1]?.split('&')[0]+ if (uddg) {+ try {+ url = decodeURIComponent(uddg)+ } catch {+ continue // kaputte Prozent-Kodierung → Treffer verwerfen+ }+ }+ }+ const title = decodeEntities(linkMatch[2]).trim()+ if (title && /^https?:\/\//i.test(url)) links.push({ title, url })+ }++ const snippets: string[] = []+ let snippetMatch: RegExpExecArray | null+ while ((snippetMatch = snippetRegex.exec(html)) !== null) {+ snippets.push(decodeEntities(snippetMatch[1]).replace(/\s+/g, ' ').trim())+ }++ const results: WebSearchResult[] = []+ for (let i = 0; i < Math.min(links.length, max); i++) {+ results.push({ title: links[i].title, url: links[i].url, snippet: snippets[i] ?? '' })+ }+ return results+}diff --git a/src/lib/__tests__/app-identity.test.ts b/src/lib/__tests__/app-identity.test.tsindex d011fe43..8694e04f 100644--- a/src/lib/__tests__/app-identity.test.ts+++ b/src/lib/__tests__/app-identity.test.ts@@ -60,18 +60,41 @@ describe('Verzeichnisnamen dieses Builds', () => {// mit `lu-labs` an, und ein neu hingeschriebenes Literal wandert an// app-identity.ts vorbei. vite.config.ts bedient den `npm run dev`-Pfad// und schreibt mit echten Node-fs-Aufrufen auf die Platte.- const vite = readFileSync(resolve(process.cwd(), 'vite.config.ts'), 'utf8')- const jail = readFileSync(resolve(process.cwd(), 'src/lib/dev-fs-jail.ts'), 'utf8')- for (const name of ['lu-labs', 'locally-uncensored', 'Locally Uncensored', 'agent-workspace']) {- for (const quelle of [- ['vite.config.ts', vite],- ['src/lib/dev-fs-jail.ts', jail],- ] as const) {- expect(quelle[1], `${quelle[0]}: '${name}' als Pfadbestandteil hartkodiert`)- .not.toContain(`'${name}'`)- expect(quelle[1], `${quelle[0]}: '${name}/' als Pfadbestandteil hartkodiert`)- .not.toContain(`/${name}/`)+ //+ // Die Prüfung WANDERT MIT dem Code: Teile des Dev-Servers liegen inzwischen+ // in src/dev/ (herausgelöst, damit sie testbar sind). Wäre hier nur+ // vite.config.ts genannt, hätte das Verschieben das Loch nur umgezogen —+ // deshalb wird das Verzeichnis gelesen, nicht eine Dateiliste gepflegt.+ for (const [name, text] of devServerSources()) {+ for (const echt of ['lu-labs', 'locally-uncensored', 'Locally Uncensored', 'agent-workspace']) {+ expect(text, `${name}: '${echt}' als Pfadbestandteil hartkodiert`)+ .not.toContain(`'${echt}'`)+ expect(text, `${name}: '${echt}/' als Pfadbestandteil hartkodiert`)+ .not.toContain(`/${echt}/`)}}})++ it('deckt alle Dev-Server-Quellen ab, auch neu hinzugekommene', () => {+ // Ohne diese Zusicherung könnte die Prüfung oben still auf null Dateien+ // laufen — ein grüner Test, der nichts liest.+ const namen = devServerSources().map(([name]) => name)+ expect(namen).toContain('vite.config.ts')+ expect(namen).toContain('src/lib/dev-fs-jail.ts')+ expect(namen.filter((n) => n.startsWith('src/dev/')).length).toBeGreaterThan(0)+ })})++/**+ * Jede Quelldatei, die den `npm run dev`-Pfad bedient: die vite-Konfiguration,+ * der Pfad-Käfig und alles, was aus der Konfiguration nach `src/dev/`+ * herausgelöst wurde (ohne die Tests dort).+ */+function devServerSources(): [string, string][] {+ const root = process.cwd()+ const dateien = ['vite.config.ts', 'src/lib/dev-fs-jail.ts']+ for (const entry of readdirSync(resolve(root, 'src/dev'), { withFileTypes: true })) {+ if (entry.isFile() && entry.name.endsWith('.ts')) dateien.push(`src/dev/${entry.name}`)+ }+ return dateien.map((name) => [name, readFileSync(resolve(root, name), 'utf8')])+}diff --git a/vite.config.ts b/vite.config.tsindex 4b166471..8cf424e1 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,9 +1,21 @@import { defineConfig, parseAst, type Plugin } from 'vite'+import type { Connect } from 'vite'import react from '@vitejs/plugin-react'import tailwindcss from '@tailwindcss/vite'-import { spawn, execSync, type ChildProcess } from 'child_process'-import { existsSync, readdirSync, createWriteStream, mkdirSync, statSync, type Dirent } from 'fs'+import { spawn, execSync, execFileSync, type ChildProcess } from 'child_process'+import {+ existsSync,+ readdirSync,+ createWriteStream,+ mkdirSync,+ readFileSync,+ statSync,+ statfsSync,+ writeFileSync,+ type Dirent,+} from 'fs'import { resolve, join, basename, isAbsolute } from 'path'+import type { IncomingMessage, ServerResponse } from 'http'import https from 'https'import http from 'http'import { config } from 'dotenv'@@ -18,6 +30,39 @@ import { devResolveWithinJail, effectiveByteCap, JailEscapeError } from './src/l// src-tauri/src/app_identity.rs.import { AGENT_WORKSPACE_DIR, APP_CONFIG_DIR } from './src/lib/app-identity'import { postContentTypeAllowed, postContentTypeError } from './src/lib/local-api-guard'+// Die herausgelösten, getesteten Teile dieses Dev-Servers. Sie liegen unter+// src/dev/, damit vitest sie sieht; alles dort ist rein (keine node:*-Importe),+// weil das App-tsconfig keine Node-Typen kennt — dieselbe Regel wie bei+// src/lib/dev-fs-jail.ts.+import {+ bodyFlag,+ bodyNumber,+ bodyRecords,+ bodyString,+ decodeBodyChunks,+ parseJsonBody,+} from './src/dev/http-body'+import { createSsrfPolicy } from './src/dev/ssrf-policy'+import {+ applyConsoleRemovals,+ collectConsoleRemovals,+ isStrippableModule,+} from './src/dev/console-strip'+import {+ comfyDestPath,+ customNodeDir,+ downloadToPathDest,+ modelDirCandidates,+} from './src/dev/model-paths'+import {+ parseBraveResults,+ parseDdgHtmlResults,+ parseSearxngResults,+ parseTavilyResults,+ parseWikipediaResults,+ type WebSearchResult,+} from './src/dev/web-search-parse'+import { asNumber, asString, errorText, prop } from './src/types/json-guards'// The port the dev server binds and the only port the /local-api origin check// treats as canonical. Kept next to the guard it feeds so the two can't drift@@ -34,66 +79,104 @@ const DEV_PORT = 5273// (src-tauri/src/commands/proxy.rs); this is the parity guard for the// `npm run dev` / web build (konata's SSH-tunnel path). Best-effort against// DNS-rebind — this is a dev server, not the production trust boundary.-function isBlockedIp(ip: string): boolean {- const v = net.isIP(ip)- if (v === 4) {- const p = ip.split('.').map(Number)- if (p.length !== 4 || p.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true- const [a, b] = p- if (a === 0) return true // 0.0.0.0/8 "this host"- if (a === 10) return true // 10/8 private- if (a === 127) return true // loopback- if (a === 169 && b === 254) return true // link-local + 169.254.169.254 cloud metadata- if (a === 172 && b >= 16 && b <= 31) return true // 172.16/12 private- if (a === 192 && b === 168) return true // 192.168/16 private- if (a === 100 && b >= 64 && b <= 127) return true // 100.64/10 CGNAT- if (a >= 224) return true // multicast + reserved- return false- }- if (v === 6) {- const lc = ip.toLowerCase().replace(/^\[|\]$/g, '')- if (lc === '::1' || lc === '::') return true // loopback / unspecified- if (lc.startsWith('fe80')) return true // link-local- if (lc.startsWith('fc') || lc.startsWith('fd')) return true // ULA fc00::/7- if (lc.startsWith('64:ff9b:')) return true // NAT64 (embeds an IPv4 — block)- // IPv4-mapped IPv6 in BOTH the dotted (::ffff:127.0.0.1) and the hex- // (::ffff:7f00:1) forms — decode the embedded IPv4 and re-check it.- const dotted = lc.match(/::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)- if (dotted) return isBlockedIp(dotted[1])- const hex = lc.match(/::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/)- if (hex) {- const hi = parseInt(hex[1], 16)- const lo = parseInt(hex[2], 16)- return isBlockedIp(`${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`)+//+// The rule table itself now lives in src/dev/ssrf-policy.ts, next to its test:+// it used to decide on the SPELLING of an IPv6 address (`startsWith('fe80')`,+// `/::ffff:…$/`), which only holds while the text is already in canonical+// compressed form. `net.isIP` stays the oracle for "is this an IP literal at+// all" and is handed in rather than reimplemented.+const ssrf = createSsrfPolicy((value) => net.isIP(value))++async function assertPublicUrl(urlStr: string): Promise<URL> {+ const verdict = ssrf.checkUrl(urlStr)+ if (verdict.kind === 'deny') throw new Error(verdict.reason)+ if (verdict.kind === 'allow') return verdict.url+ const addrs = await dns.promises.lookup(verdict.host, { all: true })+ const resolved = ssrf.checkResolved(addrs.map((a) => a.address))+ if (!resolved.ok) throw new Error(resolved.reason)+ return verdict.url+}++// ── Request bodies ──────────────────────────────────────────────+// Every /local-api POST handler used to open with the same three lines:+//+// let body = ''+// req.on('data', (c: any) => { body += c })+// req.on('end', () => { const { path } = JSON.parse(body) … })+//+// Twenty copies, and two defects copied twenty times with them: `body += c`+// decodes each chunk on its own (a multi-byte character split across a chunk+// boundary arrives as U+FFFD), and three of the handlers called JSON.parse+// with no try — a throw inside an 'end' listener happens long after the+// middleware returned, so nothing catches it and a single malformed POST takes+// the whole `npm run dev` process down with it. Both fixes live in+// src/dev/http-body.ts, next to their test; this is the one call site.+type JsonBodyHandler = (body: unknown) => void++function withJsonBody(req: IncomingMessage, res: ServerResponse, handle: JsonBodyHandler): void {+ const chunks: Buffer[] = []+ req.on('data', (chunk: Buffer) => { chunks.push(chunk) })+ req.on('end', () => {+ const parsed = parseJsonBody(decodeBodyChunks(chunks))+ if (!parsed.ok) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: `Invalid JSON body: ${parsed.error}` }))+ return}- return false- }- return false // not an IP literal — caller resolves DNS and re-checks+ try {+ handle(parsed.value)+ } catch (err) {+ // Same reason as above: we are past the middleware, nobody else is left+ // to catch this. A 400 beats a dead dev server.+ res.writeHead(err instanceof JailEscapeError ? 403 : 400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: errorText(err) || String(err) }))+ }+ })}-async function assertPublicUrl(urlStr: string): Promise<URL> {- let u: URL- try {- u = new URL(urlStr)- } catch {- throw new Error('invalid url')- }- if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('scheme not allowed')- const host = u.hostname.replace(/^\[|\]$/g, '')- if (!host) throw new Error('no host')- if (host === 'localhost' || host.toLowerCase().endsWith('.localhost')) throw new Error('blocked host')- // Reject all-digit decimal / 0x-hex integer hosts (inet_aton SSRF encodings).- if (/^\d+$/.test(host) || /^0x[0-9a-f]+$/i.test(host)) throw new Error('blocked numeric host')- if (net.isIP(host)) {- if (isBlockedIp(host)) throw new Error('blocked ip')- return u- }- const addrs = await dns.promises.lookup(host, { all: true })- if (!addrs.length) throw new Error('dns empty')- for (const a of addrs) {- if (isBlockedIp(a.address)) throw new Error('blocked resolved ip')- }- return u+/** POST-only endpoints answer 405 to everything else, as they always did. */+function requirePost(req: IncomingMessage, res: ServerResponse): boolean {+ if (req.method === 'POST') return true+ res.writeHead(405)+ res.end()+ return false+}++/** One JSON response, the shape every handler here writes. */+function sendJson(res: ServerResponse, status: number, payload: unknown): void {+ res.writeHead(status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(payload))+}++/**+ * The error answer for a handler that resolves a caller-supplied path: a jail+ * escape is a 403 and says so, everything else keeps the 400 these endpoints+ * always answered with.+ */+function failRequest(res: ServerResponse, err: unknown): void {+ sendJson(res, err instanceof JailEscapeError ? 403 : 400, { error: errorText(err) || String(err) })+}++/** One grep hit of /local-api/fs-search: a line number and the (clipped) line. */+interface FsSearchMatch {+ line: number+ text: string+}++/** One file of /local-api/fs-search with the matches found in it. */+interface FsSearchHit {+ file: string+ matches: FsSearchMatch[]+}++/** One entry of the dev download manager, as /local-api/download-progress reports it. */+interface DownloadState {+ progress: number+ total: number+ speed: number+ filename: string+ status: 'connecting' | 'downloading' | 'paused' | 'complete' | 'error'+ error?: string}// Load .env file from project root@@ -118,109 +201,25 @@ config({ path: resolve(__dirname, '.env') })// (`build.sourcemap` unset → default false), so returning transformed code// without a map is safe; the guard below also bails when a map is requested.function stripConsolePlugin(): Plugin {- const TARGETS = new Set(['log', 'info', 'debug'])- const STRIPPABLE = /\.[cm]?[jt]sx?$/-- // True iff `node` is a `console.log(...)` / `.info` / `.debug` CallExpression.- // Matches the bare `console.<m>(…)` member call only — `foo.console.log`,- // `myLogger.log`, and re-assigned `const x = console.log` are left alone.- const isStrippableConsoleCall = (node: any): boolean => {- if (!node || node.type !== 'CallExpression') return false- const callee = node.callee- if (!callee || callee.type !== 'MemberExpression' || callee.computed) return false- const obj = callee.object- const prop = callee.property- return (- obj?.type === 'Identifier' &&- obj.name === 'console' &&- prop?.type === 'Identifier' &&- TARGETS.has(prop.name)- )- }-return {name: 'lu-strip-console',apply: 'build',transform(code, id) {- if (id.includes('\0')) return null // virtual module- if (id.includes('node_modules')) return null- const clean = id.split('?')[0]- // The structured logger (src/lib/logger.ts) is the ONE sanctioned console- // sink: in production it serialises every event to a single-line JSON- // object on stdout via `console.log`. That call is a brace-less- // `else console.log(line)` which this plugin would neutralise to `void 0`,- // silencing every log.info/log.debug in prod and defeating the logger's- // whole purpose. Leave the logger module untouched, like node_modules.- if (/[\\/]lib[\\/]logger\.[cm]?[jt]sx?$/.test(clean)) return null- if (!STRIPPABLE.test(clean)) return null- if (!code.includes('console.')) return null-- let ast: any+ if (!isStrippableModule(id, code)) return null++ let ast: unknowntry {ast = parseAst(code, { sourceType: 'module' })} catch {return null // let the real parse step report syntax errors}- // Containers where an ExpressionStatement can simply be deleted with- // no syntactic fallout (its siblings or the empty block remain valid).- const BLOCK_LIKE = new Set(['BlockStatement', 'Program', 'StaticBlock'])-- // Collect [start,end) byte ranges of every strippable call.- // • Whole-statement call inside a block → delete the statement.- // • Whole-statement call that is the *single* (brace-less) body of an- // if/else/for/while/do/with/label arm → replace the CALL with- // `void 0` so the arm keeps a statement (`else void 0;`). Deleting- // it would orphan the `else`/`for(...)` and break parsing — this- // was the logger.ts `if (…) console.error(x)\nelse console.log(y)`- // case that the naive version corrupted.- // • Call used as a sub-expression (`a && console.log(b)`, a ternary- // arm, an arg) → replace the CALL with `void 0`.- const removals: Array<{ start: number; end: number; replacement: string }> = []-- const visit = (node: any, parent: any, grandparent: any, parentKey: string | null): void => {- if (!node || typeof node.type !== 'string') return- if (isStrippableConsoleCall(node)) {- const stmt = parent && parent.type === 'ExpressionStatement' && parent.expression === node- ? parent- : null- if (stmt && grandparent && BLOCK_LIKE.has(grandparent.type)) {- // Safe to drop the whole statement (incl. its trailing `;`).- removals.push({ start: stmt.start, end: stmt.end, replacement: '' })- } else if (stmt && grandparent && grandparent.type === 'SwitchCase' && parentKey === 'consequent') {- removals.push({ start: stmt.start, end: stmt.end, replacement: '' })- } else {- // Brace-less control-flow arm OR a sub-expression: neutralise the- // call but keep a valid expression in its place.- removals.push({ start: node.start, end: node.end, replacement: 'void 0' })- }- return // don't descend into the args of a call we're deleting- }- for (const key in node) {- if (key === 'start' || key === 'end' || key === 'parent') continue- const child = (node as any)[key]- if (Array.isArray(child)) {- for (const c of child) {- if (c && typeof c.type === 'string') visit(c, node, parent, key)- }- } else if (child && typeof child.type === 'string') {- visit(child, node, parent, key)- }- }- }- visit(ast, null, null, null)-+ const removals = collectConsoleRemovals(ast)if (removals.length === 0) return null- // Apply back-to-front so earlier offsets stay valid.- removals.sort((a, b) => b.start - a.start)- let out = code- for (const r of removals) {- out = out.slice(0, r.start) + r.replacement + out.slice(r.end)- }// Sourcemaps are off for prod here; null map signals "I rewrote the// text, don't trust a passthrough map" without fabricating one.- return { code: out, map: null }+ return { code: applyConsoleRemovals(code, removals), map: null }},}}@@ -374,7 +373,9 @@ function comfyLauncher(): Plugin {name: 'comfy-launcher',configureServer(server) {// --- Security Middleware ---- server.middlewares.use('/local-api', (req, res, next) => {+ // Vites eigener Middleware-Typ statt einer geratenen Signatur: `next`+ // ist hier Pflicht, weil dieser Wächter durchreicht statt zu antworten.+ const localApiGuard: Connect.NextHandleFunction = (req, res, next) => {// Exclude GET proxy-image/download from strict header checks (used in <img> tags and simple fetches)if (req.method === 'GET' && (req.url?.startsWith('/proxy-image') || req.url?.startsWith('/proxy-download'))) {return next();@@ -432,7 +433,8 @@ function comfyLauncher(): Plugin {}next();- });+ }+ server.middlewares.use('/local-api', localApiGuard);// Auto-start Ollama when dev server starts (best-effort, NEVER fatal:// a from-source dev run may not have Ollama installed at all — #63@@ -670,11 +672,12 @@ function comfyLauncher(): Plugin {'/local-api/stop-tunnel','/local-api/tunnel-status',]+ const remoteDevModeStub: Connect.SimpleHandleFunction = (_req, res) => {+ res.writeHead(501, { 'Content-Type': 'application/json' })+ res.end(REMOTE_DEV_MODE_BODY)+ }for (const path of remoteStubPaths) {- server.middlewares.use(path, (_req, res) => {- res.writeHead(501, { 'Content-Type': 'application/json' })- res.end(REMOTE_DEV_MODE_BODY)- })+ server.middlewares.use(path, remoteDevModeStub)}// API: Manual start@@ -711,7 +714,7 @@ function comfyLauncher(): Plugin {})// ─── Model Download Manager ───- const activeDownloads = new Map<string, { progress: number; total: number; speed: number; filename: string; status: string; error?: string }>()+ const activeDownloads = new Map<string, DownloadState>()function downloadFile(url: string, destPath: string, id: string): Promise<void> {return new Promise((promiseResolve, promiseReject) => {@@ -793,12 +796,13 @@ function comfyLauncher(): Plugin {// API: Start a model downloadserver.middlewares.use('/local-api/download-model', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { url, subfolder, filename, expectedBytes } = JSON.parse(body)+ const url = bodyString(body, 'url')+ const subfolder = bodyString(body, 'subfolder')+ const filename = bodyString(body, 'filename')+ const expectedBytes = bodyNumber(body, 'expectedBytes')if (!url || !subfolder || !filename) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Missing url, subfolder, or filename' }))@@ -810,10 +814,12 @@ function comfyLauncher(): Plugin {res.end(JSON.stringify({ error: 'ComfyUI not found' }))return}- const destDir = subfolder.startsWith('custom_nodes/') || subfolder.startsWith('custom_nodes\\')- ? join(comfyPath, subfolder)- : join(comfyPath, 'models', subfolder)- const destPath = join(destDir, filename)+ // SICHERHEITSBEFUND: `subfolder`/`filename` gingen ungeprüft in+ // `join(comfyPath, 'models', …)` und dann in einen echten Schreibvorgang.+ // Der Käfig liegt jetzt in src/dev/model-paths.ts; ein Ausbruch wirft+ // JailEscapeError und wird unten als 403 beantwortet.+ const destPath = comfyDestPath(comfyPath, subfolder, filename, 'separator')+ const destDir = dirname(destPath)if (existsSync(destPath)) {// Validate file size if expectedBytes provided (catch partial downloads)@@ -846,20 +852,19 @@ function comfyLauncher(): Plugin {return}console.log(`[Download] Starting: ${filename} → ${destDir}`)- downloadFile(url, destPath, id).catch(err => console.error(`[Download] Failed: ${err.message}`))+ downloadFile(url, destPath, id).catch(err => console.error(`[Download] Failed: ${errorText(err)}`))res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'started', id }))} catch (err) {- res.writeHead(400, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: String(err) }))+ failRequest(res, err)}})})// API: Download progressserver.middlewares.use('/local-api/download-progress', (_req, res) => {- const downloads: Record<string, any> = {}+ const downloads: Record<string, DownloadState> = {}for (const [id, info] of activeDownloads.entries()) {downloads[id] = infoif (info.status === 'complete' || info.status === 'error') {@@ -872,35 +877,18 @@ function comfyLauncher(): Plugin {// API: Detect model path for non-Ollama providers (LM Studio, etc.)server.middlewares.use('/local-api/detect-model-path', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { provider } = JSON.parse(body)const home = os.homedir()// Which backend was asked about used to be read and then thrown// away: every provider got LM Studio's directory back, including- // Ollama and the built-in engine. Mirrors the dispatch in the Rust- // command (src-tauri/src/commands/download.rs detect_model_path)- // for the backends with a conventional managed dir; everything- // else falls through to the LU fallback dir below, as there.- const asked = String(provider ?? '').toLowerCase()- const candidates =- asked === 'ollama'- ? [join(home, '.ollama', 'models')]- : asked === 'lm studio' || asked === 'lmstudio'- ? [- join(home, '.lmstudio', 'models'),- join(home, '.cache', 'lm-studio', 'models'),- join(home, 'AppData', 'Local', 'LM Studio', 'models'),- join(home, '.local', 'share', 'lm-studio', 'models'),- ]- : asked === 'jan'- ? [join(home, '.jan', 'models'), join(home, 'jan', 'models')]- : asked === 'gpt4all'- ? [join(home, '.cache', 'gpt4all')]- : []+ // Ollama and the built-in engine. The dispatch (a mirror of+ // src-tauri/src/commands/download.rs detect_model_path) now lives in+ // src/dev/model-paths.ts next to its test; everything it does not+ // know falls through to the LU fallback dir below, as there.+ const candidates = modelDirCandidates(bodyString(body, 'provider') ?? '')+ .map((segments) => join(home, ...segments))const found = candidates.find((p) => existsSync(p))if (found) {res.writeHead(200, { 'Content-Type': 'application/json' })@@ -921,15 +909,10 @@ function comfyLauncher(): Plugin {// API: Check model file sizes (for partial download detection)server.middlewares.use('/local-api/check-model-sizes', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { files } = JSON.parse(body)- const { existsSync, statSync } = require('fs')- const { join } = require('path')- const home = require('os').homedir()+ const home = os.homedir()// Prefer the ComfyUI path the app actually persisted (matches the// Rust backend); only then fall back to common defaults. Without// this the dev stub guessed wrong for non-default installs and@@ -939,8 +922,9 @@ function comfyLauncher(): Plugin {try {const cfgPath = join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), APP_CONFIG_DIR, 'config.json')if (existsSync(cfgPath)) {- const cfg = JSON.parse(require('fs').readFileSync(cfgPath, 'utf8'))- if (cfg.comfyui_path && existsSync(cfg.comfyui_path)) comfyPath = cfg.comfyui_path+ const cfg = parseJsonBody(readFileSync(cfgPath, 'utf8'))+ const persisted = cfg.ok ? asString(prop(cfg.value, 'comfyui_path')) : undefined+ if (persisted && existsSync(persisted)) comfyPath = persisted}} catch { /* ignore — fall through to candidates */ }if (!comfyPath) {@@ -951,54 +935,59 @@ function comfyLauncher(): Plugin {]comfyPath = candidates.find(p => existsSync(p)) || join(home, 'ComfyUI')}- const results = (files as any[]).map((f: any) => {- const subfolder = f.subfolder || ''- const dir = subfolder.startsWith('custom_nodes')- ? join(comfyPath, subfolder)- : join(comfyPath, 'models', subfolder)- const filePath = join(dir, f.filename)+ const results = bodyRecords(body, 'files').map((f) => {+ const filename = asString(f.filename) ?? ''+ const subfolder = asString(f.subfolder) ?? ''+ const expectedBytes = asNumber(f.expectedBytes) ?? 0+ // SICHERHEITSBEFUND: `subfolder`/`filename` gingen ungeprüft in+ // `join(comfyPath, …)`. Ein Ausbruch beantwortet der Eintrag jetzt+ // mit `exists: false`, statt fremde Dateien abzutasten.+ let filePath: string+ try {+ filePath = comfyDestPath(comfyPath, subfolder, filename, 'prefix')+ } catch {+ return { filename, exists: false, actualBytes: 0, complete: false }+ }if (existsSync(filePath)) {const actual = statSync(filePath).size- const threshold = f.expectedBytes > 0 ? f.expectedBytes * 0.9 : 0- return { filename: f.filename, exists: true, actualBytes: actual, complete: f.expectedBytes === 0 || actual >= threshold }+ const threshold = expectedBytes > 0 ? expectedBytes * 0.9 : 0+ return { filename, exists: true, actualBytes: actual, complete: expectedBytes === 0 || actual >= threshold }}- return { filename: f.filename, exists: false, actualBytes: 0, complete: false }+ return { filename, exists: false, actualBytes: 0, complete: false }})res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify(results))} catch (err) {res.writeHead(500, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: String(err) }))+ res.end(JSON.stringify({ error: errorText(err) || String(err) }))}})})// API: Download model to a specific path (for HuggingFace GGUF → LM Studio etc.)server.middlewares.use('/local-api/download-model-to-path', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const parsed = JSON.parse(body)- const url = parsed.url- const destDir = parsed.destDir || parsed.dest_dir- const filename = parsed.filename+ const url = bodyString(body, 'url')+ const destDir = bodyString(body, 'destDir', 'dest_dir')+ const filename = bodyString(body, 'filename')if (!url || !destDir || !filename) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Missing url, destDir, or filename' }))return}- const { existsSync, mkdirSync, statSync: statSyncFs } = require('fs')- const { join } = require('path')- const expectedBytes = parsed.expectedBytes+ const expectedBytes = bodyNumber(body, 'expectedBytes')+ // `destDir` ist hier absichtlich frei (das ist der Zweck des+ // Endpunkts: neben eine fremde Installation legen). `filename` ist+ // es nicht mehr — ein `../` darin wird jetzt abgelehnt.+ const destPath = downloadToPathDest(destDir, filename)if (!existsSync(destDir)) mkdirSync(destDir, { recursive: true })- const destPath = join(destDir, filename)if (existsSync(destPath)) {let fileComplete = trueif (expectedBytes && expectedBytes > 0) {try {- const actual = statSyncFs(destPath).size+ const actual = statSync(destPath).sizefileComplete = actual >= expectedBytes * 0.9if (!fileComplete) console.log(`[Download] ${filename} incomplete: ${actual} vs ${expectedBytes} expected`)} catch { fileComplete = true }@@ -1017,24 +1006,21 @@ function comfyLauncher(): Plugin {return}console.log(`[Download] Starting to path: ${filename} → ${destDir}`)- downloadFile(url, destPath, id).catch(err => console.error(`[Download] Failed: ${err.message}`))+ downloadFile(url, destPath, id).catch(err => console.error(`[Download] Failed: ${errorText(err)}`))res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'started', id }))} catch (err) {- res.writeHead(500, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: String(err) }))+ failRequest(res, err)}})})// API: Pause download (dev mode stub — sets status to paused)server.middlewares.use('/local-api/pause-download', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {- const { id } = JSON.parse(body)- const dl = activeDownloads.get(id)+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {+ const id = bodyString(body, 'id')+ const dl = id ? activeDownloads.get(id) : undefinedif (dl) dl.status = 'paused'res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'paused' }))@@ -1043,12 +1029,10 @@ function comfyLauncher(): Plugin {// API: Cancel download (dev mode stub — removes from map)server.middlewares.use('/local-api/cancel-download', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {- const { id } = JSON.parse(body)- activeDownloads.delete(id)+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {+ const id = bodyString(body, 'id')+ if (id) activeDownloads.delete(id)res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'cancelled' }))})@@ -1056,16 +1040,19 @@ function comfyLauncher(): Plugin {// API: Resume download (dev mode stub — restarts download)server.middlewares.use('/local-api/resume-download', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {- const { id, url, subfolder } = JSON.parse(body)- if (url && subfolder) {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {+ const id = bodyString(body, 'id')+ const url = bodyString(body, 'url')+ const subfolder = bodyString(body, 'subfolder')+ if (id && url && subfolder) {const comfyPath = findComfyUI()if (comfyPath) {- const destPath = join(comfyPath, 'models', subfolder, id)- downloadFile(url, destPath, id).catch(err => console.error(`[Download] Resume failed: ${err.message}`))+ // SICHERHEITSBEFUND, wie bei /download-model: `subfolder` und `id`+ // bauten den Zielpfad ungeprüft zusammen. `comfyDestPath` wirft+ // statt zu schreiben — withJsonBody macht daraus ein 403.+ const destPath = comfyDestPath(comfyPath, subfolder, id, 'never')+ downloadFile(url, destPath, id).catch(err => console.error(`[Download] Resume failed: ${errorText(err)}`))}}res.writeHead(200, { 'Content-Type': 'application/json' })@@ -1075,14 +1062,11 @@ function comfyLauncher(): Plugin {// API: Install custom node (git clone into ComfyUI/custom_nodes/)server.middlewares.use('/local-api/install-custom-node', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const _parsed = JSON.parse(body)- const repo_url = _parsed.repoUrl || _parsed.repo_url- const node_name = _parsed.nodeName || _parsed.node_name+ const repoUrl = bodyString(body, 'repoUrl', 'repo_url') ?? ''+ const nodeName = bodyString(body, 'nodeName', 'node_name') ?? ''const comfyPath = findComfyUI()if (!comfyPath) {res.writeHead(404, { 'Content-Type': 'application/json' })@@ -1091,50 +1075,55 @@ function comfyLauncher(): Plugin {}const customNodesDir = join(comfyPath, 'custom_nodes')if (!existsSync(customNodesDir)) mkdirSync(customNodesDir, { recursive: true })- const targetDir = join(customNodesDir, node_name || basename(repo_url, '.git'))+ // SICHERHEITSBEFUND: `nodeName` hing ungeprüft an `custom_nodes/`+ // (`'../../..'` klonte ausserhalb von ComfyUI), und `repoUrl` ging in+ // eine SHELL-Zeichenkette — `x"; rm -rf ~; echo "` war ein zweites+ // Kommando. Der Käfig steht jetzt in src/dev/model-paths.ts, und+ // execFileSync übergibt Argumente ohne Shell dazwischen.+ const targetDir = customNodeDir(comfyPath, nodeName, repoUrl)if (existsSync(targetDir)) {- console.log(`[CustomNode] Already installed: ${node_name}`)+ console.log(`[CustomNode] Already installed: ${nodeName}`)res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'already_installed', path: targetDir }))return}- console.log(`[CustomNode] Installing ${node_name} from ${repo_url}...`)+ console.log(`[CustomNode] Installing ${nodeName} from ${repoUrl}...`)try {- execSync(`git clone "${repo_url}" "${targetDir}"`, { timeout: 120000 })+ execFileSync('git', ['clone', repoUrl, targetDir], { timeout: 120000 })// Try pip install if requirements.txt existsconst reqFile = join(targetDir, 'requirements.txt')if (existsSync(reqFile)) {try {- execSync(`pip install -r "${reqFile}"`, { cwd: targetDir, timeout: 300000 })- } catch (pipErr: any) {- console.warn(`[CustomNode] pip install failed for ${node_name}:`, pipErr.message)+ execFileSync('pip', ['install', '-r', reqFile], { cwd: targetDir, timeout: 300000 })+ } catch (pipErr) {+ console.warn(`[CustomNode] pip install failed for ${nodeName}:`, errorText(pipErr))}}- console.log(`[CustomNode] Installed: ${node_name}`)+ console.log(`[CustomNode] Installed: ${nodeName}`)res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'installed', path: targetDir }))- } catch (gitErr: any) {- console.error(`[CustomNode] Git clone failed:`, gitErr.message)+ } catch (gitErr) {+ const detail = errorText(gitErr)+ console.error(`[CustomNode] Git clone failed:`, detail)res.writeHead(500, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: `Git clone failed: ${gitErr.message}` }))+ res.end(JSON.stringify({ error: `Git clone failed: ${detail}` }))}} catch (err) {- res.writeHead(400, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: String(err) }))+ failRequest(res, err)}})})// API: Set ComfyUI path (writes to .env and starts ComfyUI)server.middlewares.use('/local-api/set-comfyui-path', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: newPath } = JSON.parse(body)- const mainPy = join(newPath, 'main.py')- if (!existsSync(mainPy)) {+ const newPath = bodyString(body, 'path') ?? ''+ // Ohne Pfad gibt es nichts zu prüfen; `join(undefined, …)` warf hier+ // vorher eine TypeError in den Catch und meldete sie als "error".+ const mainPy = newPath ? join(newPath, 'main.py') : ''+ if (!mainPy || !existsSync(mainPy)) {res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'error', error: `main.py not found in "${newPath}". Make sure this is the ComfyUI root folder.` }))return@@ -1142,7 +1131,6 @@ function comfyLauncher(): Plugin {// Write to .env fileconst envPath = resolve(__dirname, '.env')- const { writeFileSync, readFileSync } = require('fs')let envContent = ''try { envContent = readFileSync(envPath, 'utf8') } catch { /* no .env yet */ }@@ -1168,7 +1156,7 @@ function comfyLauncher(): Plugin {res.end(JSON.stringify({ status: 'ok', path: newPath }))} catch (err) {res.writeHead(400, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ status: 'error', error: String(err) }))+ res.end(JSON.stringify({ status: 'error', error: errorText(err) || String(err) }))}})})@@ -1327,12 +1315,11 @@ function comfyLauncher(): Plugin {// API: Execute Python codeserver.middlewares.use('/local-api/execute-code', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { code, timeout: timeoutMs } = JSON.parse(body)+ const code = bodyString(body, 'code')+ const timeoutMs = bodyNumber(body, 'timeout')if (!code) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Missing code parameter' }))@@ -1400,12 +1387,10 @@ function comfyLauncher(): Plugin {// API: Read file from agent workspaceserver.middlewares.use('/local-api/file-read', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: filePath } = JSON.parse(body)+ const filePath = bodyString(body, 'path')if (!filePath || filePath.includes('..')) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Invalid path' }))@@ -1435,12 +1420,11 @@ function comfyLauncher(): Plugin {// API: Write file to agent workspaceserver.middlewares.use('/local-api/file-write', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: filePath, content } = JSON.parse(body)+ const filePath = bodyString(body, 'path')+ const content = bodyString(body, 'content')if (!filePath || filePath.includes('..')) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Invalid path' }))@@ -1473,12 +1457,13 @@ function comfyLauncher(): Plugin {// API: Shell executeserver.middlewares.use('/local-api/shell-execute', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { command, cwd, timeout: timeoutMs, shell: shellType } = JSON.parse(body)+ const command = bodyString(body, 'command')+ const cwd = bodyString(body, 'cwd')+ const timeoutMs = bodyNumber(body, 'timeout')+ const shellType = bodyString(body, 'shell')if (!command) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Missing command' }))@@ -1538,15 +1523,13 @@ function comfyLauncher(): Plugin {// API: FS read (unsandboxed)server.middlewares.use('/local-api/fs-read', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: filePath } = JSON.parse(body)+ const filePath = bodyString(body, 'path') ?? ''const os = require('os')const fs = require('fs')- const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)+ const resolved = isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)const content = fs.readFileSync(resolved, 'utf8')res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ content, encoding: 'utf8' }))@@ -1564,16 +1547,17 @@ function comfyLauncher(): Plugin {// panel, not a payload. Deliberately stricter than the fs-read// middleware above, which predates the jail and stays as it is.server.middlewares.use('/local-api/fs-read-bytes', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {const fail = (status: number, error: string) => {res.writeHead(status, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error }))}try {- const { path: filePath, chatId, workingDirectory, maxBytes } = JSON.parse(body)+ const filePath = bodyString(body, 'path')+ const chatId = bodyString(body, 'chatId')+ const workingDirectory = bodyString(body, 'workingDirectory')+ const maxBytes = bodyNumber(body, 'maxBytes')if (typeof filePath !== 'string' || !filePath) {fail(400, 'Missing path')return@@ -1606,15 +1590,14 @@ function comfyLauncher(): Plugin {// API: FS write (unsandboxed)server.middlewares.use('/local-api/fs-write', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: filePath, content } = JSON.parse(body)+ const filePath = bodyString(body, 'path') ?? ''+ const content = bodyString(body, 'content') ?? ''const os = require('os')const fs = require('fs')- const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)+ const resolved = isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)const parentDir = resolve(resolved, '..')if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true })fs.writeFileSync(resolved, content, 'utf8')@@ -1629,12 +1612,11 @@ function comfyLauncher(): Plugin {// API: FS listserver.middlewares.use('/local-api/fs-list', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: dirPath, recursive } = JSON.parse(body)+ const dirPath = bodyString(body, 'path') ?? ''+ const recursive = bodyFlag(body, 'recursive')const resolved = isAbsolute(dirPath) ? dirPath : join(os.homedir(), AGENT_WORKSPACE_DIR, dirPath)const entries: Array<{ name: string; path: string; size: number; isDir: boolean; modified: number }> = []// `recursive` arrived from the caller (file_list passes the model's@@ -1672,18 +1654,22 @@ function comfyLauncher(): Plugin {// API: FS search (grep-like)server.middlewares.use('/local-api/fs-search', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: dirPath, pattern, max_results } = JSON.parse(body)+ const dirPath = bodyString(body, 'path') ?? ''+ const pattern = bodyString(body, 'pattern')+ if (!pattern) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ results: [], count: 0, error: 'Missing pattern' }))+ return+ }const os = require('os')const fs = require('fs')- const resolved = require('path').isAbsolute(dirPath) ? dirPath : join(os.homedir(), AGENT_WORKSPACE_DIR, dirPath)+ const resolved = isAbsolute(dirPath) ? dirPath : join(os.homedir(), AGENT_WORKSPACE_DIR, dirPath)const re = new RegExp(pattern)- const results: any[] = []- const max = max_results || 50+ const results: FsSearchHit[] = []+ const max = bodyNumber(body, 'max_results') ?? 50function walkDir(dir: string, depth: number) {if (depth > 5 || results.length >= max) return@@ -1697,7 +1683,7 @@ function comfyLauncher(): Plugin {const stat = fs.statSync(full)if (stat.size > 1000000) continueconst content = fs.readFileSync(full, 'utf8')- const matches: any[] = []+ const matches: FsSearchMatch[] = []content.split('\n').forEach((line: string, i: number) => {if (re.test(line) && matches.length < 10) {matches.push({ line: i + 1, text: line.slice(0, 200) })@@ -1714,22 +1700,20 @@ function comfyLauncher(): Plugin {res.end(JSON.stringify({ results, count: results.length }))} catch (err) {res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ results: [], count: 0, error: String(err) }))+ res.end(JSON.stringify({ results: [], count: 0, error: errorText(err) || String(err) }))}})})// API: FS infoserver.middlewares.use('/local-api/fs-info', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { path: filePath } = JSON.parse(body)+ const filePath = bodyString(body, 'path') ?? ''const os = require('os')const fs = require('fs')- const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)+ const resolved = isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)const stat = fs.statSync(resolved)res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({@@ -1765,8 +1749,8 @@ function comfyLauncher(): Plugin {try {const r = await fetch(url)return { status: r.ok ? 'ok' : 'error', detail: `HTTP ${r.status}`, endpoint }- } catch (e: any) {- return { status: 'unreachable', detail: String(e?.message || e), endpoint }+ } catch (e) {+ return { status: 'unreachable', detail: errorText(e) || String(e), endpoint }}}const ollamaBase = (process.env.OLLAMA_HOST && /^https?:/.test(process.env.OLLAMA_HOST))@@ -1789,11 +1773,8 @@ function comfyLauncher(): Plugin {} catch { /* no nvidia-smi → null */ }let disk_free_gb = 0try {- const fs: any = require('fs')- if (fs.statfsSync) {- const st = fs.statfsSync(os.homedir())- disk_free_gb = +((st.bavail * st.bsize) / 1e9).toFixed(1)- }+ const st = statfsSync(os.homedir())+ disk_free_gb = +((Number(st.bavail) * Number(st.bsize)) / 1e9).toFixed(1)} catch { /* statfs unavailable */ }res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({@@ -1983,21 +1964,24 @@ function comfyLauncher(): Plugin {// API: Multi-tier web search (Brave/Tavily > SearXNG > DDG > Wikipedia)server.middlewares.use('/local-api/web-search', (req, res) => {- if (req.method !== 'POST') { res.writeHead(405); res.end(); return }- let body = ''- req.on('data', (c: any) => { body += c })- req.on('end', () => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {try {- const { query, count, provider, braveApiKey, tavilyApiKey } = JSON.parse(body)+ const query = bodyString(body, 'query')+ const provider = bodyString(body, 'provider')+ const braveApiKey = bodyString(body, 'braveApiKey')+ const tavilyApiKey = bodyString(body, 'tavilyApiKey')if (!query) {res.writeHead(400, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Missing query parameter' }))return}- const maxResults = count || 5+ const maxResults = bodyNumber(body, 'count') || 5- const fetchJSON = (url: string): Promise<any> => {+ // Fremde JSON-Antwort: `unknown` bis die Auswerter in+ // src/dev/web-search-parse.ts sie geprüft haben.+ const fetchJSON = (url: string): Promise<unknown> => {return new Promise((resolve, reject) => {const proto = url.startsWith('https') ? https : httpconst httpReq = proto.get(url, { headers: { 'User-Agent': 'locally-uncensored/1.0', 'Accept': 'application/json' }, timeout: 8000 }, (response) => {@@ -2010,10 +1994,10 @@ function comfyLauncher(): Plugin {response.resume()return}- let data = ''- response.on('data', (chunk: Buffer) => { data += chunk.toString() })+ const chunks: Buffer[] = []+ response.on('data', (chunk: Buffer) => { chunks.push(chunk) })response.on('end', () => {- try { resolve(JSON.parse(data)) } catch (e) { reject(e) }+ try { resolve(JSON.parse(decodeBodyChunks(chunks))) } catch (e) { reject(e) }})})httpReq.on('error', reject)@@ -2021,23 +2005,24 @@ function comfyLauncher(): Plugin {})}+ // Die fünf Auswerter liegen in src/dev/web-search-parse.ts neben+ // ihrem Test — bis hierher ist jede dieser Antworten `unknown`.+ const tierEmpty = (tier: string): Error => new Error(tier + ' returned no results')+// Tier 1: SearXNG (local instance)- const trySearXNG = (): Promise<{ title: string; url: string; snippet: string }[]> => {+ const trySearXNG = (): Promise<WebSearchResult[]> => {if (!searxngAvailable) return Promise.reject(new Error('SearXNG not available'))const searxUrl = 'http://localhost:8888/search?q=' + encodeURIComponent(query) + '&format=json'- return fetchJSON(searxUrl).then((data: any) => {- if (!data.results || data.results.length === 0) throw new Error('SearXNG returned no results')- console.log('[WebSearch] SearXNG returned ' + data.results.length + ' results')- return data.results.slice(0, maxResults).map((r: any) => ({- title: r.title || '',- url: r.url || '',- snippet: r.content || '',- }))+ return fetchJSON(searxUrl).then((data) => {+ const results = parseSearxngResults(data, maxResults)+ if (results.length === 0) throw tierEmpty('SearXNG')+ console.log('[WebSearch] SearXNG returned ' + results.length + ' results')+ return results})}// Tier 2: DuckDuckGo HTML search (POST, returns current results)- const tryDDGHTML = (): Promise<{ title: string; url: string; snippet: string }[]> => {+ const tryDDGHTML = (): Promise<WebSearchResult[]> => {return new Promise((resolve, reject) => {const postData = 'q=' + encodeURIComponent(query)const options = {@@ -2060,50 +2045,16 @@ function comfyLauncher(): Plugin {reject(new Error('DDG HTML returned HTTP ' + response.statusCode))return}- let html = ''- response.on('data', (chunk: Buffer) => { html += chunk.toString() })+ const chunks: Buffer[] = []+ response.on('data', (chunk: Buffer) => { chunks.push(chunk) })response.on('end', () => {try {- const results: { title: string; url: string; snippet: string }[] = []- // Parse result links: <a class="result__a" href="...">title</a>- const linkRegex = /<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi- // Parse snippets: <a class="result__snippet" ...>snippet</a>- const snippetRegex = /<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi-- const links: { title: string; url: string }[] = []- let linkMatch- while ((linkMatch = linkRegex.exec(html)) !== null) {- let url = linkMatch[1]- // DDG wraps URLs in redirect: //duckduckgo.com/l/?uddg=ENCODED_URL- if (url.includes('uddg=')) {- const uddg = url.split('uddg=')[1]?.split('&')[0]- if (uddg) url = decodeURIComponent(uddg)- }- const title = linkMatch[2].replace(/<[^>]*>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, "'").replace(/"/g, '"').trim()- if (title && url && url.startsWith('http')) {- links.push({ title, url })- }- }-- const snippets: string[] = []- let snippetMatch- while ((snippetMatch = snippetRegex.exec(html)) !== null) {- snippets.push(snippetMatch[1].replace(/<[^>]*>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, "'").replace(/"/g, '"').replace(/\s+/g, ' ').trim())- }-- for (let i = 0; i < Math.min(links.length, maxResults); i++) {- results.push({- title: links[i].title,- url: links[i].url,- snippet: snippets[i] || '',- })- }-+ const results = parseDdgHtmlResults(decodeBodyChunks(chunks), maxResults)if (results.length === 0) throw new Error('DDG HTML returned no parseable results')console.log('[WebSearch] DDG HTML returned ' + results.length + ' results')resolve(results)} catch (e) {- reject(e)+ reject(e instanceof Error ? e : new Error(String(e)))}})})@@ -2115,7 +2066,7 @@ function comfyLauncher(): Plugin {}// Tier: Brave Search API (needs API key)- const tryBrave = (): Promise<{ title: string; url: string; snippet: string }[]> => {+ const tryBrave = (): Promise<WebSearchResult[]> => {if (!braveApiKey) return Promise.reject(new Error('No Brave API key'))const braveUrl = 'https://api.search.brave.com/res/v1/web/search?q=' + encodeURIComponent(query) + '&count=' + maxResultsreturn new Promise((resolve, reject) => {@@ -2124,18 +2075,15 @@ function comfyLauncher(): Plugin {timeout: 8000,}, (response) => {if (response.statusCode !== 200) { response.resume(); reject(new Error('Brave HTTP ' + response.statusCode)); return }- let data = ''- response.on('data', (chunk: Buffer) => { data += chunk.toString() })+ const chunks: Buffer[] = []+ response.on('data', (chunk: Buffer) => { chunks.push(chunk) })response.on('end', () => {try {- const parsed = JSON.parse(data)- const results = (parsed.web?.results || []).slice(0, maxResults).map((r: any) => ({- title: r.title || '', url: r.url || '', snippet: r.description || '',- }))- if (results.length === 0) throw new Error('Brave returned no results')+ const results = parseBraveResults(JSON.parse(decodeBodyChunks(chunks)), maxResults)+ if (results.length === 0) throw tierEmpty('Brave')console.log('[WebSearch] Brave returned ' + results.length + ' results')resolve(results)- } catch (e) { reject(e) }+ } catch (e) { reject(e instanceof Error ? e : new Error(String(e))) }})})httpReq.on('error', reject)@@ -2144,7 +2092,7 @@ function comfyLauncher(): Plugin {}// Tier: Tavily Search API (needs API key, optimized for AI agents)- const tryTavily = (): Promise<{ title: string; url: string; snippet: string }[]> => {+ const tryTavily = (): Promise<WebSearchResult[]> => {if (!tavilyApiKey) return Promise.reject(new Error('No Tavily API key'))return new Promise((resolve, reject) => {const postData = JSON.stringify({ api_key: tavilyApiKey, query, max_results: maxResults, search_depth: 'basic' })@@ -2154,18 +2102,15 @@ function comfyLauncher(): Plugin {timeout: 10000,}, (response) => {if (response.statusCode !== 200) { response.resume(); reject(new Error('Tavily HTTP ' + response.statusCode)); return }- let data = ''- response.on('data', (chunk: Buffer) => { data += chunk.toString() })+ const chunks: Buffer[] = []+ response.on('data', (chunk: Buffer) => { chunks.push(chunk) })response.on('end', () => {try {- const parsed = JSON.parse(data)- const results = (parsed.results || []).slice(0, maxResults).map((r: any) => ({- title: r.title || '', url: r.url || '', snippet: r.content || '',- }))- if (results.length === 0) throw new Error('Tavily returned no results')+ const results = parseTavilyResults(JSON.parse(decodeBodyChunks(chunks)), maxResults)+ if (results.length === 0) throw tierEmpty('Tavily')console.log('[WebSearch] Tavily returned ' + results.length + ' results')resolve(results)- } catch (e) { reject(e) }+ } catch (e) { reject(e instanceof Error ? e : new Error(String(e))) }})})httpReq.on('error', reject)@@ -2176,23 +2121,18 @@ function comfyLauncher(): Plugin {}// Tier 3: Wikipedia API (always works)- const tryWikipedia = (): Promise<{ title: string; url: string; snippet: string }[]> => {+ const tryWikipedia = (): Promise<WebSearchResult[]> => {const wikiUrl = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + encodeURIComponent(query) + '&format=json&srlimit=' + maxResults + '&utf8=1'- return fetchJSON(wikiUrl).then((data: any) => {- if (!data.query || !data.query.search || data.query.search.length === 0) {- throw new Error('Wikipedia returned no results')- }- console.log('[WebSearch] Wikipedia returned ' + data.query.search.length + ' results')- return data.query.search.slice(0, maxResults).map((r: any) => ({- title: r.title || '',- url: 'https://en.wikipedia.org/wiki/' + encodeURIComponent(r.title.replace(/ /g, '_')),- snippet: (r.snippet || '').replace(/<[^>]*>/g, ''),- }))+ return fetchJSON(wikiUrl).then((data) => {+ const results = parseWikipediaResults(data, maxResults)+ if (results.length === 0) throw tierEmpty('Wikipedia')+ console.log('[WebSearch] Wikipedia returned ' + results.length + ' results')+ return results})}// Execute tiers based on provider setting- const searchChain = (): Promise<{ title: string; url: string; snippet: string }[]> => {+ const searchChain = (): Promise<WebSearchResult[]> => {if (provider === 'brave') return tryBrave().catch(() => trySearXNG()).catch(() => tryDDGHTML()).catch(() => tryWikipedia())if (provider === 'tavily') return tryTavily().catch(() => trySearXNG()).catch(() => tryDDGHTML()).catch(() => tryWikipedia())// 'auto': SearXNG > Brave (if key) > Tavily (if key) > DDG > Wikipedia@@ -2227,31 +2167,34 @@ function comfyLauncher(): Plugin {let whisperReady = falselet whisperBackend: string | null = nulllet whisperBuffer = ''- const whisperQueue: Array<{ resolve: (v: any) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }> = []+ // Der Whisper-Server ist ein FREMDER Prozess (public/whisper_server.py):+ // was er auf stdout schreibt, ist unbekannte Form, bis es geprüft ist.+ const whisperQueue: Array<{ resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }> = []function handleWhisperLine(line: string) {- try {- const data = JSON.parse(line)- if (data.status === 'ready') {- whisperReady = true- whisperBackend = data.backend || 'faster-whisper'- console.log(`[Whisper] Server ready (backend: ${whisperBackend})`)- return- }- if (data.status === 'error' && !whisperReady) {- console.error('[Whisper] Server failed to start:', data.error)- return- }- // Route response to the oldest queued request- const pending = whisperQueue.shift()- if (pending) {- clearTimeout(pending.timer)- pending.resolve(data)- }- } catch { /* not JSON, ignore */ }+ const parsed = parseJsonBody(line)+ if (!parsed.ok) return // keine JSON-Zeile — der Server loggt auch Text+ const data = parsed.value+ const status = asString(prop(data, 'status'))+ if (status === 'ready') {+ whisperReady = true+ whisperBackend = asString(prop(data, 'backend')) || 'faster-whisper'+ console.log(`[Whisper] Server ready (backend: ${whisperBackend})`)+ return+ }+ if (status === 'error' && !whisperReady) {+ console.error('[Whisper] Server failed to start:', errorText(prop(data, 'error')))+ return+ }+ // Route response to the oldest queued request+ const pending = whisperQueue.shift()+ if (pending) {+ clearTimeout(pending.timer)+ pending.resolve(data)+ }}- function sendWhisperCommand(cmd: object, timeoutMs = 30000): Promise<any> {+ function sendWhisperCommand(cmd: object, timeoutMs = 30000): Promise<unknown> {return new Promise((resolve, reject) => {if (!whisperProc || !whisperReady) {reject(new Error('Whisper server not ready'))@@ -2446,20 +2389,23 @@ function comfyLauncher(): Plugin {// Clean up temp filetry { fs.unlinkSync(tmpFile) } catch { /* ignore */ }- if (result.error) {- console.error('[Whisper] Transcription error:', result.error)+ const whisperError = errorText(prop(result, 'error'))+ if (whisperError) {+ console.error('[Whisper] Transcription error:', whisperError)res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: result.error, transcript: '' }))+ res.end(JSON.stringify({ error: whisperError, transcript: '' }))return}- console.log(`[Whisper] Transcribed: "${result.transcript?.substring(0, 80)}..." (lang: ${result.language})`)+ const transcript = asString(prop(result, 'transcript')) ?? ''+ const language = asString(prop(result, 'language')) ?? 'en'+ console.log(`[Whisper] Transcribed: "${transcript.substring(0, 80)}..." (lang: ${language})`)res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ transcript: result.transcript || '', language: result.language || 'en' }))+ res.end(JSON.stringify({ transcript, language }))} catch (err) {- console.error('[Whisper] Request error:', (err as Error).message)+ console.error('[Whisper] Request error:', errorText(err))res.writeHead(500, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: String(err), transcript: '' }))+ res.end(JSON.stringify({ error: errorText(err) || String(err), transcript: '' }))}})})