Compare commits

...
3 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 5.5 b81aa84898 release: v0.7.12 - restrict client-supplied backend URLs (SSRF)
Ollama chat, Tagger VLM, Eagle and the Unsloth relay accepted the target URL
from the request. Add py/services/url_guard.py: loopback or operator-listed
WFS_ALLOWED_BACKEND_HOSTS only, http(s) only, no credentials, no redirects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 06:49:16 +09:00
ketle-manandClaude Sonnet 5.5 4179511e1b fix(security): restrict preview downloads to CivitAI hosts, fix Host-header based origin
- download_image: https + CivitAI hosts only (also validates redirects, 50MB cap);
  sidecar-supplied image URLs could trigger SSRF / file:// reads
- Lora Manager bridge: connect to 127.0.0.1 with the real listening port instead
  of the request Host header
- safeHttpUrl for sample/fallback image URLs; DEVLOG

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 22:32:58 +09:00
ketle-manandClaude Sonnet 5.5 cb9f5eecc4 release: v0.7.11 - sanitize CivitAI description HTML (stored XSS), harden sidecar import
- util.js: allowlist sanitizeHtml() / safeHttpUrl() (absolute http(s) only);
  applied to the Models detail panel description, model URL and sample images
- cm-info/metadata sidecar import: numeric IDs only, type checks, 2MB size cap
- DEVLOG, README badge, version bump

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 22:26:31 +09:00
15 changed files with 279 additions and 69 deletions
+2
View File
@@ -2,6 +2,8 @@
Condensed version-by-version index of DEVLOG.md (each line: version + one-line summary of what changed and why). Full rationale, code details, and "How to apply" lessons live in the excluded DEVLOG.md itself; this index exists so graphify can extract a queryable semantic node per release without feeding the full log to the local Ollama model. Regenerate with `python tools/generate_doc_index.py devlog` whenever DEVLOG.md changes.
- **v0.7.12(2026-10-04)** — セキュリティ: バックエンド接続先をブラウザから任意指定できた問題(SSRF)を修正
- **v0.7.11(2026-10-02)** — セキュリティ: CivitAI情報の説明文のHTML無害化(保存型XSS対策)
- **v0.7.10(2026-10-02)** — Windows: ComfyUIが固まる問題の原因特定と対策(Selectorイベントループ)
- **v0.7.9(2026-10-02)** — Models: CivitAIベースモデルからの自動バッジ作成
- **v0.7.8(2026-10-01)** — Video Edit: マルチトラック化(ビデオ/オーバーレイ/テキスト/オーディオ)
+38
View File
@@ -2,6 +2,44 @@
---
## v0.7.12(2026-10-04)
### セキュリティ: バックエンド接続先をブラウザから任意指定できた問題(SSRF)を修正
ComfyUI-Manager登録PR(LiveChatStream、Comfy-Org/ComfyUI-Manager#3340)のレビューで指摘された「リクエストから接続先URLを受け取り、サーバーが接続する」問題が、WFSにも同じ構造で存在していたため修正。
- 対象: `POST /api/wfm/ollama/chat`(bodyの `url`。従来は**検証なし**で、任意ホスト・クラウドメタデータ・`file://` に接続できた)、Tagger VLM(`/wfm/tagger/vlm/models`・`vlm/predict`・`batch/start` の `api_url`。Unslothのみ制限されていた)、Eagle(`/api/wfm/eagle/add`・`/test` の `eagleUrl`)、Unslothプロキシ(`baseUrl`)。
- 新規 `py/services/url_guard.py` に共通化。許可は **loopback(localhost / 127.0.0.1 / ::1、ポート自由)** と、運用者が環境変数 `WFS_ALLOWED_BACKEND_HOSTS`(`host` または `host:port` のカンマ区切り)で指定したホストのみ。`http(s)` 以外(`file://` 等)、URL内の認証情報、`localhost.evil.com` のような偽装ホストは拒否。**リダイレクトは追従しない**(302は接続せずエラー)。
- **挙動変更**: LAN上の別マシンのOllama/Eagle等を使っている場合は `WFS_ALLOWED_BACKEND_HOSTS` の設定が必要(拒否時のエラーメッセージに案内を表示)。
- 実機(ComfyUI_5、ポート8189)で、メタデータIP・`file://`・公開IPの拒否、loopbackのOllama chat/Tagger一覧/Eagle test/Unsloth Decision APIの正常動作を確認。
- 注意: ComfyUIを `--listen` で公開すると、到達できる相手は引き続きこれらのルートを使える(接続先を変えられないだけ)。信頼できるネットワークでのみ使うこと。
---
## v0.7.11(2026-10-02)
### セキュリティ: CivitAI情報の説明文のHTML無害化(保存型XSS対策)
- Models詳細パネルのCivitAIタブは、説明文(`description`)をエスケープせずHTMLとして挿入していた。CivitAI APIの応答は従来から同じ扱いだったが、v0.7.10で追加した `.cm-info.json`(Stability Matrix)取り込みにより、**ローカルのサイドカーファイルからも同じ経路で入る**ようになった。細工されたファイルがモデルと一緒に配布された場合、詳細パネルを開いただけでスクリプトが実行され得る(ComfyUIと同一オリジンのため、ComfyUIのAPIを操作できる)。
- `static/js/util.js` に許可リスト方式の `sanitizeHtml()` と `safeHttpUrl()` を追加し、説明文・モデルURL・サンプル画像URLに適用。`script/style/iframe/svg/form` 等の要素、`on*` 属性、`style` 属性、`javascript:`/`data:` URL、**相対URL**(ComfyUI自身のURLへリクエストを送らせる経路)を除去する。許可するのは段落・見出し・リスト・強調・表・`code`・`a`/`img`(絶対http(s) URLのみ)など。
- Playwright(実ブラウザ)で攻撃文字列16種を検証し、スクリプトが一度も実行されないことを確認。
### セキュリティ: サイドカー経由のSSRF/ローカルファイル読み取りと、Hostヘッダ依存の接続先
取り込み経路の再点検で見つかった2件を修正。
- **プレビュー画像のダウンロード(`download_image`)のURLが無検証だった**。URLは `.metadata.json`(Lora Manager形式のローカルサイドカー)の `civitai.images` から来るため、細工されたサイドカーがあると、サーバーが任意のURLへ接続する(SSRF)。`file://` を指定すればローカルファイルを読んでプレビュー画像として保存でき、プレビューAPI経由で取り出せた。**https かつ CivitAI系ホスト(`civitai.com`/`civitai.red`/`civitai.green` とそのサブドメイン)のみ許可**し、リダイレクト先も同じ条件で検証、サイズ上限50MBを設定。正規のCivitAI画像の取得は実環境で確認済み。
- **Lora Manager連携(`lora_manager_bridge`)の接続先を、リクエストのHostヘッダから組み立てていた**。Hostの偽装(DNSリバインディング等)で任意のホストへ接続させられるため、**ループバック(`127.0.0.1`)+実際に待ち受けているポート**に固定。
- サンプル画像・フォールバック画像のURLにも `safeHttpUrl()`(絶対http(s)のみ)を適用。
### `.cm-info.json` / `.metadata.json` 取り込みの堅牢化
- `ModelId`/`VersionId` は正の整数のみ受け付ける(URLに文字列を埋め込まない)。不正なら情報は採用せず、sha256のみ利用。
- タグ・トリガーワードは文字列/数値のみ・件数上限あり。JSONのトップレベルがオブジェクトでない場合は無視。
- サイドカーJSONのサイズ上限を2MBに設定(巨大ファイルでメモリを使い切らない)。
---
## v0.7.10(2026-10-02)
### Windows: ComfyUIが固まる問題の原因特定と対策(Selectorイベントループ)
+5 -1
View File
@@ -26,7 +26,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.10-green)
![Version](https://img.shields.io/badge/version-0.7.12-green)
## Features (tab -> feature names)
@@ -162,6 +162,10 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
- **[comfyui-mask-editor-one](https://github.com/ketle-man/comfyui-mask-editor-one) (v0.1.9+)** — enables BiRefNet background removal, SAM3 text-prompt segmentation, and ABR stamp-brush library in the Image Edit Mask tool; `birefnet.safetensors` must be placed in `ComfyUI/models/background_removal/` for BiRefNet
- **[psd-tools](https://pypi.org/project/psd-tools/)** (v0.6.0) — enables all PSD (Photoshop) features: Gallery bulk "Create PSD" export, Gallery browsing/thumbnails for `.psd` files, and Image Edit's Save PSD / Open PSD buttons; `pip install -r requirements.txt` (ships prebuilt wheels, no C compiler required); without it, PSD-related actions show an error toast with the install command instead of failing silently
#### Backend connection security (v0.7.12)
Server-side proxies for Ollama, LM Studio, Lemonade, Unsloth, the Tagger VLM and Eagle only connect to **localhost / 127.0.0.1 / ::1** (any port); `http(s)` only, no credentials in the URL, and redirects are never followed. To use a backend on another machine (e.g. an Ollama server on your LAN), list it in the `WFS_ALLOWED_BACKEND_HOSTS` environment variable (comma-separated `host` or `host:port`, e.g. `192.168.1.20:11434,gpu-box`) and restart ComfyUI. If you start ComfyUI with `--listen`, anyone who can reach it can use these routes, so only do that on a trusted network.
---
## Supported Languages
+5 -1
View File
@@ -22,7 +22,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.10-green)
![Version](https://img.shields.io/badge/version-0.7.12-green)
## Screenshots
@@ -584,6 +584,10 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
- **[comfyui-mask-editor-one](https://github.com/ketle-man/comfyui-mask-editor-one) (v0.1.9+)** — enables BiRefNet background removal, SAM3 text-prompt segmentation, and ABR stamp-brush library in the Image Edit Mask tool; `birefnet.safetensors` must be placed in `ComfyUI/models/background_removal/` for BiRefNet
- **[psd-tools](https://pypi.org/project/psd-tools/)** (v0.6.0) — enables all PSD (Photoshop) features: Gallery bulk "Create PSD" export, Gallery browsing/thumbnails for `.psd` files, and Image Edit's Save PSD / Open PSD buttons; `pip install -r requirements.txt` (ships prebuilt wheels, no C compiler required); without it, PSD-related actions show an error toast with the install command instead of failing silently
#### Backend connection security (v0.7.12)
Server-side proxies for Ollama, LM Studio, Lemonade, Unsloth, the Tagger VLM and Eagle only connect to **localhost / 127.0.0.1 / ::1** (any port); `http(s)` only, no credentials in the URL, and redirects are never followed. To use a backend on another machine (e.g. an Ollama server on your LAN), list it in the `WFS_ALLOWED_BACKEND_HOSTS` environment variable (comma-separated `host` or `host:port`, e.g. `192.168.1.20:11434,gpu-box`) and restart ComfyUI. If you start ComfyUI with `--listen`, anyone who can reach it can use these routes, so only do that on a trusted network.
---
## Supported Languages
+7 -5
View File
@@ -9,6 +9,8 @@ import urllib.error
from aiohttp import web
from ..services.url_guard import require_backend_url, urlopen as _guarded_urlopen
logger = logging.getLogger(__name__)
@@ -92,7 +94,7 @@ def _eagle_add_from_path(eagle_url, file_path, name, tags):
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
with _guarded_urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -127,7 +129,7 @@ def _eagle_add(eagle_url, image_url, name, tags):
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
with _guarded_urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -138,7 +140,7 @@ def _eagle_test(eagle_url):
f"{eagle_url}/api/application/info",
method="GET",
)
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -146,7 +148,7 @@ async def handle_add(request: web.Request) -> web.Response:
"""POST /api/wfm/eagle/add - Add image to Eagle."""
try:
body = await request.json()
eagle_url = body.get("eagleUrl", "http://localhost:41595")
eagle_url = require_backend_url(body.get("eagleUrl", "http://localhost:41595"))
image_url = body.get("url", "")
name = body.get("name", "image.png")
tags = body.get("tags", [])
@@ -193,7 +195,7 @@ async def handle_test(request: web.Request) -> web.Response:
"""POST /api/wfm/eagle/test - Test Eagle connection."""
try:
body = await request.json()
eagle_url = body.get("eagleUrl", "http://localhost:41595")
eagle_url = require_backend_url(body.get("eagleUrl", "http://localhost:41595"))
result = await asyncio.to_thread(_eagle_test, eagle_url)
return web.json_response({
"status": "success",
+4 -1
View File
@@ -267,7 +267,10 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
# 未計算のものは Lora Manager が保持済みのsha256を借りる(サイズ一致時のみ。ハッシュ計算を省く)
if len(known) < len(model_files):
from ..services.lora_manager_bridge import fetch_lm_hashes, _norm
origin = f"{request.scheme}://{request.host}"
# Hostヘッダは信用せず、自分自身のループバック+実際のポートへ接続する(Host偽装/DNSリバインディング対策)
sockname = request.transport.get_extra_info("sockname") if request.transport else None
port = sockname[1] if sockname else (request.url.port or 8188)
origin = f"http://127.0.0.1:{port}"
lm = await asyncio.to_thread(fetch_lm_hashes, origin, model_type)
for n, p in model_files:
if n in known:
+9 -6
View File
@@ -7,6 +7,7 @@ import urllib.request
from aiohttp import web
from ..services.settings_service import SettingsService
from ..services.url_guard import require_backend_url, urlopen
logger = logging.getLogger(__name__)
@@ -39,11 +40,12 @@ async def handle_models(request: web.Request) -> web.Response:
import asyncio
try:
cfg = _get_ollama_config()
base_url = require_backend_url(cfg["url"])
def _fetch():
url = f"{cfg['url']}/api/tags"
url = f"{base_url}/api/tags"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=5) as resp:
with urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
@@ -61,11 +63,12 @@ async def handle_test(request: web.Request) -> web.Response:
import asyncio
try:
cfg = _get_ollama_config()
base_url = require_backend_url(cfg["url"])
def _test():
url = f"{cfg['url']}/api/tags"
url = f"{base_url}/api/tags"
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=5) as resp:
with urlopen(req, timeout=5) as resp:
return resp.status == 200
ok = await asyncio.to_thread(_test)
@@ -83,7 +86,7 @@ async def handle_chat(request: web.Request) -> web.Response:
body = await request.json()
cfg = _get_ollama_config()
model = body.get("model") or cfg["model"]
base_url = (body.get("url") or cfg["url"]).rstrip("/")
base_url = require_backend_url(body.get("url") or cfg["url"])
messages = body.get("messages", [])
def _chat():
@@ -100,7 +103,7 @@ async def handle_chat(request: web.Request) -> web.Response:
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
with urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode("utf-8"))
resp_data = await asyncio.to_thread(_chat)
+8 -19
View File
@@ -19,19 +19,19 @@ import logging
import os
import urllib.request
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from aiohttp import web
from ..services.url_guard import HINT as _URL_HINT, is_allowed_backend_url, urlopen as _guarded_urlopen
logger = logging.getLogger(__name__)
UNSLOTH_DEFAULT_URL = "http://localhost:8888"
_ALLOWED_PATHS = {"/v1/models", "/v1/chat/completions", "/v1/systemone"}
# baseUrl is client-supplied (so a custom Unsloth port works), but the
# Authorization header carries a real secret — restrict the host to loopback
# so this proxy can't be used to exfiltrate UNSLOTH_API_KEY to an arbitrary
# server (SSRF). Port is unrestricted.
_ALLOWED_HOSTS = {"localhost", "127.0.0.1", "::1"}
# Authorization header carries a real secret — restrict the host (loopback, or
# WFS_ALLOWED_BACKEND_HOSTS set by the operator) so this proxy can't be used to
# exfiltrate UNSLOTH_API_KEY to an arbitrary server (SSRF). Redirects are not followed.
def _get_api_key():
@@ -47,15 +47,6 @@ KEYLESS_REJECTED_MESSAGE = (
)
def _is_allowed_base_url(base_url):
"""Only relay (and attach the API key) to a loopback host."""
try:
parsed = urlparse(base_url)
return parsed.scheme in ("http", "https") and parsed.hostname in _ALLOWED_HOSTS
except Exception:
return False
def setup_routes(app: web.Application):
"""Register Unsloth API routes."""
app.router.add_post("/api/wfm/unsloth/proxy", handle_proxy)
@@ -78,10 +69,8 @@ async def handle_proxy(request: web.Request) -> web.Response:
if path not in _ALLOWED_PATHS or method not in ("GET", "POST"):
return web.json_response({"message": "Unsupported proxy target"}, status=400)
if not _is_allowed_base_url(base_url):
return web.json_response({
"message": "Unsloth backend URL must point to localhost/127.0.0.1/::1",
}, status=400)
if not is_allowed_backend_url(base_url):
return web.json_response({"message": _URL_HINT}, status=400)
# No key → relay without Authorization (Unsloth's Keyless API access); if Unsloth
# still demands one, the 401 below explains both ways to fix it.
@@ -93,7 +82,7 @@ async def handle_proxy(request: web.Request) -> web.Response:
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base_url}{path}", data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=120) as resp:
with _guarded_urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
+61 -6
View File
@@ -56,6 +56,38 @@ _MAX_RETRIES = 3
_BATCH_CHUNK_SIZE = 100
# サイドカーJSON(.metadata.json / .cm-info.json)の最大サイズ。巨大ファイルでメモリを使い切らないための上限
_SIDECAR_MAX_BYTES = 2 * 1024 * 1024
def _as_int(v):
"""数値IDだけを受け付ける(文字列に細工されたIDをURL等に埋め込まないため)。不正ならNone。"""
try:
if isinstance(v, bool):
return None
n = int(v)
return n if n > 0 else None
except (TypeError, ValueError):
return None
# プレビュー画像のダウンロード許可ホスト(サイドカーJSON由来のURLでSSRF/ローカルファイル読み取りをさせない)
_IMAGE_HOST_SUFFIXES = (".civitai.com", ".civitai.red", ".civitai.green")
_IMAGE_HOST_EXACT = ("civitai.com", "civitai.red", "civitai.green")
_IMAGE_MAX_BYTES = 50 * 1024 * 1024
def _is_allowed_image_url(url):
"""https かつ CivitAI 系ホストのURLだけ許可する(file:// や内部アドレス、他ホストは拒否)。"""
try:
from urllib.parse import urlparse
u = urlparse(str(url).strip())
host = (u.hostname or "").lower()
return u.scheme == "https" and (host in _IMAGE_HOST_EXACT or host.endswith(_IMAGE_HOST_SUFFIXES))
except Exception:
return False
class CivitaiService:
"""Fetch and cache CivitAI model metadata."""
@@ -399,8 +431,12 @@ class CivitaiService:
"""
sc = file_path.with_name(file_path.stem + ".cm-info.json")
try:
if sc.stat().st_size > _SIDECAR_MAX_BYTES: # 巨大ファイルによるメモリ消費を避ける
return None, None
with open(sc, "r", encoding="utf-8-sig") as f:
d = json.load(f)
if not isinstance(d, dict):
return None, None
sha = str((d.get("Hashes") or {}).get("SHA256", "")).lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
return None, None
@@ -412,7 +448,7 @@ class CivitaiService:
info = None
try:
if d.get("Source", 0) == 0 and d.get("VersionId"): # 0 = Civitai
if d.get("Source", 0) == 0 and _as_int(d.get("VersionId")): # 0 = Civitai
info = self._info_from_cm_info(d)
except Exception:
info = None
@@ -421,7 +457,7 @@ class CivitaiService:
@staticmethod
def _info_from_cm_info(d):
"""cm-info.json を _extract_info と同じ形式のdictに変換する。"""
model_id, version_id = d.get("ModelId"), d.get("VersionId")
model_id, version_id = _as_int(d.get("ModelId")), _as_int(d.get("VersionId"))
stats = d.get("Stats") or {}
return {
"versionId": version_id,
@@ -430,14 +466,14 @@ class CivitaiService:
"versionName": d.get("VersionName", ""),
"type": d.get("ModelType", ""),
"description": d.get("VersionDescription") or d.get("ModelDescription", ""),
"tags": d.get("Tags") or [],
"tags": [str(x) for x in (d.get("Tags") or []) if isinstance(x, (str, int, float))][:100],
"nsfw": bool(d.get("Nsfw", False)),
"nsfwLevel": 0,
"air": "",
"creator": d.get("AuthorUsername") or "",
"images": [],
"imageDetails": [],
"trainedWords": d.get("TrainedWords") or [],
"trainedWords": [str(x) for x in (d.get("TrainedWords") or []) if isinstance(x, (str, int, float))][:200],
"baseModel": d.get("BaseModel") or "",
"fileSize": 0,
"fileMeta": d.get("FileMetadata") or {},
@@ -465,8 +501,12 @@ class CivitaiService:
"""
sc = file_path.with_name(file_path.stem + ".metadata.json")
try:
if sc.stat().st_size > _SIDECAR_MAX_BYTES:
return None, None
with open(sc, "r", encoding="utf-8") as f:
d = json.load(f)
if not isinstance(d, dict):
return None, None
sha = str(d.get("sha256", "")).lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
return None, None
@@ -640,10 +680,25 @@ class CivitaiService:
@staticmethod
def download_image(url, save_path, timeout=15):
"""Download an image from URL and save to save_path. Returns True on success."""
if not _is_allowed_image_url(url):
logger.warning("Refusing to download preview from non-CivitAI URL: %s", str(url)[:120])
return False
try:
from urllib.request import HTTPRedirectHandler, HTTPSHandler, build_opener
class _SafeRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
if not _is_allowed_image_url(newurl): # リダイレクト先も検証
raise ValueError("redirect to disallowed host")
return super().redirect_request(req, fp, code, msg, headers, newurl)
opener = build_opener(_SafeRedirect, HTTPSHandler(context=_get_ssl_context()))
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
with urlopen(req, timeout=timeout, context=_get_ssl_context()) as resp:
data = resp.read()
with opener.open(req, timeout=timeout) as resp:
data = resp.read(_IMAGE_MAX_BYTES + 1)
if len(data) > _IMAGE_MAX_BYTES:
logger.warning("Preview too large, skipped: %s", str(url)[:120])
return False
with open(save_path, "wb") as f:
f.write(data)
return True
+13 -23
View File
@@ -13,7 +13,7 @@ import urllib.error
import urllib.request
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
from .url_guard import HINT as _URL_HINT, is_allowed_backend_url, urlopen as _guarded_urlopen
import numpy as np
from PIL import Image, ImageOps, PngImagePlugin
@@ -22,19 +22,9 @@ logger = logging.getLogger(__name__)
_model_lock = threading.Lock()
# Unsloth requires an Authorization: Bearer <UNSLOTH_API_KEY> header even for
# local access. api_url is client-supplied per request, so without a host
# check a client could point it at an arbitrary server and exfiltrate the key
# (SSRF). Mirrors unsloth_routes.py's _is_allowed_base_url/_ALLOWED_HOSTS.
_UNSLOTH_ALLOWED_HOSTS = {"localhost", "127.0.0.1", "::1"}
def _is_allowed_unsloth_url(api_url: str) -> bool:
try:
parsed = urlparse(api_url)
return parsed.scheme in ("http", "https") and parsed.hostname in _UNSLOTH_ALLOWED_HOSTS
except Exception:
return False
# api_url is client-supplied per request, so every backend (Ollama / OpenAI-compatible / Unsloth)
# goes through url_guard: loopback or WFS_ALLOWED_BACKEND_HOSTS only, no redirects. This also
# stops the Unsloth API key (Authorization header) from being sent to an arbitrary server.
class TaggerService:
@@ -279,22 +269,22 @@ class TaggerService:
def vlm_models(self, backend: str, api_url: str) -> list:
backend = (backend or "ollama").lower()
try:
if not is_allowed_backend_url(api_url):
logger.error("vlm_models: %s", _URL_HINT)
return []
if backend == "ollama":
req = urllib.request.Request(api_url.rstrip("/") + "/api/tags")
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["name"] for m in data.get("models", []))
headers = {}
if backend == "unsloth":
if not _is_allowed_unsloth_url(api_url):
logger.error("vlm_models: Unsloth backend URL must point to localhost/127.0.0.1/::1")
return []
key = self._unsloth_api_key()
if key:
headers["Authorization"] = f"Bearer {key}"
req = urllib.request.Request(api_url.rstrip("/") + "/v1/models", headers=headers)
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["id"] for m in data.get("data", []))
except Exception as e:
@@ -309,6 +299,8 @@ class TaggerService:
thinking_mode: bool = False, max_tokens: int = 0) -> dict:
backend = (backend or "ollama").lower()
try:
if not is_allowed_backend_url(api_url):
return {"error": _URL_HINT}
if backend == "ollama":
body = {
"model": model,
@@ -326,14 +318,12 @@ class TaggerService:
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=180) as resp:
with _guarded_urlopen(req, timeout=180) as resp:
data = json.loads(resp.read().decode("utf-8"))
content = data.get("message", {}).get("content", "")
else:
headers = {"Content-Type": "application/json"}
if backend == "unsloth":
if not _is_allowed_unsloth_url(api_url):
return {"error": "Unsloth backend URL must point to localhost/127.0.0.1/::1"}
key = self._unsloth_api_key()
if key:
headers["Authorization"] = f"Bearer {key}"
@@ -354,7 +344,7 @@ class TaggerService:
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=180) as resp:
with _guarded_urlopen(req, timeout=180) as resp:
data = json.loads(resp.read().decode("utf-8"))
message = data.get("choices", [{}])[0].get("message", {})
content = message.get("content", "")
+68
View File
@@ -0,0 +1,68 @@
"""Outbound URL guard for backend proxies (SSRF mitigation).
Several routes (Ollama chat, Tagger VLM, Eagle, Unsloth relay) connect to a backend whose
address is supplied by the browser. Without a check, any caller that can reach ComfyUI could
make the server connect to an arbitrary host (cloud metadata, LAN services, file://).
Allowed targets:
- loopback hosts (localhost / 127.0.0.1 / ::1), any port
- hosts listed by the operator in the WFS_ALLOWED_BACKEND_HOSTS environment variable
(comma-separated "host" or "host:port"; e.g. "192.168.1.20:11434,gpu-box")
Only http(s) URLs without credentials are accepted, and redirects are never followed.
"""
import os
import urllib.request
from urllib.parse import urlparse
LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
ALLOWED_HOSTS_ENV = "WFS_ALLOWED_BACKEND_HOSTS"
HINT = (
"Backend URL must point to localhost/127.0.0.1/::1. To use another host, list it in the "
f"{ALLOWED_HOSTS_ENV} environment variable (e.g. 192.168.1.20:11434) and restart ComfyUI."
)
def _operator_allowlist():
raw = os.environ.get(ALLOWED_HOSTS_ENV, "")
return {item.strip().lower() for item in raw.split(",") if item.strip()}
def is_allowed_backend_url(url):
"""True if url is an http(s) URL without credentials whose host[:port] is permitted."""
try:
parsed = urlparse((url or "").strip())
if parsed.scheme not in ("http", "https") or not parsed.hostname:
return False
if parsed.username or parsed.password:
return False
host = parsed.hostname.lower()
if host in LOOPBACK_HOSTS:
return True
allow = _operator_allowlist()
return host in allow or (parsed.port is not None and f"{host}:{parsed.port}" in allow)
except Exception:
return False
def require_backend_url(url):
"""Return url stripped of trailing slashes, or raise ValueError(HINT)."""
url = (url or "").strip()
if not is_allowed_backend_url(url):
raise ValueError(HINT)
return url.rstrip("/")
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
_opener = urllib.request.build_opener(_NoRedirect)
def urlopen(req, timeout):
"""urllib urlopen that never follows redirects (a 3xx surfaces as HTTPError)."""
return _opener.open(req, timeout=timeout)
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-workflow-studio"
description = "A comprehensive workflow, asset management, and generation UI plugin for ComfyUI. Manage workflows, models, images, and prompts; batch generation and Image Feeder in the GenerateUI tab; library side panel with canvas drag & drop and AI tools."
version = "0.7.10"
version = "0.7.12"
license = { file = "LICENSE" }
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+5 -5
View File
@@ -8,7 +8,7 @@
import { showToast, openModal, closeModal } from "../app.js";
import { t } from "../i18n.js";
import { escapeHtml } from "../util.js";
import { escapeHtml, sanitizeHtml, safeHttpUrl } from "../util.js";
import { state, RESERVED_GROUPS, GENUI_TYPE_MAP } from "./state.js";
import { getCurrentModels, renderTagFilter, renderDirFilter } from "./filters.js";
import { getBadgePalette, modelBadgesHtml, openBadgeEditModal } from "./badges.js";
@@ -619,7 +619,7 @@ export async function fetchCivitaiForModel(modelName, el) {
if (data.preview_saved) {
sideImg.src = previewUrl(modelName) + "&t=" + Date.now();
} else {
const civitaiImg = data.civitai.images && data.civitai.images[0];
const civitaiImg = safeHttpUrl(data.civitai.images && data.civitai.images[0]);
if (civitaiImg) sideImg.src = civitaiImg;
}
sideImg.style.display = "";
@@ -648,7 +648,7 @@ export function renderCivitaiInfo(el, info, modelName) {
? `https://${civitaiHost}/models/${info.modelId}?modelVersionId=${info.versionId}`
: info.versionId
? `https://${civitaiHost}/model-versions/${info.versionId}`
: (info.modelUrl || "#");
: safeHttpUrl(info.modelUrl, "#");
// Hash: BLAKE3 優先、なければ SHA256
const fileHashes = info.fileHashes || {};
@@ -697,7 +697,7 @@ export function renderCivitaiInfo(el, info, modelName) {
).join(" ");
// Sample images — all go to Sample pane
const images = info.images || [];
const images = (info.images || []).filter((u) => safeHttpUrl(u));
const sampleImagesHtml = images.map((url) =>
`<a href="${escapeHtml(url)}" target="_blank" rel="noopener" title="${t("civitaiOpenImage")}"><img src="${escapeHtml(url)}" style="width:100%;border-radius:4px;margin-bottom:6px;cursor:pointer;display:block;" loading="lazy" /></a>`
).join("");
@@ -727,7 +727,7 @@ export function renderCivitaiInfo(el, info, modelName) {
${detailSection}
${tagsHtml ? `<div style="margin-bottom:8px;">${tagsHtml}</div>` : ""}
${trainedWordsHtml ? `<div style="margin-bottom:10px;"><div style="font-weight:600;font-size:12px;margin-bottom:4px;">${t("civitaiTriggerWords")}</div>${trainedWordsHtml}</div>` : ""}
${info.description ? `<div style="font-size:12px;color:var(--wfm-text-secondary);line-height:1.5;max-height:120px;overflow-y:auto;">${info.description}</div>` : ""}
${info.description ? `<div style="font-size:12px;color:var(--wfm-text-secondary);line-height:1.5;max-height:120px;overflow-y:auto;">${sanitizeHtml(info.description)}</div>` : ""}
<div style="margin-top:10px;">
<button class="wfm-btn wfm-btn-sm" id="wfm-civitai-refresh-btn">${t("civitaiRefresh")}</button>
</div>
+2 -1
View File
@@ -3,6 +3,7 @@
*/
import { state } from "./state.js";
import { safeHttpUrl } from "../util.js";
export function parseModelPath(fullName) {
const lastSlash = Math.max(fullName.lastIndexOf("/"), fullName.lastIndexOf("\\"));
@@ -68,7 +69,7 @@ export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
const meta = state.modelMetadata[modelName] || {};
const sha256 = meta.sha256;
const civitai = sha256 && state.civitaiCache[sha256];
const civitaiImg = civitai && civitai.images && civitai.images[0];
const civitaiImg = safeHttpUrl(civitai && civitai.images && civitai.images[0]);
if (civitaiImg) {
imgEl.onerror = () => {
imgEl.style.display = "none";
+51
View File
@@ -82,6 +82,57 @@ export function escapeHtml(s) {
.replace(/'/g, "&#x27;");
}
// http(s) 以外(javascript: / data: など)を拒否して安全なURLだけ返す。不正なら fallback
export function safeHttpUrl(url, fallback = "") {
// 絶対URLのhttp(s)のみ許可(相対URLだとComfyUI自身のURLへリクエストを送らせられるため不可)
const s = String(url ?? "").trim();
if (!/^https?:\/\/[^\s]+$/i.test(s)) return fallback;
try {
new URL(s);
return s;
} catch {
return fallback;
}
}
// 外部由来のHTML(CivitAIの説明文など)を許可リスト方式で無害化して返す。
// スクリプト・イベント属性・style・javascript:/data: URL・iframe等は除去する。
const _SAN_DROP = new Set(["script", "style", "iframe", "frame", "frameset", "object", "embed", "applet",
"link", "meta", "base", "form", "input", "button", "textarea", "select", "svg", "math", "template",
"noscript", "audio", "video", "source", "track", "canvas", "title", "head"]);
const _SAN_KEEP = new Set(["p", "br", "hr", "strong", "b", "em", "i", "u", "s", "del", "ins", "mark", "small",
"sub", "sup", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "code", "pre", "kbd",
"span", "div", "a", "img", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "details", "summary"]);
export function sanitizeHtml(html) {
if (html == null || html === "") return "";
const doc = new DOMParser().parseFromString(String(html), "text/html"); // 不活性ドキュメント(スクリプト非実行)
const walk = (node) => {
let out = "";
for (const child of node.childNodes) {
if (child.nodeType === 3) { // text
out += escapeHtml(child.nodeValue);
} else if (child.nodeType === 1) { // element
const tag = child.tagName.toLowerCase();
if (_SAN_DROP.has(tag)) continue;
if (!_SAN_KEEP.has(tag)) { out += walk(child); continue; } // 未知タグは中身だけ残す
if (tag === "br" || tag === "hr") { out += `<${tag}>`; continue; }
if (tag === "a") {
const href = safeHttpUrl(child.getAttribute("href") || "", "");
out += `<a${href ? ` href="${escapeHtml(href)}"` : ""} target="_blank" rel="noopener noreferrer">${walk(child)}</a>`;
} else if (tag === "img") {
const src = safeHttpUrl(child.getAttribute("src") || "", "");
if (src) out += `<img src="${escapeHtml(src)}" alt="${escapeHtml(child.getAttribute("alt") || "")}" loading="lazy" style="max-width:100%;">`;
} else {
out += `<${tag}>${walk(child)}</${tag}>`;
}
}
}
return out;
};
return walk(doc.body);
}
// localStorage からJSONを安全に読む(不正JSON・未設定時はfallback)
export function readJsonStorage(key, fallback = {}) {
try {