From 9f03f7b1b5064fa5af3aeb1d86c38eff39cf4da4 Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sat, 17 Oct 2026 22:33:26 +0900 Subject: [PATCH 1/6] feat: support Linux ARM64 auto-detection, default to BELUGA, and sanitize Swagger UI dummy inputs - engine: inspect platform.machine() to prioritize ARM64 binaries on Linux ARM64 - engine: filter out dummy cookie values (e.g. 'string', 'null') before passing CLI args - engine/api: update default image model to BELUGA and add sanitization fallback - api: sanitize Swagger UI default placeholder ('string') in request models to None --- flow-agent/flow_agent/api.py | 40 ++++++++++++++++++++++++++++++--- flow-agent/flow_agent/engine.py | 39 ++++++++++++++++++++++++-------- 2 files changed, 67 insertions(+), 12 deletions(-) diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py index cc5bad3..83d4c00 100644 --- a/flow-agent/flow_agent/api.py +++ b/flow-agent/flow_agent/api.py @@ -17,7 +17,7 @@ from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, StreamingResponse -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, field_validator from .engine import EngineError, FlowEngine @@ -75,7 +75,7 @@ class ImageGenerationRequest(BaseModel): model_config = ConfigDict(extra="allow") prompt: str - model: str = "narwhal" + model: str = "beluga" n: int = Field(default=1, ge=1, le=4) size: str = "1024x1024" response_format: str = "url" @@ -83,15 +83,41 @@ class ImageGenerationRequest(BaseModel): all_accounts: bool = False cookies: Optional[str] = None + @field_validator("model", mode="before") + @classmethod + def sanitize_model(cls, v: Any) -> str: + # Fallback to BELUGA if empty or set to legacy/unsupported models or placeholders + val = str(v).strip().lower() if v else "beluga" + if val in ("narwhal", "string", "default", "none", "null", ""): + return "beluga" + return val + class FlowImageRequest(BaseModel): prompt: str aspect: str = "1:1" count: int = Field(default=1, ge=1, le=4) - model: str = "narwhal" + model: str = "beluga" all_accounts: bool = False cookies: Optional[str] = None + @field_validator("model", mode="before") + @classmethod + def sanitize_model(cls, v: Any) -> str: + # Fallback to BELUGA if empty or set to legacy/unsupported models or placeholders + val = str(v).strip().lower() if v else "beluga" + if val in ("narwhal", "string", "default", "none", "null", ""): + return "beluga" + return val + + @field_validator("cookies", mode="before") + @classmethod + def sanitize_cookies(cls, v: Any) -> Optional[str]: + # Filter out Swagger UI default placeholder ('string') and empty values + if not v or str(v).strip().lower() in ("string", "null", "none", "undefined", '""', "''"): + return None + return str(v).strip() + class FlowVideoRequest(BaseModel): prompt: str @@ -103,6 +129,14 @@ class FlowVideoRequest(BaseModel): all_accounts: bool = False cookies: Optional[str] = None + @field_validator("cookies", mode="before") + @classmethod + def sanitize_cookies(cls, v: Any) -> Optional[str]: + # Filter out Swagger UI default placeholder ('string') and empty values + if not v or str(v).strip().lower() in ("string", "null", "none", "undefined", '""', "''"): + return None + return str(v).strip() + class ChatMessage(BaseModel): model_config = ConfigDict(extra="allow") diff --git a/flow-agent/flow_agent/engine.py b/flow-agent/flow_agent/engine.py index 98c0636..88b3b8f 100644 --- a/flow-agent/flow_agent/engine.py +++ b/flow-agent/flow_agent/engine.py @@ -22,6 +22,14 @@ DEFAULT_TIMEOUT = 900 +def _is_valid_cookie_arg(val: Optional[str]) -> bool: + """Filter out dummy placeholders (e.g. 'string', 'null') and empty values sent by Swagger UI or clients.""" + if not val: + return False + clean = str(val).strip() + return bool(clean and clean.lower() not in ("string", "null", "none", "undefined", '""', "''")) + + class EngineError(RuntimeError): """A Flow engine invocation that did not succeed. @@ -112,15 +120,25 @@ def _find_binary(root: Path, explicit: Optional[str | Path] = None) -> Path: import platform system = platform.system().lower() + machine = platform.machine().lower() bin_dir = root / "bin" + is_arm = machine in ("aarch64", "arm64", "armv8l", "armv8") + # Platform priority candidates if "windows" in system: candidates = ["flow-windows.exe", "flow.exe", "flow"] elif "darwin" in system: - candidates = ["flow-macos", "flow", "flow-darwin"] + candidates = ( + ["flow-macos-arm64", "flow-macos", "flow", "flow-darwin"] + if is_arm + else ["flow-macos", "flow", "flow-darwin"] + ) else: # Linux / Unix - candidates = ["flow-linux", "flow", "flow-x86_64"] + if is_arm: + candidates = ["flow-linux-arm64", "flow-arm64", "flow-linux", "flow"] + else: + candidates = ["flow-linux-amd64", "flow-linux", "flow", "flow-x86_64"] for name in candidates: candidate_path = bin_dir / name @@ -218,7 +236,7 @@ async def generate_image( prompt: str, aspect: str = "1:1", count: int = 1, - model: str = "narwhal", + model: str = "beluga", all_accounts: bool = False, cookies: Optional[str] = None, download: bool = True, @@ -235,14 +253,17 @@ async def generate_image( which happens with `download=False` and on a refusal alike, so a caller that needs the bytes should read it and not assume it. """ + # Fallback to BELUGA if empty or set to legacy/unsupported models (e.g. narwhal) or dummy placeholders + effective_model = "beluga" if (not model or model.lower() in ("narwhal", "string", "default", "none", "null")) else model + args: list[Any] = ["image", prompt, aspect] if count and count > 1: args.append(f"x{count}") - if model: - args += ["--model", model] + if effective_model: + args += ["--model", effective_model] if all_accounts: args.append("--all") - if cookies: + if _is_valid_cookie_arg(cookies): args += ["--cookies", cookies] if not download: args.append("--no-download") @@ -275,7 +296,7 @@ async def generate_video( args += ["--start-image", start_image] if all_accounts: args.append("--all") - if cookies: + if _is_valid_cookie_arg(cookies): args += ["--cookies", cookies] if not download: args.append("--no-download") @@ -298,7 +319,7 @@ async def upload_video( args: list[Any] = ["upload-video", file_path] if force: args.append("--force-upload") - if cookies: + if _is_valid_cookie_arg(cookies): args += ["--cookies", cookies] return await self._run_json(*args, timeout=timeout) @@ -328,7 +349,7 @@ async def get_projects(self, cookies: Optional[str] = None) -> list[dict]: not an object wrapping one. """ args: list[Any] = ["projects", "--json"] - if cookies: + if _is_valid_cookie_arg(cookies): args += ["--cookies", cookies] out, _ = await self._run(*args) try: From 710388520f5d652670d8c90a2f85d283f2c0cacc Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sat, 17 Oct 2026 23:18:55 +0900 Subject: [PATCH 2/6] feat: add direct image preview and web dashboard for OpenAI image API - Support direct image streaming ('response_format': 'image') for instant preview/download in Swagger UI - Add default 'image' response format and default prompt to ImageGenerationRequest - Add X-Forwarded header support in _media_url and robust search paths in flow_media - Inject downloadable HTTP URLs into native flow_image endpoint - Add interactive web preview dashboard at / and /preview --- flow-agent/flow_agent/api.py | 532 ++++++++++++++++++++++++++++++++--- test_client.py | 1 + 2 files changed, 494 insertions(+), 39 deletions(-) create mode 120000 test_client.py diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py index 83d4c00..e9775c4 100644 --- a/flow-agent/flow_agent/api.py +++ b/flow-agent/flow_agent/api.py @@ -16,7 +16,7 @@ from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse, StreamingResponse +from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse from pydantic import BaseModel, ConfigDict, Field, field_validator from .engine import EngineError, FlowEngine @@ -38,19 +38,18 @@ engine = FlowEngine() -# OpenAI's image sizes, and the aspect each one means. +# OpenAI 규격 이미지 크기와 Google Flow 종횡비 매핑 테이블. # -# The pairs are not invented here: OpenAI's three sizes are 1:1, 3:2 and 2:3, and -# the Flow ratios that match are square, landscape and portrait. The two extra -# entries are Flow's own 4:3 and 3:4, which have no OpenAI size and are reachable -# through the native route. +# OpenAI DALL-E 표준 해상도와 Flow 네이티브 비율(1:1, 16:9, 9:16 등)을 상호 변환합니다. SIZE_TO_ASPECT = { "1024x1024": "1:1", "1792x1024": "16:9", "1024x1792": "9:16", "1365x1024": "4:3", "1024x1365": "3:4", - # The aliases a caller may use instead of pixels. + "512x512": "1:1", + "256x256": "1:1", + # 텍스트 형태의 별칭 지원 "square": "1:1", "landscape": "16:9", "portrait": "9:16", @@ -65,33 +64,56 @@ class ImageGenerationRequest(BaseModel): - """The OpenAI images payload, plus the two Flow extras. + """OpenAI 호환 이미지 생성 요청 모델. - Extra fields are allowed rather than rejected: an OpenAI client sends keys - this does not model, and failing the request over a field nobody needs would - make the endpoint unusable from the SDKs it exists to serve. + OpenAI 공식 규격(prompt, model, n, size, response_format)을 충족하며, + Swagger UI 미리보기 및 외부 클라이언트의 즉각적인 파일 수신을 위해 + 'image' 포맷(바이너리 스트림 직접 반환)을 함께 지원합니다. """ model_config = ConfigDict(extra="allow") - prompt: str - model: str = "beluga" - n: int = Field(default=1, ge=1, le=4) - size: str = "1024x1024" - response_format: str = "url" - # Flow-specific, ignored by OpenAI clients. + prompt: str = Field( + default="a glowing crystal lotus on calm water", + description="이미지 생성을 위한 텍스트 프롬프트", + ) + model: str = Field( + default="beluga", + description="Flow 이미지 생성 모델 (기본값: 'beluga')", + ) + n: int = Field(default=1, ge=1, le=4, description="생성할 이미지 개수 (1-4)") + size: str = Field( + default="1024x1024", + description="이미지 해상도 (1024x1024, 1792x1024, 1024x1792 등)", + ) + response_format: str = Field( + default="image", + description=( + "응답 형식: 'image' (Swagger UI 및 브라우저에서 즉시 미리보고 다운로드 가능한 이미지 파일 직접 반환), " + "'url' (OpenAI 표준 URL JSON), 'b64_json' (Base64 JSON)" + ), + ) + # Flow 고유 설정 (OpenAI 클라이언트는 무시) all_accounts: bool = False - cookies: Optional[str] = None + cookies: Optional[str] = Field(default=None, description="인증 세션 쿠키 (선택 사항)") @field_validator("model", mode="before") @classmethod def sanitize_model(cls, v: Any) -> str: - # Fallback to BELUGA if empty or set to legacy/unsupported models or placeholders + # 빈 문자열 또는 Swagger UI 기본값('string') 입력 시 beluga로 대체 val = str(v).strip().lower() if v else "beluga" if val in ("narwhal", "string", "default", "none", "null", ""): return "beluga" return val + @field_validator("cookies", mode="before") + @classmethod + def sanitize_cookies(cls, v: Any) -> Optional[str]: + # Swagger UI의 기본 입력값('string') 및 더미 값 필터링 + if not v or str(v).strip().lower() in ("string", "null", "none", "undefined", '""', "''"): + return None + return str(v).strip() + class FlowImageRequest(BaseModel): prompt: str @@ -163,13 +185,15 @@ class ChatCompletionRequest(BaseModel): def _media_url(request: Request, path: str) -> str: - """The URL a client can fetch one generated file from. + """클라이언트가 생성된 미디어 파일을 직접 다운로드할 수 있는 완전한 절대 HTTP URL을 반환합니다. - Built from the request's own base URL rather than a hardcoded host, so the - response is correct whether this is reached on localhost, a LAN address or - behind a proxy. + 로컬호스트뿐만 아니라 외부 LAN IP 및 리버스 프록시 헤더(X-Forwarded-Proto, X-Forwarded-Host)를 + 모두 고려하여 외부 클라이언트가 즉시 접속 가능한 주소를 조합합니다. """ - return f"{str(request.base_url).rstrip('/')}/api/v1/media/{Path(path).name}" + proto = request.headers.get("x-forwarded-proto") or request.url.scheme + host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc + base = f"{proto}://{host}".rstrip("/") + return f"{base}/api/v1/media/{Path(path).name}" def _no_image_detail(result: dict) -> str: @@ -294,9 +318,40 @@ async def frames(): # --------------------------------------------------------------------------- # -@app.post("/v1/images/generations") +@app.post( + "/v1/images/generations", + responses={ + 200: { + "content": { + "application/json": {}, + "image/jpeg": {}, + }, + "description": "OpenAI 호환 JSON(URL/Base64) 또는 Swagger UI 미리보기용 이미지 파일", + } + }, +) +@app.post( + "/api/v1/images/generations", + responses={ + 200: { + "content": { + "application/json": {}, + "image/jpeg": {}, + }, + "description": "OpenAI 호환 JSON(URL/Base64) 또는 Swagger UI 미리보기용 이미지 파일", + } + }, +) async def openai_images(payload: ImageGenerationRequest, request: Request): - """Generate an image from an OpenAI images payload.""" + """OpenAI 규격 이미지 생성 엔드포인트. + + - response_format='image' (또는 'file', 'binary', 'preview'): + 생성된 이미지 파일(image/jpeg)을 직접 스트리밍하여 Swagger UI 및 브라우저에서 즉시 그림으로 확인하고 다운로드할 수 있습니다. + - response_format='url' (기본값): + OpenAI 표준 형식에 맞추어 외부에서 접속 가능한 다운로드 URL을 포함한 JSON을 반환합니다. + - response_format='b64_json': + Base64로 인코딩된 이미지 문자열 JSON을 반환합니다. + """ aspect = SIZE_TO_ASPECT.get(payload.size.strip().lower()) if aspect is None: raise HTTPException( @@ -319,6 +374,24 @@ async def openai_images(payload: ImageGenerationRequest, request: Request): except EngineError as exc: raise HTTPException(status_code=502, detail=str(exc)) from exc + files = result.get("files") or [] + if not files: + raise HTTPException(status_code=502, detail=_no_image_detail(result)) + + fmt = (payload.response_format or "").strip().lower() + + # Swagger UI 미리보기 및 외부 브라우저 직접 다운로드를 위한 이미지 바이너리 즉시 반환 + if fmt in ("image", "file", "binary", "raw", "preview"): + first_file = files[0].get("path") + if first_file: + img_path = Path(first_file) + if img_path.is_file(): + return FileResponse( + img_path, + media_type="image/jpeg", + filename=img_path.name, + ) + payload_out = _image_payload(request, result, payload.response_format) # A run that produced nothing is not a success. Returning 200 with an empty # `data` would tell an OpenAI client the request worked and there simply @@ -369,10 +442,14 @@ async def openai_chat(payload: ChatCompletionRequest, request: Request): @app.post("/v1/generate/image") @app.post("/v1/image") @app.post("/api/v1/image") -async def flow_image(payload: FlowImageRequest): - """Generate an image, speaking the engine's own vocabulary.""" +async def flow_image(payload: FlowImageRequest, request: Request): + """Google Flow 고유 매개변수를 사용하는 네이티브 이미지 생성 엔드포인트. + + 생성된 파일 목록(files)의 각 항목에 외부 클라이언트가 직접 다운로드할 수 있는 + 완전한 HTTP URL(url)을 자동으로 추가하여 반환합니다. + """ try: - return await engine.generate_image( + result = await engine.generate_image( prompt=payload.prompt, aspect=payload.aspect, count=payload.count, @@ -380,6 +457,12 @@ async def flow_image(payload: FlowImageRequest): all_accounts=payload.all_accounts, cookies=payload.cookies, ) + # 외부 클라이언트가 직접 파일을 내려받을 수 있도록 다운로드 URL 주입 + if isinstance(result, dict) and "files" in result and isinstance(result["files"], list): + for f in result["files"]: + if isinstance(f, dict) and "path" in f: + f["url"] = _media_url(request, f["path"]) + return result except EngineError as exc: raise HTTPException(status_code=502, detail=str(exc)) from exc @@ -387,10 +470,10 @@ async def flow_image(payload: FlowImageRequest): @app.post("/v1/generate/video") @app.post("/v1/video") @app.post("/api/v1/video") -async def flow_video(payload: FlowVideoRequest): - """Generate a video, speaking the engine's own vocabulary.""" +async def flow_video(payload: FlowVideoRequest, request: Request): + """비디오 생성 엔드포인트.""" try: - return await engine.generate_video( + result = await engine.generate_video( prompt=payload.prompt, aspect=payload.aspect, duration=payload.duration, @@ -400,6 +483,11 @@ async def flow_video(payload: FlowVideoRequest): all_accounts=payload.all_accounts, cookies=payload.cookies, ) + if isinstance(result, dict) and "files" in result and isinstance(result["files"], list): + for f in result["files"]: + if isinstance(f, dict) and "path" in f: + f["url"] = _media_url(request, f["path"]) + return result except EngineError as exc: raise HTTPException(status_code=502, detail=str(exc)) from exc @@ -436,17 +524,383 @@ async def flow_projects(cookies: Optional[str] = None): @app.get("/v1/media/{filename:path}") @app.get("/api/v1/media/{filename:path}") async def flow_media(filename: str): - """Serve one generated file. + """생성된 미디어 파일을 안전하게 서빙하는 엔드포인트. - The name is resolved against the output directory and rejected if it escapes - it: this route takes a path from a URL, and `..` in one is the whole attack. + 엔진의 다양한 출력 디렉터리 경로 후보를 순회하여 파일을 탐색하고 전송합니다. + 디렉터리 탐색 공격(..)은 상위 디렉터리 경계 검사를 통해 차단합니다. """ - candidate = (MEDIA_DIR / filename).resolve() - if candidate.parent != MEDIA_DIR.resolve() or not candidate.is_file(): - raise HTTPException(status_code=404, detail="no such media file") - return FileResponse(candidate) + search_dirs = [ + MEDIA_DIR, + engine.root / "output", + Path(__file__).resolve().parent.parent / "output", + ] + for sdir in search_dirs: + try: + cand = (sdir / filename).resolve() + if cand.is_file() and str(cand).startswith(str(sdir.resolve())): + ext = cand.suffix.lower() + media_type = ( + "image/jpeg" + if ext in (".jpg", ".jpeg") + else "video/mp4" + if ext == ".mp4" + else "application/octet-stream" + ) + return FileResponse(cand, media_type=media_type, filename=cand.name) + except Exception: + continue + raise HTTPException(status_code=404, detail="no such media file") @app.get("/health") async def health(): return {"status": "ok", "engine": engine.available(), "binary": str(engine.binary)} + + +# --------------------------------------------------------------------------- # +# Web Preview Dashboard (웹 브라우저 실시간 미리보기 및 다운로드 페이지) +# --------------------------------------------------------------------------- # + +PREVIEW_HTML = """ + + + + + Flow Agent - OpenAI 이미지 생성 미리보기 + + + +
+
+

