Compare commits

...
2 Commits
Author SHA1 Message Date
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
10 changed files with 151 additions and 16 deletions
+1
View File
@@ -2,6 +2,7 @@
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.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: マルチトラック化(ビデオ/オーバーレイ/テキスト/オーディオ)
+24
View File
@@ -2,6 +2,30 @@
---
## 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イベントループ)
+1 -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.11-green)
## Features (tab -> feature names)
+1 -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.11-green)
## Screenshots
+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:
+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
+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.11"
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 {