From 5e2846ff72fef40aab4d91ea743c6247ee8b7381 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 7 Oct 2026 15:43:18 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EA=B3=B5=EC=9C=A0=EB=A5=BC=20=EB=B9=84?= =?UTF-8?q?=EC=9C=A8=20=EA=B3=A0=EB=A5=B4=EA=B8=B0=20+=20=EA=B3=B5?= =?UTF-8?q?=EC=9C=A0=ED=95=98=EA=B8=B0=20=ED=95=98=EB=82=98=EB=A1=9C=20?= =?UTF-8?q?=EC=A4=84=EC=9D=B4=EA=B3=A0=20=EC=9D=B4=EB=AF=B8=EC=A7=80?= =?UTF-8?q?=EC=97=90=20=ED=96=89=EC=82=AC=20=EC=82=AC=EC=A7=84=C2=B7?= =?UTF-8?q?=EC=9A=B0=EB=A6=AC=20=EC=A3=BC=EC=86=8C=20=EB=84=A3=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 공유 이미지 9:16·4:5·1:1, 위 로고·지역 날짜 / 카드 / 아래 주소 알약 (시안 A) - 2장 카드는 한 이미지에 묶음, 버튼만 빼고 링크(장소)는 남김 - 웹폰트는 카드 글자에 필요한 조각만 data URL 로 넣어 글꼴이 안 깨지게 - 문구 고르기·링크 복사 제거, 공유하기 한 번에 이미지 + 제목·주소 글 - 행사 사진은 백엔드 /v1/image 가 대신 받음 (IMAGE_PROXY_HOSTS 만 허용) - 공유 주소는 VITE_SITE_URL 하나로 --- .env.example | 3 + TODO.md | 5 + backend/config/settings.py | 6 + backend/router/router.py | 2 + backend/router/v1/image/__init__.py | 0 backend/router/v1/image/image.py | 22 +++ backend/services/external/image_proxy.py | 39 ++++ backend/tests/test_image_proxy.py | 93 ++++++++++ compose.yaml | 3 + frontend/Dockerfile | 2 + frontend/index.html | 2 + frontend/src/api/setup.ts | 1 + frontend/src/b/Post.tsx | 8 +- frontend/src/b/Sheets.tsx | 146 ++++++--------- frontend/src/b/WeekPage.tsx | 9 +- frontend/src/b/sheetContext.ts | 4 +- frontend/src/b/storyImage.ts | 222 ++++++++++++++++++++--- 17 files changed, 432 insertions(+), 135 deletions(-) create mode 100644 backend/router/v1/image/__init__.py create mode 100644 backend/router/v1/image/image.py create mode 100644 backend/services/external/image_proxy.py create mode 100644 backend/tests/test_image_proxy.py diff --git a/.env.example b/.env.example index 8c89672..d2dcd97 100644 --- a/.env.example +++ b/.env.example @@ -5,6 +5,7 @@ DATA_GO_KR_SERVICE_KEY= # 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다. TEAMS_WEBHOOK_URL= +IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr # ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다) DB_HOST=localhost @@ -29,3 +30,5 @@ PG_BIND= REDIS_BIND= # 프론트가 부를 API 주소. 비우면 같은 주소의 /v1 (nginx 가 backend 로 넘김) VITE_API_BASE_URL= +# 공유할 때 이미지·글에 나가는 우리 주소 (예: https://nalssigak.kr). 비우면 지금 보고 있는 주소 +VITE_SITE_URL= diff --git a/TODO.md b/TODO.md index 4ea5bf6..8cb45a2 100644 --- a/TODO.md +++ b/TODO.md @@ -98,3 +98,8 @@ | [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` | | [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` | | [ ] | 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 사진 기록·사용자 반응 등 후보 | 노을 탭 다시 기획 (10/7) | `backend/services/calc/sky_score.py` (`situation`) | +| [x] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 ``도 빼서 생김. 링크는 남기고 버튼만 빼야 함 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`keep`), `frontend/src/b/ui.tsx` (지도 링크) | +| [x] | 공유 이미지: 행사 사진은 백엔드 `/v1/image`(허용 호스트만)로 대신 받음 (사용자 결정). 행사 사진(한국관광공사·문화정보원)이 CORS 차단으로 하얗게 빠짐. 안: 백엔드가 사진을 대신 받아 주기 / 공유 때만 사진 대신 아이콘 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `backend` 이미지 응답 | +| [x] | 공유 이미지: 2장 카드는 한 이미지에 엇갈려 묶음 (사용자 결정). 여러 장 카드는 보고 있는 1장만 나감(주말 예보는 2번째 장 내용이 빠짐). 1장만 / 장마다 이미지 여러 장 / 2장을 한 이미지에 중 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `frontend/src/b/Post.tsx` (`share`) | +| [x] | 공유 이미지: 카드 아래 긴 제목이 한 줄 폭에 눌려 찌그러짐 — 두 줄 나눔 또는 말줄임 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`fillText`) | +| [x] | 공유 이미지: 카드 아래 제목을 빼고 주소 알약으로 바꿈 (시안 A, 사용자 결정). 카드 안 제목과 카드 아래 제목이 같아 두 번 보임. 아래 줄을 뺄지, 다른 말(지역·날짜)로 바꿀지 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` | diff --git a/backend/config/settings.py b/backend/config/settings.py index eb717d4..3b0ac98 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -28,6 +28,8 @@ class Settings(BaseSettings): data_go_kr_service_key: str = "" teams_webhook_url: str = "" + # 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분) + image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr" jwt_access_secret: str = "" jwt_refresh_secret: str = "" @@ -40,6 +42,10 @@ class Settings(BaseSettings): """인코딩 키를 넣어도 디코딩해 둔다. httpx 가 다시 인코딩하므로 이중 인코딩을 막는다.""" return unquote(v) if "%" in v else v + @property + def image_proxy_host_set(self) -> frozenset[str]: + return frozenset(h.strip().lower() for h in self.image_proxy_hosts.split(",") if h.strip()) + @property def db_url(self) -> str: return f"postgresql+asyncpg://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}" diff --git a/backend/router/router.py b/backend/router/router.py index 6598437..28316de 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -9,6 +9,7 @@ from common.database.db_session_manager import DB_SESSION_MNG from common.models.gmodel import Res_WebPacketProtocol from router.v1.auth.account import router as auth_router from router.v1.feed.feed import router as feed_router +from router.v1.image.image import router as image_router from router.v1.index.index import router as index_router from router.v1.reaction.reaction import router as reaction_router from router.v1.region.region import router as region_router @@ -41,6 +42,7 @@ app.include_router(feed_router) app.include_router(auth_router) app.include_router(reaction_router) app.include_router(watch_router) +app.include_router(image_router) class Res_Health(Res_WebPacketProtocol): diff --git a/backend/router/v1/image/__init__.py b/backend/router/v1/image/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/image/image.py b/backend/router/v1/image/image.py new file mode 100644 index 0000000..c93cdcf --- /dev/null +++ b/backend/router/v1/image/image.py @@ -0,0 +1,22 @@ +import httpx +from fastapi import APIRouter, HTTPException, Query +from fastapi.responses import Response + +from common.logger import LOG +from services.external.image_proxy import TIMEOUT_SEC, ImageFetchFailed, allowed, fetch_image + +router = APIRouter(prefix="/v1/image", tags=["image"]) + + +# 이미지 자체를 돌려주므로 다른 API 와 달리 실패는 HTTP 상태 코드로 알린다 +@router.get("", summary="행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)", responses={200: {"content": {"image/*": {}}}, 400: {}, 502: {}}) +async def get_image(url: str = Query(..., max_length=2048, description="원본 이미지 주소")) -> Response: + if not allowed(url): + raise HTTPException(status_code=400, detail="url not allowed") + try: + async with httpx.AsyncClient(timeout=TIMEOUT_SEC, headers={"User-Agent": "nalssigak-bot"}) as client: + data, ctype = await fetch_image(client, url) + except (ImageFetchFailed, httpx.HTTPError) as e: + LOG.warning(f"[image] fetch failed {url}: {e!r}") + raise HTTPException(status_code=502, detail="image fetch failed") from e + return Response(content=data, media_type=ctype, headers={"Cache-Control": "public, max-age=86400", "X-Content-Type-Options": "nosniff"}) diff --git a/backend/services/external/image_proxy.py b/backend/services/external/image_proxy.py new file mode 100644 index 0000000..f3ebb72 --- /dev/null +++ b/backend/services/external/image_proxy.py @@ -0,0 +1,39 @@ +from urllib.parse import urlsplit + +import httpx + +from config.settings import settings + +# 공유 이미지에 행사 사진을 그리려고 대신 받아 준다. 사진 서버가 브라우저가 픽셀을 읽는 것(CORS)을 막기 때문. 허용 호스트는 IMAGE_PROXY_HOSTS. +MAX_BYTES = 5 * 1024 * 1024 +TIMEOUT_SEC = 10.0 + + +class ImageFetchFailed(Exception): + pass + + +def allowed(url: str) -> bool: + """https, 허용한 호스트, 기본 포트, 계정 정보 없음일 때만.""" + try: + u = urlsplit(url) + port = u.port + except ValueError: + return False + return u.scheme == "https" and u.hostname in settings.image_proxy_host_set and port in (None, 443) and not u.username and not u.password + + +async def fetch_image(client: httpx.AsyncClient, url: str) -> tuple[bytes, str]: + """이미지 바이트와 content-type. 리다이렉트는 따라가지 않는다.""" + async with client.stream("GET", url, follow_redirects=False) as res: + if res.status_code != 200: + raise ImageFetchFailed(f"status {res.status_code}") + ctype = res.headers.get("content-type", "").split(";")[0].strip().lower() + if not ctype.startswith("image/") or ctype == "image/svg+xml": + raise ImageFetchFailed(f"content-type {ctype or '-'}") + buf = bytearray() + async for chunk in res.aiter_bytes(): + buf += chunk + if len(buf) > MAX_BYTES: + raise ImageFetchFailed("too large") + return bytes(buf), ctype diff --git a/backend/tests/test_image_proxy.py b/backend/tests/test_image_proxy.py new file mode 100644 index 0000000..6d61f55 --- /dev/null +++ b/backend/tests/test_image_proxy.py @@ -0,0 +1,93 @@ +import httpx +import pytest +from httpx import ASGITransport, AsyncClient + +from router.router import app +from services.external import image_proxy +from services.external.image_proxy import ImageFetchFailed, allowed, fetch_image + +OK_URL = "https://tong.visitkorea.or.kr/cms/resource/01/test_image.jpg" + + +@pytest.mark.parametrize("url,ok", [ + (OK_URL, True), + ("https://www.culture.go.kr/upload/test.jpg", True), + ("http://tong.visitkorea.or.kr/cms/a.jpg", False), + ("https://evil.example.com/a.jpg", False), + ("https://tong.visitkorea.or.kr.evil.example.com/a.jpg", False), + ("https://tong.visitkorea.or.kr:8443/a.jpg", False), + ("https://user:pw@tong.visitkorea.or.kr/a.jpg", False), + ("https://169.254.169.254/latest/meta-data", False), + ("not a url", False), +]) +def test_allowed(url, ok): + assert allowed(url) is ok + + +def _client(handler) -> httpx.AsyncClient: + return httpx.AsyncClient(transport=httpx.MockTransport(handler)) + + +@pytest.mark.anyio +async def test_fetch_image_returns_bytes_and_type(): + async with _client(lambda r: httpx.Response(200, content=b"\xff\xd8jpeg", headers={"content-type": "image/jpeg; charset=binary"})) as c: + assert await fetch_image(c, OK_URL) == (b"\xff\xd8jpeg", "image/jpeg") + + +@pytest.mark.anyio +@pytest.mark.parametrize("res", [ + httpx.Response(302, headers={"location": "https://evil.example.com/a.jpg"}), + httpx.Response(404), + httpx.Response(200, content=b"", headers={"content-type": "text/html"}), + httpx.Response(200, content=b"", headers={"content-type": "image/svg+xml"}), +]) +async def test_fetch_image_rejects_redirect_error_and_non_image(res): + async with _client(lambda r: res) as c: + with pytest.raises(ImageFetchFailed): + await fetch_image(c, OK_URL) + + +@pytest.mark.anyio +async def test_fetch_image_rejects_too_large(monkeypatch): + monkeypatch.setattr(image_proxy, "MAX_BYTES", 10) + async with _client(lambda r: httpx.Response(200, content=b"x" * 11, headers={"content-type": "image/png"})) as c: + with pytest.raises(ImageFetchFailed): + await fetch_image(c, OK_URL) + + +@pytest.mark.anyio +async def test_image_api_blocks_other_hosts(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + res = await c.get("/v1/image", params={"url": "https://evil.example.com/a.jpg"}) + assert res.status_code == 400 + + +@pytest.mark.anyio +async def test_image_api_serves_image_with_cache(monkeypatch): + async def fake(_client, url): + assert url == OK_URL + return b"png-bytes", "image/png" + monkeypatch.setattr("router.v1.image.image.fetch_image", fake) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + res = await c.get("/v1/image", params={"url": OK_URL}) + assert res.status_code == 200 + assert res.content == b"png-bytes" + assert res.headers["content-type"] == "image/png" + assert "max-age=86400" in res.headers["cache-control"] + + +@pytest.mark.anyio +async def test_image_api_reports_upstream_failure(monkeypatch): + async def fail(_client, _url): + raise ImageFetchFailed("status 404") + monkeypatch.setattr("router.v1.image.image.fetch_image", fail) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + res = await c.get("/v1/image", params={"url": OK_URL}) + assert res.status_code == 502 + + +def test_allowed_follows_settings(monkeypatch): + from config.settings import settings + monkeypatch.setattr(settings, "image_proxy_hosts", " cdn.example.org , ") + assert allowed("https://cdn.example.org/a.jpg") is True + assert allowed(OK_URL) is False diff --git a/compose.yaml b/compose.yaml index 6d9d479..c87c165 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,6 +9,8 @@ services: args: # 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다 VITE_API_BASE_URL: ${VITE_API_BASE_URL:-} + # 공유할 때 나가는 우리 주소. 비우면 지금 보고 있는 주소 + VITE_SITE_URL: ${VITE_SITE_URL:-} ports: - "${FRONT_PORT:-8080}:80" restart: unless-stopped @@ -26,6 +28,7 @@ services: - /app/node_modules environment: - CHOKIDAR_USEPOLLING=true + - VITE_SITE_URL=${VITE_SITE_URL:-} # 백엔드 API: http://localhost:9810/docs backend: diff --git a/frontend/Dockerfile b/frontend/Dockerfile index d08c117..72f8135 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -16,6 +16,8 @@ CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"] FROM deps AS build ARG VITE_API_BASE_URL="" ENV VITE_API_BASE_URL=$VITE_API_BASE_URL +ARG VITE_SITE_URL="" +ENV VITE_SITE_URL=$VITE_SITE_URL COPY . . RUN npm run build diff --git a/frontend/index.html b/frontend/index.html index cf68ea0..ebeb3a2 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -11,10 +11,12 @@ diff --git a/frontend/src/api/setup.ts b/frontend/src/api/setup.ts index c693c2b..b5217e6 100644 --- a/frontend/src/api/setup.ts +++ b/frontend/src/api/setup.ts @@ -2,6 +2,7 @@ import { client } from './client/client.gen' import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth' export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810' +export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '') type Refresh = 'ok' | 'rejected' | 'unreachable' diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index 8ed1b74..fe61ea9 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -308,11 +308,11 @@ function FullCard({ post }: PostProps) { const [pop, setPop] = useState(0) const [likeFailed, setLikeFailed] = useState(0) const lastTap = useRef(0) - const cardRef = useRef(null) + const trackRef = useRef(null) const [account, avatar] = ACCOUNTS[post.post_type] const n = post.slides.length const bgs = post.slides.map((sl) => slideBg(post, sl)) - const share = () => open({ type: 'share', share: { title: post.title, icon: post.icon, bg: bgs[0] ?? 'sky', messages: post.share_messages ?? [], card: cardRef.current } }) + const share = () => open({ type: 'share', share: { title: post.title, slides: Array.from(trackRef.current?.children ?? []).filter((c) => c instanceof HTMLElement) } }) const comments = () => open({ type: 'comments', postId: post.post_id }) const patch = (values: Partial) => patchFeed(queryClient, post.post_id, values) @@ -368,7 +368,7 @@ function FullCard({ post }: PostProps) { {account} -
+
{n > 1 && (