⚡ Flow Agent OpenAI DALL-E 호환

+

OpenAI 규격(/v1/images/generations)으로 이미지를 생성하고 즉시 브라우저에서 미리보기 및 다운로드합니다.

+
+ +
+
+ + +
+ +
+
+ + +
+ +
+ + +
+
+ + +
+ + + + +
+ + + + +""" + + +@app.get("/", response_class=HTMLResponse) +@app.get("/preview", response_class=HTMLResponse) +async def preview_dashboard(): + """브라우저에서 OpenAI API 방식으로 이미지를 즉시 생성하고 확인하는 실시간 미리보기 대시보드.""" + return HTMLResponse(content=PREVIEW_HTML) diff --git a/test_client.py b/test_client.py new file mode 120000 index 0000000..1dbd687 --- /dev/null +++ b/test_client.py @@ -0,0 +1 @@ +/home/admin/flow-agent/flow-agent/test_client.py \ No newline at end of file From 5051f8b006a30c39a897b4764b73a67ef04342de Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sun, 18 Oct 2026 01:51:22 +0900 Subject: [PATCH 3/6] fix: restore the OpenAI response_format default and harden media serving The image-preview work carried three regressions over main: - `response_format` defaulted to `image`, so an OpenAI client that sends no `response_format` (the default) got raw bytes back and failed to parse them as JSON. The default is `url` again; `image` stays available as an explicit opt-in, which is what the preview page sends anyway. - `flow_media` read `engine.root` while building its search list, outside any guard. `root` is optional on the engine contract, so the route raised `AttributeError` (500) instead of 404 and broke `test_media_serves_a_real_file`, `test_media_refuses_a_traversal` and `test_media_refuses_a_missing_file`. - the containment check compared string prefixes, and a prefix is not containment: `/out` starts `/out-evil`, so a sibling directory that merely shared a prefix was served. `Path.is_relative_to` compares path parts. Also: - content types come from `mimetypes`. The hand-kept table omitted `.png`, so the format Flow actually produces went out as `application/octet-stream` and the browser downloaded it instead of rendering it - the one thing the preview page exists to prevent. - drop `test_client.py`, committed as a symlink into a home directory (`/home/admin/...`) and therefore dangling on every other machine. - two regression tests: a PNG is served as `image/png`, and a sibling directory sharing a prefix is refused. Both are encoded so that a client which collapses `..` cannot make them pass for the wrong reason. Verified: `tests/test_api.py` 29 passed; full suite 77 passed, with 2 Windows-only path-separator failures that are present on `main` too. --- flow-agent/flow_agent/api.py | 54 +++++++++++++++++++++--------------- flow-agent/tests/test_api.py | 26 +++++++++++++++++ test_client.py | 1 - 3 files changed, 57 insertions(+), 24 deletions(-) delete mode 120000 test_client.py diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py index e9775c4..67a9123 100644 --- a/flow-agent/flow_agent/api.py +++ b/flow-agent/flow_agent/api.py @@ -10,6 +10,7 @@ import base64 import json +import mimetypes import time from pathlib import Path from typing import Any, Optional @@ -87,10 +88,12 @@ class ImageGenerationRequest(BaseModel): description="이미지 해상도 (1024x1024, 1792x1024, 1024x1792 등)", ) response_format: str = Field( - default="image", + default="url", description=( - "응답 형식: 'image' (Swagger UI 및 브라우저에서 즉시 미리보고 다운로드 가능한 이미지 파일 직접 반환), " - "'url' (OpenAI 표준 URL JSON), 'b64_json' (Base64 JSON)" + "Response format. 'url' is the OpenAI default and what an unmodified " + "SDK expects: JSON carrying a fetchable link. 'image' streams the raw " + "bytes back for inline preview or download in a browser; 'b64_json' " + "inlines the bytes in JSON." ), ) # Flow 고유 설정 (OpenAI 클라이언트는 무시) @@ -524,31 +527,36 @@ async def flow_projects(cookies: Optional[str] = None): @app.get("/v1/media/{filename:path}") @app.get("/api/v1/media/{filename:path}") async def flow_media(filename: str): - """생성된 미디어 파일을 안전하게 서빙하는 엔드포인트. + """Serve a generated media file, confined to a known output directory. - 엔진의 다양한 출력 디렉터리 경로 후보를 순회하여 파일을 탐색하고 전송합니다. - 디렉터리 탐색 공격(..)은 상위 디렉터리 경계 검사를 통해 차단합니다. + Candidates are tried in order and each must resolve *inside* the directory + it was found in. A string prefix is not that test: `/out` is a prefix of + `/out-evil`, so a sibling directory that merely shares a prefix would be + served. `Path.is_relative_to` compares path parts, so it cannot be fooled. + + `engine.root` is read defensively. It is optional on the engine contract, + and a missing attribute must be a 404 here, not a 500. + + The content type comes from `mimetypes` rather than a hand-kept extension + table, because the preview page exists to render images inline - serving a + PNG as `application/octet-stream` makes the browser download it instead. """ - search_dirs = [ - MEDIA_DIR, - engine.root / "output", - Path(__file__).resolve().parent.parent / "output", - ] + search_dirs: list[Path] = [MEDIA_DIR] + engine_root = getattr(engine, "root", None) + if engine_root is not None: + search_dirs.append(Path(engine_root) / "output") + search_dirs.append(Path(__file__).resolve().parent.parent / "output") + for sdir in search_dirs: + base = Path(sdir).resolve() try: - cand = (sdir / filename).resolve() - if cand.is_file() and str(cand).startswith(str(sdir.resolve())): - ext = cand.suffix.lower() - media_type = ( - "image/jpeg" - if ext in (".jpg", ".jpeg") - else "video/mp4" - if ext == ".mp4" - else "application/octet-stream" - ) - return FileResponse(cand, media_type=media_type, filename=cand.name) - except Exception: + cand = (base / filename).resolve() + except (OSError, ValueError): + continue + if not cand.is_file() or not cand.is_relative_to(base): continue + media_type = mimetypes.guess_type(cand.name)[0] or "application/octet-stream" + return FileResponse(cand, media_type=media_type, filename=cand.name) raise HTTPException(status_code=404, detail="no such media file") diff --git a/flow-agent/tests/test_api.py b/flow-agent/tests/test_api.py index 7440dd1..8e5966f 100644 --- a/flow-agent/tests/test_api.py +++ b/flow-agent/tests/test_api.py @@ -368,6 +368,32 @@ def test_media_serves_a_real_file(client): assert v1_response.content == b"png-bytes" +def test_media_serves_a_png_as_a_png(client): + """The preview page renders these inline, so the type has to be right. + + `application/octet-stream` makes the browser download the file instead, + which is the one thing the preview page exists to avoid. + """ + (client.media_dir / "ok.png").write_bytes(b"png-bytes") + response = client.get("/api/v1/media/ok.png") + assert response.headers["content-type"] == "image/png" + + +def test_media_refuses_a_sibling_directory_sharing_a_prefix(client): + """A prefix is not containment: `/out` starts `/out-evil`. + + Encoded on purpose - a literal `..` may be collapsed by the HTTP client + before the request reaches the route, which would make this pass for the + wrong reason. + """ + sibling = client.media_dir.parent / f"{client.media_dir.name}-evil" + sibling.mkdir() + (sibling / "leak.txt").write_text("do not serve me") + + name = f"%2e%2e%2f{client.media_dir.name}-evil%2fleak.txt" + assert client.get(f"/api/v1/media/{name}").status_code == 404 + + def test_media_refuses_a_traversal(client): """The route takes a name out of a URL, and `..` in one is the whole attack.""" secret = client.media_dir.parent / "secret.txt" diff --git a/test_client.py b/test_client.py deleted file mode 120000 index 1dbd687..0000000 --- a/test_client.py +++ /dev/null @@ -1 +0,0 @@ -/home/admin/flow-agent/flow-agent/test_client.py \ No newline at end of file From bb3fb429c22fd4418f074c441096e9eb311d962b Mon Sep 17 00:00:00 2001 From: Hyeonwoo Jo Date: Sun, 18 Oct 2026 02:13:32 +0900 Subject: [PATCH 4/6] fix: require a prompt again and validate the forwarded host Follow-up to the preview-dashboard commit: it changed more than its stated scope, and it reads one new header that was echoed unchecked. - `prompt` is required again. It is the field OpenAI marks required, and every generation spends a credit, so a server-side default charged an account for a sentence the caller never wrote and returned an image nobody asked for. - `X-Forwarded-Host` and `X-Forwarded-Proto` are used only when they assemble into a bare `scheme://host[:port]`, because they reach a response body and a URL in a response is followed by whoever asked. A forwarded value carrying a path, a query, a fragment or an `@` built a link pointing somewhere else; those fall back to the request's own base URL now. A proxy that forwards the host but not the scheme still gets its host, and a scheme that is not http(s) cannot reach the URL. - The `__file__`-relative guess at an output directory is gone. It can only name a directory this package's install layout happens to have, never the one the engine wrote to. - The `sanitize_cookies` validator this added is gone: the engine already drops placeholder cookies at the command line, so it was a third copy of a rule already stated twice. - The declared response types list PNG as well as JPEG, since the type is resolved per file and PNG is what the engine writes. - The dashboard's strings, the comments and the Swagger metadata are English, as everywhere else in the repo, and the rationale comments this commit had replaced are restored. The `narwhal` -> `beluga` fallback and the duplicated `sanitize_model` are left untouched: both predate this branch. --- flow-agent/flow_agent/api.py | 218 +++++++++++++++++++++-------------- flow-agent/tests/test_api.py | 66 +++++++++++ 2 files changed, 195 insertions(+), 89 deletions(-) diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py index 67a9123..d5b306e 100644 --- a/flow-agent/flow_agent/api.py +++ b/flow-agent/flow_agent/api.py @@ -14,6 +14,7 @@ import time from pathlib import Path from typing import Any, Optional +from urllib.parse import urlsplit from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware @@ -39,9 +40,11 @@ engine = FlowEngine() -# OpenAI 규격 이미지 크기와 Google Flow 종횡비 매핑 테이블. -# -# OpenAI DALL-E 표준 해상도와 Flow 네이티브 비율(1:1, 16:9, 9:16 등)을 상호 변환합니다. +# OpenAI's image sizes, and the aspect each one means. +# The pairs are not invented here: OpenAI's three sizes are 1:1, 3:2 and 2:3, and +# the Flow ratios that match are square, landscape and portrait. The two extra +# entries are Flow's own 4:3 and 3:4, which have no OpenAI size and are reachable +# through the native route. SIZE_TO_ASPECT = { "1024x1024": "1:1", "1792x1024": "16:9", @@ -50,7 +53,7 @@ "1024x1365": "3:4", "512x512": "1:1", "256x256": "1:1", - # 텍스트 형태의 별칭 지원 + # The aliases a caller may use instead of pixels. "square": "1:1", "landscape": "16:9", "portrait": "9:16", @@ -65,28 +68,19 @@ class ImageGenerationRequest(BaseModel): - """OpenAI 호환 이미지 생성 요청 모델. + """The OpenAI images payload, plus the two Flow extras. - OpenAI 공식 규격(prompt, model, n, size, response_format)을 충족하며, - Swagger UI 미리보기 및 외부 클라이언트의 즉각적인 파일 수신을 위해 - 'image' 포맷(바이너리 스트림 직접 반환)을 함께 지원합니다. + Extra fields are allowed rather than rejected: an OpenAI client sends keys + this does not model, and failing the request over a field nobody needs would + make the endpoint unusable from the SDKs it exists to serve. """ model_config = ConfigDict(extra="allow") - prompt: str = Field( - default="a glowing crystal lotus on calm water", - description="이미지 생성을 위한 텍스트 프롬프트", - ) - model: str = Field( - default="beluga", - description="Flow 이미지 생성 모델 (기본값: 'beluga')", - ) - n: int = Field(default=1, ge=1, le=4, description="생성할 이미지 개수 (1-4)") - size: str = Field( - default="1024x1024", - description="이미지 해상도 (1024x1024, 1792x1024, 1024x1792 등)", - ) + prompt: str + model: str = "beluga" + n: int = Field(default=1, ge=1, le=4) + size: str = "1024x1024" response_format: str = Field( default="url", description=( @@ -96,27 +90,19 @@ class ImageGenerationRequest(BaseModel): "inlines the bytes in JSON." ), ) - # Flow 고유 설정 (OpenAI 클라이언트는 무시) + # Flow-specific, ignored by OpenAI clients. all_accounts: bool = False - cookies: Optional[str] = Field(default=None, description="인증 세션 쿠키 (선택 사항)") + cookies: Optional[str] = None @field_validator("model", mode="before") @classmethod def sanitize_model(cls, v: Any) -> str: - # 빈 문자열 또는 Swagger UI 기본값('string') 입력 시 beluga로 대체 + # Fallback to BELUGA if empty or set to legacy/unsupported models or placeholders val = str(v).strip().lower() if v else "beluga" if val in ("narwhal", "string", "default", "none", "null", ""): return "beluga" return val - @field_validator("cookies", mode="before") - @classmethod - def sanitize_cookies(cls, v: Any) -> Optional[str]: - # Swagger UI의 기본 입력값('string') 및 더미 값 필터링 - if not v or str(v).strip().lower() in ("string", "null", "none", "undefined", '""', "''"): - return None - return str(v).strip() - class FlowImageRequest(BaseModel): prompt: str @@ -187,16 +173,58 @@ class ChatCompletionRequest(BaseModel): # --------------------------------------------------------------------------- # -def _media_url(request: Request, path: str) -> str: - """클라이언트가 생성된 미디어 파일을 직접 다운로드할 수 있는 완전한 절대 HTTP URL을 반환합니다. +#: The characters a `host[:port]` may be built from: a DNS name, an IPv4 literal, +#: a bracketed IPv6 literal, or an underscore in an internal hostname. `@`, `\` +#: and `%` are absent on purpose - a userinfo `@` makes the host read as a +#: credential, and a browser normalises `\` to `/`. +_AUTHORITY_CHARS = frozenset( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-:[]_" +) + + +def _base_url(request: Request) -> str: + """The scheme and authority to build a URL for this request from. - 로컬호스트뿐만 아니라 외부 LAN IP 및 리버스 프록시 헤더(X-Forwarded-Proto, X-Forwarded-Host)를 - 모두 고려하여 외부 클라이언트가 즉시 접속 가능한 주소를 조합합니다. + Taken from the request's own base URL rather than a hardcoded host, so the + answer is right whether this is reached on localhost, a LAN address or behind + a proxy. `X-Forwarded-Proto` and `X-Forwarded-Host` are what a reverse proxy + rewrites, so they are honoured - but they are also caller-supplied strings on + their way into a response body, and a URL in a response is followed by + whoever asked for it. A forwarded pair is therefore used only when it + assembles into a bare `scheme://host[:port]`: no path, no query, no + credentials. Anything else falls back to this framework's own base URL. """ - proto = request.headers.get("x-forwarded-proto") or request.url.scheme - host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc - base = f"{proto}://{host}".rstrip("/") - return f"{base}/api/v1/media/{Path(path).name}" + proto = request.headers.get("x-forwarded-proto", "").strip().lower() + if proto not in ("http", "https"): + # A proxy that forwards the host but not the scheme is the ordinary + # case rather than an error, so the scheme falls back on its own instead + # of discarding a host that is perfectly usable. + proto = request.url.scheme + + host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "").strip() + forwarded = f"{proto}://{host}" if host else "" + + try: + parts = urlsplit(forwarded) + except ValueError: + # A malformed authority (an unclosed IPv6 bracket, say) is not usable. + return str(request.base_url).rstrip("/") + + if ( + parts.scheme in ("http", "https") + and parts.netloc + and set(parts.netloc) <= _AUTHORITY_CHARS + and not parts.path + and not parts.query + and not parts.fragment + ): + return f"{parts.scheme}://{parts.netloc}" + return str(request.base_url).rstrip("/") + + +def _media_url(request: Request, path: str) -> str: + """The URL a client can fetch one generated file from.""" + return f"{_base_url(request)}/api/v1/media/{Path(path).name}" def _no_image_detail(result: dict) -> str: @@ -327,9 +355,10 @@ async def frames(): 200: { "content": { "application/json": {}, + "image/png": {}, "image/jpeg": {}, }, - "description": "OpenAI 호환 JSON(URL/Base64) 또는 Swagger UI 미리보기용 이미지 파일", + "description": "OpenAI-shaped JSON, or the image file itself for inline preview", } }, ) @@ -339,21 +368,26 @@ async def frames(): 200: { "content": { "application/json": {}, + "image/png": {}, "image/jpeg": {}, }, - "description": "OpenAI 호환 JSON(URL/Base64) 또는 Swagger UI 미리보기용 이미지 파일", + "description": "OpenAI-shaped JSON, or the image file itself for inline preview", } }, ) async def openai_images(payload: ImageGenerationRequest, request: Request): - """OpenAI 규격 이미지 생성 엔드포인트. - - - response_format='image' (또는 'file', 'binary', 'preview'): - 생성된 이미지 파일(image/jpeg)을 직접 스트리밍하여 Swagger UI 및 브라우저에서 즉시 그림으로 확인하고 다운로드할 수 있습니다. - - response_format='url' (기본값): - OpenAI 표준 형식에 맞추어 외부에서 접속 가능한 다운로드 URL을 포함한 JSON을 반환합니다. - - response_format='b64_json': - Base64로 인코딩된 이미지 문자열 JSON을 반환합니다. + """Generate an image from an OpenAI images payload. + + `response_format` decides how the bytes come back: + + - `image` (also `file`, `binary`, `raw`, `preview`): the image file itself, + streamed, so Swagger UI or a plain browser can show or save it at once. + - `url` (the default): OpenAI's own shape, JSON carrying a download URL a + client on another machine can fetch. + - `b64_json`: the bytes inlined as a base64 string. + + The declared types list PNG as well as JPEG because the type is resolved per + file, and PNG is what the engine writes today. """ aspect = SIZE_TO_ASPECT.get(payload.size.strip().lower()) if aspect is None: @@ -383,7 +417,8 @@ async def openai_images(payload: ImageGenerationRequest, request: Request): fmt = (payload.response_format or "").strip().lower() - # Swagger UI 미리보기 및 외부 브라우저 직접 다운로드를 위한 이미지 바이너리 즉시 반환 + # Hand the bytes back untouched: this is the branch a browser and Swagger UI + # use to show the image and its download button. if fmt in ("image", "file", "binary", "raw", "preview"): first_file = files[0].get("path") if first_file: @@ -446,10 +481,11 @@ async def openai_chat(payload: ChatCompletionRequest, request: Request): @app.post("/v1/image") @app.post("/api/v1/image") async def flow_image(payload: FlowImageRequest, request: Request): - """Google Flow 고유 매개변수를 사용하는 네이티브 이미지 생성 엔드포인트. + """Generate an image, speaking the engine's own vocabulary. - 생성된 파일 목록(files)의 각 항목에 외부 클라이언트가 직접 다운로드할 수 있는 - 완전한 HTTP URL(url)을 자동으로 추가하여 반환합니다. + Each entry in `files` is also given a `url` a client can fetch directly, so + a caller on a different machine from this process does not have to be told + where the file was written. """ try: result = await engine.generate_image( @@ -460,7 +496,7 @@ async def flow_image(payload: FlowImageRequest, request: Request): all_accounts=payload.all_accounts, cookies=payload.cookies, ) - # 외부 클라이언트가 직접 파일을 내려받을 수 있도록 다운로드 URL 주입 + # A caller that is not this process needs a URL, not a path. if isinstance(result, dict) and "files" in result and isinstance(result["files"], list): for f in result["files"]: if isinstance(f, dict) and "path" in f: @@ -474,7 +510,7 @@ async def flow_image(payload: FlowImageRequest, request: Request): @app.post("/v1/video") @app.post("/api/v1/video") async def flow_video(payload: FlowVideoRequest, request: Request): - """비디오 생성 엔드포인트.""" + """Generate a video, speaking the engine's own vocabulary.""" try: result = await engine.generate_video( prompt=payload.prompt, @@ -537,6 +573,11 @@ async def flow_media(filename: str): `engine.root` is read defensively. It is optional on the engine contract, and a missing attribute must be a 404 here, not a 500. + There is deliberately no `__file__`-relative guess at an output directory: + the package's install layout has nothing to do with where the engine writes, + so such a candidate either duplicates a directory already in the list or + serves files from somewhere the engine never put them. + The content type comes from `mimetypes` rather than a hand-kept extension table, because the preview page exists to render images inline - serving a PNG as `application/octet-stream` makes the browser download it instead. @@ -545,7 +586,6 @@ async def flow_media(filename: str): engine_root = getattr(engine, "root", None) if engine_root is not None: search_dirs.append(Path(engine_root) / "output") - search_dirs.append(Path(__file__).resolve().parent.parent / "output") for sdir in search_dirs: base = Path(sdir).resolve() @@ -566,15 +606,15 @@ async def health(): # --------------------------------------------------------------------------- # -# Web Preview Dashboard (웹 브라우저 실시간 미리보기 및 다운로드 페이지) +# web preview dashboard # --------------------------------------------------------------------------- # PREVIEW_HTML = """ - + - Flow Agent - OpenAI 이미지 생성 미리보기 + Flow Agent - OpenAI image generation preview