From 3257360b5becf1ef2631643464cf29c03061eeb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Thu, 26 Nov 2026 15:26:30 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=EC=9C=84=EC=A0=AF=20=EC=B9=B4?= =?UTF-8?q?=EB=93=9C=20=EC=A1=B0=ED=9A=8C=EB=A5=BC=20=EB=82=A0=EC=94=A8?= =?UTF-8?q?=EA=B0=81=20umami=20=EC=97=90=20/widget-card=20=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=EB=A1=9C=20=EA=B8=B0=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 다른 사이트에서 카드를 부르면 카드 화면에 날씨각 umami 스크립트를 붙여 조회를 /widget-card(제목 '날씨 위젯 · 기본형/상세형')로 보냄. 붙인 사이트는 유입 경로로 남음. 날씨각 미리보기는 보내지 않음 - 쿠키 없음, 스크립트가 늦거나 막혀도 카드는 그대로 - 개인정보처리방침에 umami(쿠키 없는 방문 통계)와 위젯 조회 집계를 적음 - 운영 문서 4-4장: umami 에서 카드 조회 보기 --- backend/services/embed_service.py | 26 +++++++++++++++++++++++--- backend/tests/test_embed.py | 18 ++++++++++++++++++ docs/위젯_운영.md | 16 ++++++++++++++++ frontend/public/privacy.html | 2 +- 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/backend/services/embed_service.py b/backend/services/embed_service.py index 413fc7a..15d8793 100644 --- a/backend/services/embed_service.py +++ b/backend/services/embed_service.py @@ -44,6 +44,13 @@ _REGION_CODE = re.compile(r"[0-9]{10}") _PATHS: dict[str, str] = json.loads((Path(__file__).resolve().parent.parent / "seed" / "region_path.json").read_text(encoding="utf-8")) _widgets = WidgetCRUD() +# 날씨각 umami(frontend/index.html 과 같은 사이트 ID): 카드 조회를 날씨각 통계 안의 /widget-card 페이지로 보낸다. +# 쿠키를 쓰지 않는다. 자동 수집을 끄고 주소를 바꿔 보내, 붙인 사이트는 umami '유입 경로'에 남는다(iframe 의 referrer) +UMAMI_SRC = "https://analytics.webforai.kr/script.js" +UMAMI_WEBSITE_ID = "b2244cf7-9b43-49c0-b1c0-acfaaab95ddb" +UMAMI_PATH = "/widget-card" +_KIND_LABEL = {"side": "기본형", "home": "상세형"} + _FONT = '-apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif' # card.css --font 의 시스템 글꼴 부분 # 조용한 화면 바탕: 카드(card.css)의 배경별 낮 하늘과 같은 색. 링크는 카드 is-failed 의 흰 알약과 같은 모양 # (frontend/public/embed/quiet.html 은 nginx 가 백엔드 없이 주는 같은 모양의 sky 판이다) @@ -134,9 +141,20 @@ def _page(title: str, head: str, body: str, body_class: str = "") -> str: ) -def render_card(kind: str, bg: str, data: dict, link: str) -> str: +def _umami(kind: str) -> str: + """umami 로 카드 조회 한 번(/widget-card, 제목에 모양). 스크립트가 늦거나 막혀도 카드 그리기와는 상관없다.""" + title = json.dumps(f"날씨 위젯 · {_KIND_LABEL[kind]}", ensure_ascii=False) + send = f"umami.track(function(p){{p.url={json.dumps(UMAMI_PATH)};p.title={title};return p}})" + return ( + f'' + ) + + +def render_card(kind: str, bg: str, data: dict, link: str, track: bool = False) -> str: """카드 화면. 상자는 군산각 카드(.wx)와 같은 구조이고, 본문 칸(data-wx-b)은 card.js 가 #wx-data 를 읽어 그린다. - 그리기 전에는 토끼 로딩 화면(.wx-load)이 보이고, 못 그리면(is-failed, 또는 8초 안에 스크립트가 안 돌면) 날씨각 링크(.wx-go)가 보인다.""" + 그리기 전에는 토끼 로딩 화면(.wx-load)이 보이고, 못 그리면(is-failed, 또는 8초 안에 스크립트가 안 돌면) 날씨각 링크(.wx-go)가 보인다. + track 이면 umami 로 조회를 보낸다(날씨각 자신의 미리보기는 빼려고 부르는 쪽이 정한다).""" payload = json.dumps({**data, "link": link}, ensure_ascii=False).replace("<", "\\u003c") # 값 안의 가 태그를 닫지 못하게 # color-scheme 은 light 로 고정: light dark 면 색 선언이 없는 사이트(대부분)에서 방문자 기기가 다크 모드일 때 모서리 밖이 검게 칠해진다. # color-scheme: dark 를 선언한 사이트에서 생기는 불투명 바탕은 붙이는 코드의 iframe border-radius 가 잘라 낸다 @@ -153,6 +171,8 @@ def render_card(kind: str, bg: str, data: dict, link: str) -> str: f'\n' f'' ) + if track: + body += "\n" + _umami(kind) return _page(f"{data['name']} 날씨 - 날씨각", head, body) @@ -321,7 +341,7 @@ class EmbedService: if data is None: return status, render_quiet(link, bg) - html = render_card(kind, bg, data, link) + html = render_card(kind, bg, data, link, track=viewer is not None) if viewer is not None: try: await self._count(viewer, kind) diff --git a/backend/tests/test_embed.py b/backend/tests/test_embed.py index cdcfe14..ec5d264 100644 --- a/backend/tests/test_embed.py +++ b/backend/tests/test_embed.py @@ -2,6 +2,7 @@ import asyncio import json import re from datetime import datetime, timedelta +from pathlib import Path import pytest from httpx import ASGITransport, AsyncClient @@ -205,6 +206,21 @@ def test_quiet_follows_bg(): assert f'href="{link.replace("&", "&")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›' in html +def test_card_umami_sends_widget_card_page(): + data = card_data(_feed(), _today(), "군산시", NOW) + assert "analytics.webforai.kr" not in render_card("side", "sky", data, card_link(None, "preview")) + html = render_card("home", "dark", data, card_link(None, "unknown"), track=True) + tag = re.search(r'', html).group(0) + assert 'data-auto-track="false"' in tag and 'data-domains="weather.o2o.kr,www.weather.o2o.kr"' in tag + assert ""/widget-card"" in tag and "날씨 위젯 · 상세형" in tag + assert "날씨 위젯 · 기본형" in render_card("side", "sky", data, card_link(None, "unknown"), track=True) + + +def test_card_umami_uses_site_id_from_index_html(): + index = (Path(__file__).resolve().parents[2] / "frontend" / "index.html").read_text(encoding="utf-8") + assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index and embed_service.UMAMI_SRC in index + + def test_card_markup_escapes_name(): html = render_card("side", "sky", card_data(_feed(), _today(), '"군산"', NOW), card_link(None, "unknown")) body = html.split("", 1)[1].split('' ) diff --git a/backend/tests/test_embed.py b/backend/tests/test_embed.py index ec5d264..d028874 100644 --- a/backend/tests/test_embed.py +++ b/backend/tests/test_embed.py @@ -208,17 +208,23 @@ def test_quiet_follows_bg(): def test_card_umami_sends_widget_card_page(): data = card_data(_feed(), _today(), "군산시", NOW) - assert "analytics.webforai.kr" not in render_card("side", "sky", data, card_link(None, "preview")) + assert "/embed/umami.js" not in render_card("side", "sky", data, card_link(None, "preview")) html = render_card("home", "dark", data, card_link(None, "unknown"), track=True) - tag = re.search(r'', html).group(0) + # 외부 스크립트를 직접 실행하지 않는다: 날씨각에 복사해 둔 스크립트를 쓰고 기록만 umami 서버로 보낸다 + tag = re.search(r'', html).group(0) + assert 'data-host-url="https://analytics.webforai.kr"' in tag assert 'data-auto-track="false"' in tag and 'data-domains="weather.o2o.kr,www.weather.o2o.kr"' in tag assert ""/widget-card"" in tag and "날씨 위젯 · 상세형" in tag + assert 'src="https://analytics.webforai.kr' not in html assert "날씨 위젯 · 기본형" in render_card("side", "sky", data, card_link(None, "unknown"), track=True) -def test_card_umami_uses_site_id_from_index_html(): - index = (Path(__file__).resolve().parents[2] / "frontend" / "index.html").read_text(encoding="utf-8") - assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index and embed_service.UMAMI_SRC in index +def test_card_umami_matches_index_html(): + frontend = Path(__file__).resolve().parents[2] / "frontend" + index = (frontend / "index.html").read_text(encoding="utf-8") + assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index + assert f'src="{embed_service.UMAMI_SRC}"' in index and f'data-host-url="{embed_service.UMAMI_HOST}"' in index + assert (frontend / "public" / embed_service.UMAMI_SRC.lstrip("/")).is_file() def test_card_markup_escapes_name(): @@ -237,7 +243,7 @@ async def test_any_site_gets_card(offline): assert header not in res.headers, header assert res.headers["cache-control"] == "no-store" assert res.headers["x-robots-tag"] == "noindex" - assert "analytics.webforai.kr" in res.text + assert "/embed/umami.js" in res.text assert await _views() == {"evil.example": 1} @@ -274,7 +280,7 @@ async def test_self_preview_not_counted(offline): res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "http://test/widget"}) assert res.status_code == 200 and 'id="wx-data"' in res.text assert "utm_campaign=preview" in _card(res.text)["link"] - assert "analytics.webforai.kr" not in res.text + assert "/embed/umami.js" not in res.text assert await _views() == {} diff --git a/docs/위젯_운영.md b/docs/위젯_운영.md index b921ac4..831c522 100644 --- a/docs/위젯_운영.md +++ b/docs/위젯_운영.md @@ -199,6 +199,8 @@ curl -s -H "X-Admin-Key: $ADMIN_API_KEY" https://weather.o2o.kr/v1/admin/widget/ - 날씨각 전체 방문자·조회 수에 위젯 조회가 더해집니다. 위젯을 빼고 보려면 umami에서 페이지 `/widget-card` 를 필터로 뺍니다. - `data-domains` 가 `weather.o2o.kr` 이라 로컬(`localhost`)에서는 보내지 않습니다. - umami 사이트 ID 는 `frontend/index.html` 과 같아야 합니다(`tests/test_embed.py` 가 확인). +- umami 스크립트는 외부(`analytics.webforai.kr/script.js`)에서 직접 부르지 않고 날씨각에 복사해 둔 `frontend/public/embed/umami.js` 를 씁니다(날씨각 웹 `index.html` 도 같음). 기록은 `data-host-url` 의 umami 서버로 갑니다. 외부 스크립트가 바뀌거나 그 서버가 뚫려도 날씨각과 위젯을 붙인 사이트에서 다른 코드가 돌지 않게 하려는 것입니다(무결성 확인 SRI 대신. umami 서버가 다른 사이트의 파일 확인 요청을 허락하지 않아 SRI 를 쓸 수 없다). +- umami 서버를 업그레이드한 뒤 기록이 안 쌓이면: `https://analytics.webforai.kr/script.js` 를 다시 받아 `umami.js` 맨 위 주석만 남기고 덮어씁니다. 이 파일은 린트에서 뺐습니다(`frontend/.oxlintrc.json`). --- diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json index 6fa991d..4b9cb21 100644 --- a/frontend/.oxlintrc.json +++ b/frontend/.oxlintrc.json @@ -1,6 +1,7 @@ { "$schema": "./node_modules/oxlint/configuration_schema.json", "plugins": ["react", "typescript", "oxc"], + "ignorePatterns": ["public/embed/umami.js"], "rules": { "react/rules-of-hooks": "error", "react/only-export-components": ["warn", { "allowConstantExport": true }] diff --git a/frontend/index.html b/frontend/index.html index 0999416..d54b997 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -10,8 +10,9 @@ gtag('config', 'G-D378J4X373', { platform: '%MODE%' === 'toss' ? 'toss' : /NalssigakApp\//.test(navigator.userAgent) ? 'android_app' : 'web' }); - -