Compare commits

...
Author SHA1 Message Date
HyeongBaeYangandClaude Opus 5 af6e3799eb [feat] solution/backend: 에이전트가 사진을 내리고 대표를 지정한다
사진 쪽은 MediaService 에 list_media 하나뿐이었다 — 쓰기 경로가 아예 없었고
빌더 화면에서도 보기만 됐다. 서비스·라우터부터 열고 도구를 붙였다.

- crud: set_sort_order / service: hide_media · set_primary
- POST .../media/{id}/hide · /primary — ★ 에이전트 전용 뒷문을 만들지 않는다.
  그러면 빌더 화면이 그 기능을 못 쓰고 나중에 붙일 때 로직이 두 벌이 된다
- 도구 셋: list_photos(READ) · hide_photo · set_primary_photo(REVERSIBLE)

★ 대표 사진에 별도 칸을 두지 않았다. primary_media 가 '첫 장' 을 쓰고 목록이
ORDER BY sort_order 라, 지정은 sort_order 를 가장 작게 내리는 일이다 —
칸을 따로 두면 규칙이 둘이 되어 검색 결과의 그림과 화면 첫 장이 갈린다.

★ 내려도 지우지 않는다(REJECTED). origin_url·source_type 이 남아야 재게시
권리(DECISIONS 1-2) 결론이 났을 때 되짚을 수 있다.

★★ 업로드·교체는 만들지 않았다 — 미결 사항을 코드가 먼저 푸는 자리다.
테스트가 레지스트리에 upload·replace 가 없는지 실제로 검사한다.

test_agent_runtime 32 passed(사진 6건 추가).
전체 871 passed / 53 failed — 53 은 이번 변경 전과 동일. npm run lint 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-28 14:16:08 +09:00
HyeongBaeYangandClaude Opus 5 ea9ae1ac2a [feat] solution/backend: 에이전트가 페이지 구성을 바꾼다 — 섹션 on/off·순서
"문구 변경밖에 안 된다" 는 지적에서 시작했다. 페이지 구성은 sites.theme.sections
배열 하나이고 배열 순서가 곧 발행본의 순서라, 그 JSON 을 만지는 도구 셋을 붙였다.

- list_sections(READ) · toggle_section(REVERSIBLE) · move_section(REVERSIBLE)
- 목록은 site_payload._sections 를 그대로 쓴다 — 발행본이 쓰는 그 함수다.
  표를 따로 만들면 에디터·발행본·대화 셋이 갈라지고 "껐는데 나온다" 가 된다
- 잠긴 섹션은 못 끈다. _sections 가 어차피 켜서 내보내므로 끌 수 있게 두면
  화면만 거짓말한다
- 이름이 둘 이상 걸리면 고르지 않는다 — 추측으로 고르면 발행하고 나서야 안다
- sections 만 갈아끼운다 — theme 을 통째로 쓰면 고른 색·서체가 말없이 사라진다

★ 템플릿·색은 넣지 않았다. templatesFor() 가 색·look·기본 섹션·배리에이션을 함께
계산해서, 백엔드가 template_id 만 바꾸면 "레이아웃은 새것, 색은 옛것" 이 된다 —
레지스트리를 공유 단일 출처로 옮기는 작업이 먼저다(docs/AGENT.md).

test_agent_runtime 26 passed(구성 7건 추가).
전체 864 passed / 53 failed — 53 은 이번 변경 전과 동일. npm run lint 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-28 11:50:38 +09:00
HyeongBaeYangandClaude Opus 5 e35ce311d3 [fix] solution/backend,frontend: 메일 '고쳐서 올리려면' 링크를 일회용 코드로
주소가 500자였던 것은 곁가지고, 진짜 문제는 그 auto= 가 빌더 액세스 토큰
통짜(sub 에 UserInfo 전체 — role 포함)였다는 것이다. 메일 전달 한 번이 그날
자정까지의 권한 양도였고, 브라우저 히스토리·프록시 로그·Referer 에도 남았다.
SNS 승인 흐름에서는 같은 이유로 "기존 액세스 토큰을 승인 링크에 얹지 않는다" 를
원칙으로 박아 뒀는데 이 경로에만 남아 있었다.

- 0023: place_posts.edit_token_hash. 승인 토큰과 같은 규약(평문은 메일에만)
- GET /v1/site/post/edit?t=<코드> → 검증 후 day-pass 를 그 자리에서 만들어
  /blog?...#auto=<JWT> 로 303. ★ 프래그먼트는 서버 로그·Referer 에 안 남는다
- 프론트는 hash 에서 읽고 **주소창에서 지운다**. 쿼리도 계속 받는다 —
  이미 나간 메일이 자정까지 살아 있고 그걸 깨면 그 링크들이 통째로 죽는다
- 두 코드는 서로 다른 칸에 산다. 하나로 둘 다 되면 일회성이 무의미해진다
- blog_service.app_origin() 으로 오리진 계산을 옮겼다 — 라우터도 같은 값을 쓴다

링크 길이 약 500자 → 약 75자.

test_blog_owner 45 passed (신규 6건: 길이·프래그먼트·소유자·만료·없는 코드·
승인 코드 교차 사용). test_upcoming_only_returns_next_week_in_date_order 1건은
기준(stash)에서도 동일하게 실패하는 기존 건. npm run lint 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-28 09:00:02 +09:00
minaChoi 79962b93e2 Merge branch 'feature/site-features-and-mockup' into main 2026-09-23 13:19:19 +09:00
20 changed files with 963 additions and 34 deletions

No files matched your search

+45 -2
View File
@@ -131,10 +131,53 @@ services/fact_service.py · site_service.py ★ 게이트가 사는 곳
| 등급 | 도구 | 대화에서 |
|---|---|---|
| `READ` | `get_site_status` · `list_facts` | 바로 답한다 |
| `REVERSIBLE` | `set_fact` | 실행하고 알린다 |
| `READ` | `get_site_status` · `list_facts` · `list_sections` · `list_photos` | 바로 답한다 |
| `REVERSIBLE` | `set_fact` · `toggle_section` · `move_section` · `hide_photo` · `set_primary_photo` | 실행하고 알린다 |
| `SEMI` | `publish` | **실행 전에 한 번 묻는다** |
### 페이지 구성 (2026-09-28)
"후기 빼줘" · "사진 갤러리 맨 위로" 처럼 **화면 구성**을 바꾼다. 구성은 `sites.theme.sections`
배열 하나이고, **배열 순서가 곧 발행본의 섹션 순서**다.
★ 목록은 `site_payload._sections` 를 **그대로 쓴다** — 발행본이 쓰는 바로 그 함수다.
표를 따로 만들면 에디터·발행본·대화 셋이 갈라지고, 사장님은 "껐는데 나온다" 를 겪는다.
저장값이 없어도 업종 기본이 서므로, 디자인을 한 번도 안 만진 사업장에서도 바로 통한다.
★ **잠긴 섹션(히어로·기본 정보·오시는 길)은 끌 수 없다.** SEO·필수 마크업 때문에 잠긴 것이고,
`_sections` 가 어차피 켜서 내보낸다 — 끌 수 있게 두면 **화면만 거짓말한다.**
★ **이름이 둘 이상 걸리면 고르지 않는다.** 추측으로 고르면 엉뚱한 부분을 끄고, 사장님은
발행하고 나서야 안다. 티오더가 "유사 메뉴 2개 이상이면 후보 제시" 로 푼 것과 같은 문제다.
★ **`sections` 만 갈아끼운다.** theme 을 통째로 새로 쓰면 사장님이 고른 색·서체가 말없이 사라진다.
### 사진 (2026-09-28)
"객실 사진 내려줘" · "대표 사진 수영장으로 바꿔줘". 지목은 Vision 이 만든 **라벨·alt** 로 한다.
★ **대표 사진은 별도 칸이 아니라 목록의 첫 장**이다(`site_payload.primary_media`). 그래서
'대표로 지정' 은 `sort_order` 를 가장 작게 내리는 일이다 — 칸을 따로 두면 규칙이 둘이 되고,
검색 결과에 뜨는 그림과 화면 첫 장이 갈린다.
★ **객실·메뉴 전용 사진(`unit_id` 있음)은 대표가 될 수 없다.** `primary_media` 가 건너뛰므로
지정하게 두면 화면만 거짓말한다.
★ **내려도 지우지 않는다**(`REJECTED`). `origin_url`·`source_type` 이 남아 있어야 재게시
권리(DECISIONS 1-2) 결론이 났을 때 무엇을 실었는지 되짚을 수 있고, 잘못 내렸을 때 되돌릴 수도 있다.
★★ **업로드·교체 도구는 만들지 않았다.** 이미지 재게시 권리가 미결이라 저장 경로를 일부러
안 만들어 둔 것이고(DECISIONS 5-3), 도구가 생기면 **그 결정을 코드가 먼저 풀어 버린다.**
테스트가 레지스트리에 `upload`·`replace` 가 없는지 실제로 검사한다.
★ 서버 엔드포인트(`POST .../media/{id}/hide` · `/primary`)도 함께 열었다 — 에이전트 전용
뒷문을 만들면 빌더 화면이 그 기능을 못 쓰고, 나중에 붙일 때 로직이 두 벌이 된다.
★ **템플릿·색 변경은 아직 없다.** 목록이 프론트(`frontend/src/data/industryData.ts`)에 있고
`templatesFor()` 가 색·`look`·기본 섹션·배리에이션을 **함께 계산**한다. 백엔드가 `template_id`
만 바꾸면 색은 옛것이 남아 "레이아웃은 새것, 색은 옛것" 이 된다 — 조용히 틀리는 종류다.
하려면 그 레지스트리를 공유 단일 출처로 옮기는 작업이 먼저다.
★ **등급은 레지스트리가 못 박는다.** 모델이 정하게 두면 프롬프트에 끼어든 한 줄이 확인
절차를 건너뛴다. 그래서 응답 스키마에 등급 칸 자체가 없고, 도구 목록에도 등급을 싣지 않는다.
+45
View File
@@ -1,5 +1,50 @@
# 개발 일지
## 2026-09-28 — 에이전트가 사진을 내리고 대표를 지정한다
사진 쪽은 `MediaService` 에 `list_media` 하나뿐이었다 — **쓰기 경로가 아예 없었다.**
빌더 화면에서도 보기만 됐다. 그래서 서비스·라우터부터 열고 도구를 붙였다.
- `crud/media_crud.set_sort_order` · `services/media_service.hide_media`·`set_primary`
- `POST .../media/{id}/hide` · `/primary` — ★ 에이전트 전용 뒷문을 만들지 않는다.
그러면 빌더 화면이 그 기능을 못 쓰고 나중에 붙일 때 로직이 두 벌이 된다
- 도구 셋: `list_photos`(READ) · `hide_photo` · `set_primary_photo`(REVERSIBLE)
**★ 대표 사진에 별도 칸을 두지 않았다.** `site_payload.primary_media` 가 '첫 장' 을 쓰고
목록이 `ORDER BY sort_order, created_at` 이라, 지정은 `sort_order` 를 가장 작게 내리는 일이다.
칸을 따로 두면 규칙이 둘이 되어 **검색 결과에 뜨는 그림과 화면 첫 장이 갈린다.**
**★ 내려도 지우지 않는다**(`REJECTED`). `origin_url`·`source_type` 이 남아야 재게시 권리
(DECISIONS 1-2) 결론이 났을 때 되짚을 수 있다.
**★★ 업로드·교체는 만들지 않았다.** 미결 사항(1-2)을 코드가 먼저 푸는 자리다 —
테스트가 레지스트리에 `upload`·`replace` 가 없는지 실제로 검사한다.
**검증** — `test_agent_runtime` 32 passed(사진 6건 추가). 전체 `871 passed / 53 failed` 이고
그 53 은 이번 변경 전과 같다. `npm run lint` 통과.
## 2026-09-28 — 에이전트가 페이지 구성을 바꾼다 (섹션 on/off · 순서)
"문구 변경밖에 안 된다" 는 지적에서 시작했다. 페이지 구성은 `sites.theme.sections` 배열
하나이고 **배열 순서가 곧 발행본의 순서**라, 그 JSON 을 만지는 도구 셋을 붙였다.
- `list_sections`(READ) · `toggle_section`(REVERSIBLE) · `move_section`(REVERSIBLE)
- 목록은 `site_payload._sections` 를 그대로 쓴다 — 발행본이 쓰는 그 함수다.
표를 따로 만들면 에디터·발행본·대화 셋이 갈라진다.
- 잠긴 섹션은 못 끈다. `_sections` 가 어차피 켜서 내보내므로 끌 수 있게 두면 화면만 거짓말한다.
- 이름이 둘 이상 걸리면 고르지 않는다. 추측으로 고르면 발행하고 나서야 안다.
- `sections` 만 갈아끼운다 — theme 을 통째로 쓰면 고른 색·서체가 말없이 사라진다.
**★ 템플릿·색은 넣지 않았다(요청 범위였으나 선행 작업이 필요하다).**
템플릿 목록은 `frontend/src/data/industryData.ts` 의 `templatesFor()` 가 **생성**하고,
색·`look`·`defaultSectionTypes`·`defaultVariants` 를 함께 계산한다(`stores/builder.selectTemplate`
가 섹션 on/off 와 배리에이션까지 바꾼다). 백엔드가 `template_id` 만 바꾸면 색은 옛것이 남아
**"레이아웃은 새것, 색은 옛것"** 이 된다 — 이 레포가 반복해 경고하는 '두 곳에 같은 표' 함정이다.
하려면 그 레지스트리를 공유 단일 출처로 옮기는 작업이 먼저다.
**검증** — `test_agent_runtime` 26 passed(구성 7건 추가). 전체 `864 passed / 53 failed` 이고
그 53 은 이번 변경 전과 같다.
## 2026-09-22 — 카톡 5초 벽을 콜백으로 넘는다
실제 카톡에서 "시설 편의에서 바비큐 이용 문구 빼줘" 가 **"확인하는 데 시간이 조금 걸리네요"**
+25
View File
@@ -260,3 +260,28 @@
- 글마다 별도 URL·목록 페이지 — 한 장 규칙을 깬다
- 예약 요청 관리 화면 — `booking_request.py` 는 요청을 DB 에 남기지 않는다(2026-09-16
대표 지시). 목록을 만들려면 그 결정부터 바꿔야 한다
## 메일 링크 — 둘 다 일회용 코드다 (2026-09-28)
```
이대로 올리려면 : /v1/site/post/approve?t=<43자>
고쳐서 올리려면 : /v1/site/post/edit?t=<43자>
```
★ 예전에는 수정 링크가 `/blog?placeId=..&postId=..&auto=<JWT>` 였다. 주소가 500자였던 것은
곁가지고, 진짜 문제는 그 `auto` 가 **빌더 액세스 토큰 통짜**(sub 에 UserInfo 전체 — role 포함)
였다는 것이다 — **메일 전달 한 번이 그날 자정까지의 권한 양도**이고, 브라우저 히스토리 ·
앞단 프록시 로그 · Referer 에도 그대로 남았다.
(SNS 승인 흐름에서는 같은 이유로 "기존 액세스 토큰을 승인 링크에 얹지 않는다" 를 원칙으로
박아 뒀는데, 이 경로에만 남아 있었다.)
지금은 `/edit` 이 코드를 검증한 뒤 **그 자리에서** day-pass 토큰을 만들어
`/blog?placeId=..&postId=..#auto=<JWT>` 로 303 리다이렉트한다.
★ **프래그먼트**로 넘기는 이유: 프래그먼트는 서버 로그와 Referer 에 남지 않는다.
프론트(`app/provider.tsx`)는 그 값을 읽어 세션을 세운 뒤 **주소창에서 지운다.**
★ 쿼리(`?auto=`)도 계속 받는다 — 이미 나간 메일이 자정까지 살아 있고, 그걸 깨면 그 링크들이
통째로 죽는다.
★ 두 코드는 **서로 다른 칸**(`approve_token_hash` · `edit_token_hash`)에 산다. 하나로 둘 다
되면 일회성이 무의미해진다. 만료는 `token_expires_at` 을 같이 쓴다.
+6
View File
@@ -367,6 +367,7 @@ CREATE TABLE IF NOT EXISTS public.place_posts (
scheduled_date DATE NULL, -- 이 업장 몫 하루 한 통 배정일(KST). 생성 시 순서대로 채운다
generation_meta JSONB NULL, -- 생성 당시 부가정보(모델명 등) — 컬럼 안 늘리고 여기 담는다
approve_token_hash VARCHAR(64) NULL, -- sha256(평문). 평문은 메일 본문에만
edit_token_hash VARCHAR(64) NULL, -- '고쳐서 올리려면' 링크의 일회용 코드 해시(migrations/0023)
token_expires_at TIMESTAMPTZ NULL,
sent_at TIMESTAMPTZ NULL,
approved_at TIMESTAMPTZ NULL,
@@ -571,6 +572,11 @@ CREATE INDEX IF NOT EXISTS ix_place_posts_status
CREATE INDEX IF NOT EXISTS ix_place_posts_token
ON public.place_posts (approve_token_hash) WHERE approve_token_hash IS NOT NULL;
-- 메일 '고쳐서 올리려면' 링크가 한 번에 한 행을 집는다(migrations/0023).
CREATE INDEX IF NOT EXISTS ix_place_posts_edit_token
ON public.place_posts(edit_token_hash)
WHERE deleted = false AND edit_token_hash IS NOT NULL;
-- alert_outbox
-- 재시도 경로: PENDING(1) 이면서 next_attempt_at 이 지난 것.
CREATE INDEX IF NOT EXISTS ix_alert_outbox_pending ON public.alert_outbox (status, next_attempt_at);
@@ -0,0 +1,17 @@
-- 0023 · place_posts.edit_token_hash — 메일의 "고쳐서 올리려면" 링크를 일회용 코드로.
--
-- ★ 예전에는 그 링크에 **빌더 액세스 토큰 통짜**(sub 에 UserInfo 전체 — role 포함)를
-- 쿼리로 실어 보냈다. 주소가 500자였던 것은 그 때문이고, 길이보다 나쁜 것은 따로 있다:
-- 메일을 한 번 전달하면 **그날 자정까지 빌더 권한이 그대로 넘어간다.** 브라우저 히스토리 ·
-- 앞단 프록시 로그 · Referer 에도 그대로 남는다.
-- (SNS 승인 흐름에서는 같은 이유로 "기존 액세스 토큰을 승인 링크에 얹지 않는다" 를
-- 설계 원칙으로 박아 뒀는데, 이 경로에만 남아 있었다.)
--
-- ★ 승인 토큰(approve_token_hash)과 같은 규약이다 — 평문은 메일 본문에만 있고 DB 에는
-- sha256 만 둔다. 만료는 token_expires_at 을 같이 쓴다(두 링크가 같은 시각에 죽는다).
ALTER TABLE public.place_posts ADD COLUMN IF NOT EXISTS edit_token_hash varchar(64);
-- 링크 한 번에 한 행을 집는다. 승인 토큰과 같은 이유로 부분 인덱스다.
CREATE INDEX IF NOT EXISTS ix_place_posts_edit_token
ON public.place_posts(edit_token_hash)
WHERE deleted = false AND edit_token_hash IS NOT NULL;
@@ -461,6 +461,9 @@ class place_posts(MainTableMixin, MAIN_BASE):
# 파서 컬럼"). 새 필드가 늘어도 마이그레이션이 안 따라온다.
generation_meta = Column(JSONB, nullable=True)
approve_token_hash = Column(String(64), nullable=True)
# ★ 메일 '고쳐서 올리려면' 링크의 일회용 코드. 예전에는 그 자리에 빌더 액세스 토큰을
# 통짜로 실어 보냈다 — 메일 전달 한 번이 자정까지의 권한 양도였다(migrations/0023).
edit_token_hash = Column(String(64), nullable=True)
token_expires_at = Column(DateTime(timezone=True), nullable=True)
sent_at = Column(DateTime(timezone=True), nullable=True)
approved_at = Column(DateTime(timezone=True), nullable=True)
+21
View File
@@ -24,6 +24,9 @@ class IMediaCRUD(ABC):
pass
@abstractmethod
async def set_sort_order(self, cdb: AsyncSession, place_id, media_id, sort_order: int, ts) -> Tuple[ErrorType, int]:
pass
async def set_status(self, cdb: AsyncSession, place_id, media_id, status: int, ts) -> Tuple[ErrorType, int]:
pass
@@ -81,6 +84,24 @@ class MediaCRUD(IMediaCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def set_sort_order(self, cdb: AsyncSession, place_id, media_id, sort_order: int, ts) -> Tuple[ErrorType, int]:
"""사진 순서를 바꾼다.
★ 목록이 `ORDER BY sort_order, created_at` 이고 대표 사진은 그 **첫 장**이다
(site_payload.primary_media). 그래서 '대표로 지정' 은 이 값을 가장 작게 만드는 일이다 —
별도의 is_primary 칸을 두지 않는 이유는, 두면 두 규칙(칸 · 순서)이 생겨
검색 결과에 뜨는 그림과 화면 첫 장이 갈릴 수 있기 때문이다."""
try:
query = (
update(place_photos)
.where(place_photos.media_id == media_id, place_photos.place_id == place_id, place_photos.deleted == False) # noqa: E712
.values(sort_order=sort_order, updated_at=ts)
)
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def set_status(self, cdb: AsyncSession, place_id, media_id, status: int, ts) -> Tuple[ErrorType, int]:
"""사람이 사진을 승인/반려한다."""
try:
+10 -1
View File
@@ -144,11 +144,20 @@ class PostCRUD:
)
return result.scalars().first()
async def mark_sent(self, cdb: AsyncSession, post_id, token_hash: str, expires_at) -> ErrorType:
async def by_edit_token_hash(self, cdb: AsyncSession, token_hash: str):
result = await cdb.execute(
select(place_posts)
.where(place_posts.edit_token_hash == token_hash, place_posts.deleted == False) # noqa: E712
)
return result.scalars().first()
async def mark_sent(self, cdb: AsyncSession, post_id, token_hash: str, expires_at,
edit_token_hash: str | None = None) -> ErrorType:
await cdb.execute(
update(place_posts)
.where(place_posts.post_id == post_id)
.values(status=PostStatus.SENT.value, approve_token_hash=token_hash,
edit_token_hash=edit_token_hash,
token_expires_at=expires_at, sent_at=GTime.UTC(), updated_at=GTime.UTC())
)
return ErrorType.SUCCESS
+34
View File
@@ -30,3 +30,37 @@ async def list_media(
publishable_only: bool = Query(False),
):
return RemoveNoneResponse(await service.list_media(user_info, str(place_id), unit_id, publishable_only))
@router.post(
path="/{media_id}/hide",
response_model=Res_MediaList,
summary="사진 내리기",
description="그 사진을 REJECTED 로 내려 발행본에서 뺀다. ★ 지우지 않는다 — origin_url·source_type 이 "
"남아 있어야 재게시 권리(docs/DECISIONS.md 1-2) 결론이 났을 때 되짚을 수 있고, "
"잘못 내렸을 때 되돌릴 수도 있다. 응답은 갱신된 목록이다.",
)
async def hide_media(
place_id: UUID,
media_id: UUID,
service: MediaService = Depends(),
user_info: UserInfo = Depends(IsValidAccessToken),
):
return RemoveNoneResponse(await service.hide_media(user_info, str(place_id), str(media_id)))
@router.post(
path="/{media_id}/primary",
response_model=Res_MediaList,
summary="대표 사진 지정",
description="목록 맨 앞으로 올린다. ★ 대표 사진은 별도 칸이 아니라 **목록의 첫 장**이다"
"(site_payload.primary_media) — 칸을 따로 두면 검색 결과에 뜨는 그림과 화면 첫 장이 갈린다. "
"객실·메뉴 전용 사진(unit_id 가 있는 것)은 대표가 될 수 없다.",
)
async def set_primary_media(
place_id: UUID,
media_id: UUID,
service: MediaService = Depends(),
user_info: UserInfo = Depends(IsValidAccessToken),
):
return RemoveNoneResponse(await service.set_primary(user_info, str(place_id), str(media_id)))
+23 -1
View File
@@ -19,13 +19,14 @@ from datetime import date
from uuid import UUID
from fastapi import APIRouter, Depends, Query
from fastapi.responses import HTMLResponse
from fastapi.responses import HTMLResponse, RedirectResponse
from common.models.gmodel import Res_WebPacketProtocol, UserInfo
from router.v1.site.protocol import (
Req_EditPost, Res_GenerateNow, Res_GenerateOne, Res_GenerationHistory, Res_MyPosts,
)
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
from services import blog_service
from services.post_service import PostService
router = APIRouter(prefix="/v1/site/post", tags=["Site"])
@@ -61,6 +62,27 @@ def _expired_page() -> HTMLResponse:
)
@router.get(path="/edit", summary="수정하기 — 일회용 코드를 세션으로 바꿔 편집 화면으로 보낸다")
async def edit_redirect(t: str = Query(min_length=8, max_length=200), service: PostService = Depends()):
"""메일의 '고쳐서 올리려면'.
★ 액세스 토큰은 **쿼리가 아니라 프래그먼트**로 넘긴다 — 프래그먼트는 서버 로그와 Referer 에
남지 않는다. 예전처럼 쿼리에 실으면 주소가 500자가 되는 것보다, 메일 전달 한 번이
자정까지의 권한 양도가 되는 쪽이 더 나빴다(services/post_service.open_editor)."""
result = await service.open_editor(t)
if not result["success"]:
return _expired_page()
target = (
f"{blog_service.app_origin()}/blog"
f"?placeId={result['place_id']}&postId={result['post_id']}"
f"#auto={result['auto']}"
)
# 303 — 이 주소는 다시 쓸 수 없으니 브라우저가 되돌아오지 않게 한다.
return RedirectResponse(target, status_code=303, headers={
"Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
})
@router.get(path="/approve", response_class=HTMLResponse, summary="승인 확정 — 누르는 즉시 게재 큐에 넣는다")
async def approve_page(t: str = Query(min_length=8, max_length=200), service: PostService = Depends()):
result = await service.decide(t, skip=False)
+8 -2
View File
@@ -82,7 +82,7 @@ async def _context_facts(user: UserInfo, place_id: str, place) -> list[dict]:
return out[:30]
async def _choose(place, fields, facts, message) -> dict:
async def _choose(place, fields, facts, sections, photos, message) -> dict:
"""LLM 한 번. 고른 도구 이름과 인자만 받는다."""
active = provider.active()
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
@@ -94,6 +94,8 @@ async def _choose(place, fields, facts, message) -> dict:
tools=registry.describe(),
fields=fields,
facts=facts,
sections=sections,
photos=photos,
message=message,
),
response_schema=prompt.RESPONSE_SCHEMA,
@@ -129,11 +131,15 @@ async def chat(user: UserInfo, place_id: str, message: str, confirm: dict | None
fields = registry.fields_of(place)
facts = await _context_facts(user, place_id, place)
# ★ 섹션은 이름으로 지목한다("후기 빼줘"). 목록을 안 실으면 모델이 이름을 지어낸다.
sections, _theme = await registry.sections_of(ctx)
# ★ 사진도 이름으로 지목한다. 목록을 안 실으면 모델이 라벨을 지어낸다.
photos = await registry.photo_names(ctx)
# ★ 사이트 상태는 프롬프트에 싣지 않는다. 그 한 줄 때문에 매 턴 사이트 조회 + 슬러그 계산이
# 돌았고, 정작 모델이 필요할 때는 `get_site_status` 도구를 부르면 된다.
try:
choice = await _choose(place, fields, facts, message)
choice = await _choose(place, fields, facts, sections, photos, message)
except LlmError as ex:
LOG.w(f"[agent] 도구 선택 실패: {type(ex).__name__}")
raise AgentError("AGENT_CALL_FAILED") from ex
+222 -1
View File
@@ -23,12 +23,14 @@ from common.enums import ErrorType, PlaceCategory, SourceType
from common.models.gmodel import UserInfo
from crud.fact_crud import FactCRUD
from crud.job_crud import JobQueue
from crud.media_crud import MediaCRUD
from crud.place_crud import PlaceCRUD
from crud.site_crud import SiteCRUD
from router.v1.fact.protocol import Req_UpsertFact
from router.v1.site.protocol import Req_StartBuild
from router.v1.site.protocol import Req_SiteTheme, Req_StartBuild
from services import site_payload
from services.fact_service import FactService
from services.media_service import MediaService
from services.site_service import SiteService
@@ -67,6 +69,10 @@ def _services():
return FactService(FactCRUD(), place_crud), SiteService(SiteCRUD(), place_crud, JobQueue())
def _media_service() -> MediaService:
return MediaService(MediaCRUD(), PlaceCRUD())
# ── 읽기 ────────────────────────────────────────────────────────────────
async def _get_site_status(ctx: ToolContext, args: dict) -> str:
@@ -129,6 +135,169 @@ async def _set_fact(ctx: ToolContext, args: dict) -> str:
return f"{spec.label} 을(를) {value} 로 바꿨습니다. 사이트에 반영하려면 다시 발행해야 해요 — 지금 할까요?"
# ── 페이지 구성 ──────────────────────────────────────────────────────────
async def _sections_of(ctx: ToolContext) -> tuple[list, dict]:
"""지금 발행본에 서는 섹션 목록(해석된 결과)과 저장된 theme.
★ `site_payload._sections` 를 그대로 쓴다 — 발행본이 쓰는 바로 그 함수다. 표를 따로
만들면 에디터·발행본·대화 셋이 갈라지고, 사장님은 "껐는데 나온다" 를 겪는다.
★ 저장값이 없어도 업종 기본이 선다. 그래서 아직 한 번도 디자인을 만지지 않은
사업장에서도 대화가 바로 통한다."""
_fact, site_service = _services()
res = await site_service.get_site(ctx.user, ctx.place_id)
theme = dict((res.site.theme if res.site and res.site.theme else {}) or {})
spec = site_payload._DEFAULT_THEME[PlaceCategory(ctx.place.category).value]["sections"]
return site_payload._sections(theme.get("sections"), spec), theme
def _find_section(rows: list, wanted: str):
"""이름이나 id 로 찾는다. 사장님은 '후기' 처럼 줄여 말한다 — 부분 일치도 받는다.
★ 둘 이상 걸리면 **고르지 않는다**(None). 추측으로 고르면 엉뚱한 섹션을 끄고,
사장님은 그 사실을 발행하고 나서야 안다."""
wanted = (wanted or "").strip()
if not wanted:
return None
exact = [r for r in rows if r["id"] == wanted or r["name"] == wanted]
if len(exact) == 1:
return exact[0]
partial = [r for r in rows if wanted in r["name"]]
return partial[0] if len(partial) == 1 else None
async def _save_sections(ctx: ToolContext, theme: dict, rows: list) -> None:
"""★ theme 의 나머지 칸(colors·fontStyle·look…)을 그대로 들고 간다. sections 만 갈아끼운다 —
통째로 새로 쓰면 사장님이 고른 색과 서체가 말없이 사라진다."""
_fact, site_service = _services()
theme["sections"] = rows
res = await site_service.set_theme(ctx.user, ctx.place_id, Req_SiteTheme(theme=theme))
if not res.result.success:
raise ToolRejected("화면 구성을 저장하지 못했습니다. 빌더 화면에서 확인해 주세요.")
def _layout_line(row: dict) -> str:
mark = "켜짐" if row["enabled"] else "꺼짐"
lock = " (항상 켜짐)" if row["locked"] else ""
return f"· {row['name']} — {mark}{lock}"
async def _list_sections(ctx: ToolContext, args: dict) -> str:
rows, _theme = await _sections_of(ctx)
body = "\n".join(_layout_line(r) for r in rows)
return f"지금 홈페이지는 위에서부터 이 순서입니다.\n{body}"
async def _toggle_section(ctx: ToolContext, args: dict) -> str:
rows, theme = await _sections_of(ctx)
row = _find_section(rows, args.get("name"))
if row is None:
raise ToolRejected("어느 부분을 말씀하시는지 못 찾았어요. '목록' 이라고 하시면 보여드릴게요.")
on = (args.get("enabled") or "").strip().lower() in ("true", "1", "켜", "켜기", "on", "yes")
# ★ 잠긴 섹션은 끌 수 없다. SEO·필수 마크업 때문에 잠긴 것이라, 끄면 발행 게이트에 걸린다
# (site_payload._sections 가 어차피 켜서 내보낸다 — 화면만 거짓말하게 된다).
if row["locked"] and not on:
raise ToolRejected(f"{row['name']} 은(는) 홈페이지에 꼭 있어야 하는 부분이라 끌 수 없어요.")
if row["enabled"] == on:
return f"{row['name']} 은(는) 이미 {'켜져' if on else '꺼져'} 있어요."
row["enabled"] = on
await _save_sections(ctx, theme, rows)
return (f"{row['name']} 을(를) {'켰습니다' if on else '껐습니다'}. "
f"사이트에 반영하려면 다시 발행해야 해요 — 지금 할까요?")
async def _move_section(ctx: ToolContext, args: dict) -> str:
"""★ 배열 순서가 곧 발행본의 섹션 순서다(site_payload._sections)."""
rows, theme = await _sections_of(ctx)
row = _find_section(rows, args.get("name"))
if row is None:
raise ToolRejected("어느 부분을 말씀하시는지 못 찾았어요. '목록' 이라고 하시면 보여드릴게요.")
to = (args.get("to") or "").strip()
rest = [r for r in rows if r["id"] != row["id"]]
if to in ("맨 위", "처음", "위", "top", "first"):
moved, where = [row] + rest, "맨 위로"
elif to in ("맨 아래", "마지막", "아래", "bottom", "last"):
moved, where = rest + [row], "맨 아래로"
else:
anchor = _find_section(rest, to)
if anchor is None:
raise ToolRejected("어디로 옮길지 못 찾았어요. '소개 다음으로' 처럼 말씀해 주세요.")
at = rest.index(anchor) + 1
moved, where = rest[:at] + [row] + rest[at:], f"{anchor['name']} 다음으로"
await _save_sections(ctx, theme, moved)
return (f"{row['name']} 을(를) {where} 옮겼습니다. "
f"사이트에 반영하려면 다시 발행해야 해요 — 지금 할까요?")
# ── 사진 ─────────────────────────────────────────────────────────────────
#
# ★ 업로드·교체는 없다. 이미지 재게시 권리가 미결이라 저장 경로를 일부러 안 만들어 뒀다
# (docs/DECISIONS.md 1-2 · 5-3). 아래는 **이미 있는 사진의 노출과 순서**만 바꾼다.
def _photo_name(row) -> str:
"""사장님이 부를 이름. Vision 이 만든 라벨·alt 가 유일한 단서다."""
return (row.label or "").strip() or (row.alt_text or "").strip() or "이름 없는 사진"
async def _photos(ctx: ToolContext) -> list:
res = await _media_service().list_media(ctx.user, ctx.place_id)
return list(res.media or [])
def _find_photo(rows: list, wanted: str):
"""★ 둘 이상 걸리면 고르지 않는다 — 추측으로 내리면 엉뚱한 사진이 사라지고,
사장님은 발행하고 나서야 안다(섹션과 같은 규칙)."""
wanted = (wanted or "").strip()
if not wanted:
return None
hits = [r for r in rows if wanted in _photo_name(r)]
return hits[0] if len(hits) == 1 else None
async def _list_photos(ctx: ToolContext, args: dict) -> str:
rows = await _photos(ctx)
if not rows:
return "아직 등록된 사진이 없어요."
lines = []
for i, r in enumerate(rows[:15]):
where = " (객실·메뉴 전용)" if r.unit_id else ""
mark = "" if r.publishable else " — 지금은 안 나감"
head = "대표 " if i == 0 and not r.unit_id else ""
lines.append(f"· {head}{_photo_name(r)}{where}{mark}")
more = f"\n(그 밖에 {len(rows) - 15}장 더)" if len(rows) > 15 else ""
return "홈페이지에 있는 사진입니다.\n" + "\n".join(lines) + more
async def _hide_photo(ctx: ToolContext, args: dict) -> str:
rows = await _photos(ctx)
row = _find_photo(rows, args.get("name"))
if row is None:
raise ToolRejected("어느 사진을 말씀하시는지 못 찾았어요. '사진 목록' 이라고 하시면 보여드릴게요.")
res = await _media_service().hide_media(ctx.user, ctx.place_id, str(row.media_id))
if not res.result.success:
raise ToolRejected("그 사진을 내리지 못했습니다. 빌더 화면에서 확인해 주세요.")
return (f"'{_photo_name(row)}' 사진을 내렸습니다. "
f"사이트에 반영하려면 다시 발행해야 해요 — 지금 할까요?")
async def _set_primary_photo(ctx: ToolContext, args: dict) -> str:
rows = await _photos(ctx)
row = _find_photo(rows, args.get("name"))
if row is None:
raise ToolRejected("어느 사진을 말씀하시는지 못 찾았어요. '사진 목록' 이라고 하시면 보여드릴게요.")
if row.unit_id:
raise ToolRejected(f"'{_photo_name(row)}' 은(는) 객실·메뉴 전용 사진이라 대표로 쓸 수 없어요.")
res = await _media_service().set_primary(ctx.user, ctx.place_id, str(row.media_id))
if not res.result.success:
raise ToolRejected("대표 사진을 바꾸지 못했습니다. 빌더 화면에서 확인해 주세요.")
return (f"대표 사진을 '{_photo_name(row)}' 으로 바꿨습니다. "
f"사이트에 반영하려면 다시 발행해야 해요 — 지금 할까요?")
# ── 반쯤 되돌릴 수 있는 것 ───────────────────────────────────────────────
async def _publish(ctx: ToolContext, args: dict) -> str:
@@ -168,6 +337,46 @@ REGISTRY: dict[str, Tool] = {
args={"key": "아래 항목 목록의 key", "value": "바꿀 값"},
run=_set_fact,
),
Tool(
name="list_sections",
grade=ToolGrade.READ,
summary="홈페이지가 어떤 부분들로 어떤 순서로 되어 있는지 보여준다.",
run=_list_sections,
),
Tool(
name="toggle_section",
grade=ToolGrade.REVERSIBLE,
summary="홈페이지의 한 부분을 켜거나 끈다(예: 후기, 사진 갤러리, 예약 안내).",
args={"name": "그 부분의 이름", "enabled": "켜면 true, 끄면 false"},
run=_toggle_section,
),
Tool(
name="move_section",
grade=ToolGrade.REVERSIBLE,
summary="홈페이지에서 한 부분의 위치(순서)를 바꾼다.",
args={"name": "옮길 부분의 이름", "to": "'맨 위' · '맨 아래' · 또는 그 뒤에 올 부분의 이름"},
run=_move_section,
),
Tool(
name="list_photos",
grade=ToolGrade.READ,
summary="홈페이지에 올라가 있는 사진 목록을 보여준다(맨 앞이 대표 사진).",
run=_list_photos,
),
Tool(
name="hide_photo",
grade=ToolGrade.REVERSIBLE,
summary="사진 한 장을 홈페이지에서 내린다. 새 사진을 올리는 것은 아직 못 한다.",
args={"name": "그 사진의 이름(라벨)"},
run=_hide_photo,
),
Tool(
name="set_primary_photo",
grade=ToolGrade.REVERSIBLE,
summary="대표 사진을 바꾼다(검색 결과와 목록 카드에 나오는 그림).",
args={"name": "대표로 쓸 사진의 이름(라벨)"},
run=_set_primary_photo,
),
Tool(
name="publish",
grade=ToolGrade.SEMI,
@@ -179,6 +388,18 @@ REGISTRY: dict[str, Tool] = {
}
async def sections_of(ctx: ToolContext):
"""런타임이 프롬프트에 실을 섹션 목록. 도구가 쓰는 것과 같은 함수여야 한다 —
다르면 모델이 본 이름과 도구가 찾는 이름이 갈린다."""
return await _sections_of(ctx)
async def photo_names(ctx: ToolContext) -> list[str]:
"""런타임이 프롬프트에 실을 사진 이름. 도구가 찾는 이름과 **같은 함수**로 만든다 —
다르면 모델이 본 이름과 도구가 찾는 이름이 갈린다."""
return [_photo_name(r) for r in (await _photos(ctx))[:15]]
def describe() -> list[dict]:
"""프롬프트에 실을 도구 목록. ★ 등급은 싣지 않는다 — 모델이 알 필요도, 정할 이유도 없다."""
return [{"name": t.name, "설명": t.summary, "args": t.args} for t in REGISTRY.values()]
+11 -17
View File
@@ -18,9 +18,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import place_posts, places, sites, users
from common.enums import DBWRType, PostStatus, SiteStatus
from common.logger import LOG
from common.models.gmodel import UserInfo
from crud.post_crud import PostCRUD
from router.v1.validator.dependencies import CreateDayPassToken
from services import blog_service, mail_service, site_payload
from services.snapshot import build_snapshot
@@ -196,15 +194,15 @@ async def generate_one_for_date(place_id: str, target_date: date) -> dict | None
) # None 이면 그 날짜(또는 주제)가 이미 차 있었다 — 다시 시도하지 않는다
def _mail_body(*, place_name: str, post, user, origin: str, approve_token: str) -> str:
def _mail_body(*, place_name: str, post, user, origin: str, approve_token: str, edit_token: str) -> str:
"""승인(누르면 바로 게재) · 수정(빌더 앱 로그인 상태로 그 글 편집 모달) 두 링크만 둔다
(2026-09-17, 사장님 지시: "승인이랑 수정하기 있어야해"). 둘 다 오늘 자정(KST)에
만료된다(2026-09-17, 사장님 지시: "승인이랑 수정모두 자정에 만료") — 그 뒤로는
로그인해서 빌더 앱에서 처리한다. 수정 링크는 토큰 하나짜리 공개 편집 화면 대신,
실제 로그인 세션으로 빌더 앱의 편집 모달을 그대로 연다."""
user_info = UserInfo(user_id=str(user.user_id), id=user.id, role=user.role, token_version=user.token_version)
auto_token = CreateDayPassToken(user_info)
edit_link = f"{origin}/blog?placeId={post.place_id}&postId={post.post_id}&auto={auto_token}"
# ★ 두 링크가 같은 모양이다 — 일회용 코드 하나씩. 예전에는 수정 링크만 500자였는데,
# 길이보다 나쁜 것은 거기 실린 빌더 액세스 토큰이었다(services/post_service.open_editor).
edit_link = f"{origin}/v1/site/post/edit?t={edit_token}"
approve_link = f"{origin}/v1/site/post/approve?t={approve_token}"
return (
f"{place_name} 사이트에 올릴 글을 준비했습니다.\n\n"
@@ -223,30 +221,26 @@ def _notify_address(place, user) -> str:
def _app_origin() -> str:
"""메일의 승인·수정 링크가 향할 곳 — 빌더 앱(과 그 앞의 API)이 사는 오리진.
★ site_payload.publish_origin() 을 쓰면 안 된다 — 그건 발행된 고객 사이트(/s/<slug>)
전용이다. 로컬에선 그게 solution-site 정적 서버(포트 80)라, 메일의 "수정하려면"
링크(/blog?...)가 거기로 가서 404 났다(2026-09-21 실측). SNS 알림(notify_service.py)이
이미 같은 목적으로 쓰는 SOCIAL_APP_ORIGIN 을 그대로 재사용한다 — 설정을 두 벌 안 둔다.
비어 있으면(로컬에서 안 채웠으면) publish_origin() 으로 폴백해 링크가 아예 상대경로로
깨지는 것보다는 낫게 한다."""
return social_config.get("SOCIAL_APP_ORIGIN") or site_payload.publish_origin()
"""blog_service.app_origin() 을 그대로 쓴다 — 라우터도 같은 값을 써야 해서 거기로 옮겼다."""
return blog_service.app_origin()
async def _send_one(place, user, post) -> bool:
"""토큰 발급 → 메일 본문 조립 → 발송 → 성공하면 SENT 로 표시. 실패하면 DB 를 안 건드린다."""
token, token_hash, expires = blog_service.issue_token()
# ★ 수정 링크도 일회용 코드다. 예전에는 여기 빌더 액세스 토큰을 통짜로 실었고,
# 메일 전달 한 번이 자정까지의 권한 양도였다(migrations/0023).
edit_token, edit_hash, _edit_expires = blog_service.issue_token()
body = _mail_body(
place_name=place.name, post=post, user=user,
origin=_app_origin(), approve_token=token,
origin=_app_origin(), approve_token=token, edit_token=edit_token,
)
ok = mail_service.send(to=_notify_address(place, user), subject=f"[{place.name}] 이번 글 올릴까요?", text=body)
if not ok:
return False
await DB_SESSION_MNG.execute_lambda_run(
[place_posts.DBType()],
[lambda s, pid=post.post_id, h=token_hash, e=expires: _crud.mark_sent(s, pid, h, e)],
[lambda s, pid=post.post_id, h=token_hash, e=expires, eh=edit_hash: _crud.mark_sent(s, pid, h, e, eh)],
)
return True
+14
View File
@@ -10,6 +10,7 @@ import re
import secrets
from datetime import date, datetime, timedelta, timezone
from config import social_config
from common.enums import LocalContentType, PlaceCategory, PostStatus, PostTopicKind
from common.logger import LOG
@@ -51,6 +52,19 @@ def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def app_origin() -> str:
"""메일의 승인·수정 링크가 향할 곳 — 빌더 앱(과 그 앞의 API)이 사는 오리진.
★ site_payload.publish_origin() 을 쓰면 안 된다 — 그건 발행된 고객 사이트(/s/<slug>)
전용이다. 로컬에선 그게 solution-site 정적 서버(포트 80)라, 메일의 "수정하려면"
링크(/blog?...)가 거기로 가서 404 났다(2026-09-21 실측). SNS 알림(notify_service.py)이
이미 같은 목적으로 쓰는 SOCIAL_APP_ORIGIN 을 그대로 재사용한다 — 설정을 두 벌 안 둔다.
비어 있으면 publish_origin() 으로 폴백해 링크가 상대경로로 깨지는 것보다는 낫게 한다."""
from services import site_payload
return social_config.get("SOCIAL_APP_ORIGIN") or site_payload.publish_origin()
def issue_token() -> tuple[str, str, object]:
"""(평문, 해시, 만료시각=오늘 자정 KST). 평문은 메일 본문에만 나가고 DB 에는 해시만 둔다.
+67 -1
View File
@@ -5,6 +5,7 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import place_photos, places
from common.enums import DBWRType, ErrorType, MediaStatus, SourceType
from common.utils.gtime import GTime
from common.models.gmodel import UserInfo
from crud.media_crud import IMediaCRUD, MediaCRUD
from crud.place_crud import PlaceCRUD
@@ -21,7 +22,7 @@ def _is_publishable(row) -> bool:
class MediaService:
"""사진 조회.
"""사진 조회 · 노출 여부 · 순서.
★ 이 서비스가 지키는 규칙은 둘이다.
1. 회사 스코프 — 사업장을 먼저 회사 스코프로 로드해서 남의 회사 사진에 닿지 못하게 한다.
@@ -89,3 +90,68 @@ class MediaService:
# 직접 올릴 사진을 몇 장 준비해야 하는지 안다.
res.crawled = sum(1 for r in rows if r.source_type == SourceType.CRAWL.value)
return res
# ---- 노출 여부 · 순서 ----
#
# ★ 업로드·교체는 여기 없다. 이미지 재게시 권리가 미결이라(docs/DECISIONS.md 1-2) 저장
# 경로를 일부러 안 만들어 둔 것이고(5-3), 아래 둘은 **이미 우리 DB 에 있는 사진의
# 노출과 순서**만 바꾼다 — 그 결론이 어느 쪽으로 나든 영향받지 않는다.
async def _owned_photo(self, user_info: UserInfo, place_id: str, media_id: str):
"""사업장 스코프 + 그 사업장의 사진인지. ★ 없는 것과 남의 것을 똑같이 답한다."""
err_type, _place = await self._load_place(user_info, place_id)
if err_type != ErrorType.SUCCESS:
return err_type, None
_err, rows = await DB_SESSION_MNG.execute_lambda(
place_photos.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.list_media(s, uuid.UUID(place_id), None, False, None, False),
)
for row in rows or []:
if str(row.media_id) == str(media_id):
return ErrorType.SUCCESS, row
return ErrorType.MEDIA_NOT_FOUND, None
async def hide_media(self, user_info: UserInfo, place_id: str, media_id: str) -> Res_MediaList:
"""사진을 내린다 — REJECTED 로 내려 발행본에서 빠진다.
★ 지우지 않는다. `origin_url`·`source_type` 이 남아 있어야 재게시 권리(1-2) 결론이
나왔을 때 무엇을 실었는지 되짚을 수 있고, 잘못 내렸을 때 되돌릴 수도 있다."""
err_type, row = await self._owned_photo(user_info, place_id, media_id)
if err_type != ErrorType.SUCCESS:
res = Res_MediaList()
res.result.SetResult(err_type)
return res
await DB_SESSION_MNG.execute_lambda_write(
place_photos.DBType(),
lambda s: self.crud.set_status(s, uuid.UUID(place_id), row.media_id, MediaStatus.REJECTED.value, GTime.UTC()),
)
return await self.list_media(user_info, place_id)
async def set_primary(self, user_info: UserInfo, place_id: str, media_id: str) -> Res_MediaList:
"""대표 사진으로 올린다.
★ 대표는 목록의 **첫 장**이다(site_payload.primary_media) — 별도 칸을 두지 않는다.
그래서 이 사진의 sort_order 를 지금 가장 작은 값보다 하나 더 작게 내리면 된다.
★ 객실·메뉴 전용 사진(unit_id 가 있는 것)은 대표가 될 수 없다 — primary_media 가
그런 사진을 건너뛰므로, 지정해도 화면만 거짓말하게 된다."""
err_type, row = await self._owned_photo(user_info, place_id, media_id)
res = Res_MediaList()
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
if row.unit_id is not None:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
return res
_err, rows = await DB_SESSION_MNG.execute_lambda(
place_photos.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.list_media(s, uuid.UUID(place_id), None, False, None, False),
)
lowest = min((r.sort_order or 0) for r in (rows or [row]))
await DB_SESSION_MNG.execute_lambda_write(
place_photos.DBType(),
lambda s: self.crud.set_sort_order(s, uuid.UUID(place_id), row.media_id, lowest - 1, GTime.UTC()),
)
return await self.list_media(user_info, place_id)
+56
View File
@@ -63,6 +63,62 @@ class PostService:
return None
return post
async def open_editor(self, token: str) -> dict:
"""메일의 '고쳐서 올리려면' — 일회용 코드를 그 자리에서 세션으로 바꾼다.
★ 예전에는 메일 링크에 **빌더 액세스 토큰을 통짜로** 실어 보냈다(sub 에 UserInfo
전체 — role 포함). 주소가 500자였던 것은 곁가지고, 진짜 문제는 **메일 전달 한 번이
그날 자정까지의 권한 양도**였다는 것이다. 브라우저 히스토리·프록시 로그·Referer 에도
그대로 남았다. 이제 URL 에는 일회용 코드만 있고, 토큰은 여기서 만들어 **프래그먼트**로
넘긴다 — 프래그먼트는 서버 로그와 Referer 에 남지 않는다.
★ 실패 이유를 구분해 답하지 않는다(만료·없는 코드·이미 처리됨) — 사장님에게는
'못 쓰는 링크' 하나다(find_by_token 과 같은 규약)."""
from router.v1.validator.dependencies import CreateDayPassToken
token_hash = blog_service.hash_token(token)
post = await DB_SESSION_MNG.execute_lambda(
place_posts.DBType(), DBWRType.DB_READ.value,
lambda s: self.crud.by_edit_token_hash(s, token_hash),
)
if not post or post.status not in (PostStatus.SENT.value, PostStatus.REVIEWED.value):
return {"success": False}
if post.token_expires_at and post.token_expires_at.replace(tzinfo=None) < GTime.UTC():
return {"success": False}
owner = await self._owner_of(post.place_id)
if owner is None:
return {"success": False}
return {
"success": True,
"place_id": str(post.place_id),
"post_id": str(post.post_id),
"auto": CreateDayPassToken(owner),
}
async def _owner_of(self, place_id) -> UserInfo | None:
"""글이 달린 사업장의 주인. ★ 토큰이 가리키는 글에서 사람을 끌어낸다 —
URL 에 누구인지 싣지 않기 위한 조건이다."""
from common.database.model.models import users
def query(session):
return session.execute(
select(users)
.join(places, places.owner_user_id == users.user_id)
.where(
places.place_id == place_id,
places.deleted == False, # noqa: E712
users.deleted == False, # noqa: E712
)
.limit(1)
)
result = await DB_SESSION_MNG.execute_lambda(place_posts.DBType(), DBWRType.DB_READ.value, query)
row = result.scalars().first() if result is not None else None
if row is None:
return None
return UserInfo(user_id=str(row.user_id), id=row.id, role=row.role, token_version=row.token_version)
async def decide(self, token: str, *, skip: bool) -> dict:
post = await self.find_by_token(token)
if not post:
+8 -1
View File
@@ -36,7 +36,8 @@ RESPONSE_SCHEMA = {
}
def build_prompt(*, place_name: str, tools: list[dict], fields: list[dict], facts: list[dict], message: str) -> str:
def build_prompt(*, place_name: str, tools: list[dict], fields: list[dict], facts: list[dict],
sections: list[dict], photos: list[str], message: str) -> str:
"""사장님 발화 → 도구 하나.
★ 모호하면 실행하지 말고 되물으라고 명시한다. 티오더가 "유사한 메뉴가 2개 이상이면
@@ -61,5 +62,11 @@ def build_prompt(*, place_name: str, tools: list[dict], fields: list[dict], fact
지금 저장된 값:
{json.dumps(facts, ensure_ascii=False)}
홈페이지를 이루는 부분들 — 위에서부터의 순서다(toggle_section·move_section 의 name 은 이 중 하나):
{chr(10).join(f"{s['name']}" + (" [끄기 불가]" if s['locked'] else "") + (" (꺼짐)" if not s['enabled'] else "") for s in sections)}
올라가 있는 사진 — 맨 앞이 대표 사진이다(hide_photo·set_primary_photo 의 name 은 이 중 하나):
{chr(10).join(photos) if photos else "(없음)"}
사장님 요청:
{message}'''
@@ -248,3 +248,218 @@ async def test_닫아_두면_대화_요청은_거절된다(client, auth_headers,
assert res.status_code == 409
assert res.json()["detail"] == "AGENT_NOT_CONFIGURED"
assert (await client.get("/v1/agent/status", headers=h)).json()["enabled"] is False
# ── 페이지 구성 (섹션 on/off · 순서) ─────────────────────────────────────
async def _sections(client, headers, place_id):
"""대화가 보는 것과 같은 목록 — 도구가 쓰는 함수를 그대로 쓴다."""
from services.agent.tools import ToolContext, sections_of
from router.v1.validator.dependencies import DecodeAccessToken
from crud.place_crud import PlaceCRUD
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import places
from common.enums import DBWRType
user = DecodeAccessToken(headers["Authorization"].split(" ", 1)[1])
_err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(), DBWRType.DB_READ.value,
lambda s: PlaceCRUD().get_place(s, uuid.UUID(user.user_id), uuid.UUID(place_id)),
)
rows, theme = await sections_of(ToolContext(user=user, place_id=place_id, place=place))
return rows, theme
async def test_저장값이_없어도_업종_기본_구성이_보인다(client, auth_headers, choose, db_engine):
"""★ 아직 디자인을 한 번도 안 만진 사업장에서도 대화가 바로 통해야 한다."""
h, pid = await seed(client, auth_headers)
rows, _theme = await _sections(client, h, pid)
names = {r["name"] for r in rows}
assert "히어로" in names and "객실 안내" in names
async def test_섹션을_끄면_순서는_그대로고_그_칸만_꺼진다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
before, _t = await _sections(client, h, pid)
order_before = [r["id"] for r in before]
choose({"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": "false"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "사진 갤러리 빼줘"})).json()
assert body.get("rejected") is not True, body["reply"]
assert "발행" in body["reply"] # 재발행 안내가 따라붙는다
after, _t = await _sections(client, h, pid)
assert [r["id"] for r in after] == order_before
assert next(r for r in after if r["name"] == "사진 갤러리")["enabled"] is False
async def test_꼭_있어야_하는_부분은_끌_수_없다(client, auth_headers, choose, db_engine):
"""★ 잠긴 섹션은 발행본이 어차피 켜서 내보낸다 — 끌 수 있게 두면 화면만 거짓말한다."""
h, pid = await seed(client, auth_headers)
choose({"tool": "toggle_section", "args": {"name": "히어로", "enabled": "false"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "히어로 빼줘"})).json()
assert body.get("rejected") is True
assert "끌 수 없" in body["reply"]
after, _t = await _sections(client, h, pid)
assert next(r for r in after if r["name"] == "히어로")["enabled"] is True
async def test_순서를_옮기면_배열_순서가_바뀐다(client, auth_headers, choose, db_engine):
"""★ 배열 순서가 곧 발행본의 섹션 순서다(site_payload._sections)."""
h, pid = await seed(client, auth_headers)
choose({"tool": "move_section", "args": {"name": "사진 갤러리", "to": "맨 위"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "사진 갤러리 맨 위로"})).json()
assert body.get("rejected") is not True, body["reply"]
after, _t = await _sections(client, h, pid)
assert after[0]["name"] == "사진 갤러리"
async def test_어느_것인지_모호하면_고르지_않는다(client, auth_headers, choose, db_engine):
"""★ 추측으로 고르면 엉뚱한 부분을 끄고, 사장님은 발행하고 나서야 안다."""
h, pid = await seed(client, auth_headers)
choose({"tool": "toggle_section", "args": {"name": "정보", "enabled": "false"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "정보 빼줘"})).json()
assert body.get("rejected") is True
assert "못 찾았" in body["reply"]
async def test_색과_서체는_손대지_않는다(client, auth_headers, choose, db_engine):
"""★ sections 만 갈아끼운다 — 통째로 새로 쓰면 사장님이 고른 색이 말없이 사라진다."""
h, pid = await seed(client, auth_headers)
await client.post(f"/v1/place/{pid}/site/theme", headers=h, json={
"theme": {"colors": {"accent": "#123456"}, "fontStyle": "고딕"},
})
choose({"tool": "toggle_section", "args": {"name": "사진 갤러리", "enabled": "false"}, "message": ""})
await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "사진 갤러리 빼줘"})
_rows, theme = await _sections(client, h, pid)
assert theme["colors"]["accent"] == "#123456"
assert theme["fontStyle"] == "고딕"
def test_구성_도구의_등급(client=None):
assert tools.REGISTRY["list_sections"].grade == ToolGrade.READ
assert tools.REGISTRY["toggle_section"].grade == ToolGrade.REVERSIBLE
assert tools.REGISTRY["move_section"].grade == ToolGrade.REVERSIBLE
# ── 사진 (내리기 · 대표 지정) ────────────────────────────────────────────
async def _seed_photos(db_engine, place_id, rows):
"""(label, unit_id, sort_order) 로 사진을 심는다. alt 는 채운다 — 빈 alt 는 발행본이 안 그린다."""
from common.enums import MediaStatus, SourceType
async with db_engine.begin() as c:
for label, unit_id, order in rows:
await c.execute(
text("""INSERT INTO place_photos
(media_id, place_id, unit_id, url, source_type, label, alt_text, status, sort_order)
VALUES (:m, :p, :u, :url, :st, :l, :alt, :status, :o)"""),
{"m": uuid.uuid4(), "p": uuid.UUID(place_id), "u": unit_id,
"url": f"https://example.com/{label}.jpg", "st": SourceType.CRAWL.value,
"l": label, "alt": f"{label} 사진", "status": MediaStatus.APPROVED.value, "o": order},
)
async def _photo_rows(db_engine, place_id):
async with db_engine.begin() as c:
result = await c.execute(
text("""SELECT label, status, sort_order FROM place_photos
WHERE place_id=:p AND deleted=false
ORDER BY sort_order ASC, created_at ASC"""),
{"p": uuid.UUID(place_id)},
)
return result.all()
async def test_사진을_내리면_지우지_않고_내려간다(client, auth_headers, choose, db_engine):
"""★ 지우면 origin_url·source_type 이 사라져 재게시 권리 결론이 났을 때 되짚을 수 없다."""
from common.enums import MediaStatus
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("외관", None, 0), ("객실", None, 1)])
choose({"tool": "hide_photo", "args": {"name": "객실"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "객실 사진 내려줘"})).json()
assert body.get("rejected") is not True, body["reply"]
assert "발행" in body["reply"]
rows = await _photo_rows(db_engine, pid)
hidden = next(r for r in rows if r.label == "객실")
assert hidden.status == MediaStatus.REJECTED.value
assert len(rows) == 2 # 행은 남는다
async def test_대표_사진은_목록의_첫_장이_된다(client, auth_headers, choose, db_engine):
"""★ 별도 칸을 두지 않는다 — site_payload.primary_media 가 '첫 장' 을 쓴다."""
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("외관", None, 0), ("수영장", None, 1)])
choose({"tool": "set_primary_photo", "args": {"name": "수영장"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "대표 사진 수영장으로"})).json()
assert body.get("rejected") is not True, body["reply"]
rows = await _photo_rows(db_engine, pid)
assert rows[0].label == "수영장"
async def test_객실_전용_사진은_대표가_될_수_없다(client, auth_headers, choose, db_engine):
"""★ primary_media 가 unit_id 있는 사진을 건너뛴다 — 지정하게 두면 화면만 거짓말한다."""
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("외관", None, 0), ("침대", uuid.uuid4(), 1)])
choose({"tool": "set_primary_photo", "args": {"name": "침대"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "대표 사진 침대로"})).json()
assert body.get("rejected") is True
assert "대표로 쓸 수 없" in body["reply"]
rows = await _photo_rows(db_engine, pid)
assert rows[0].label == "외관"
async def test_어느_사진인지_모호하면_고르지_않는다(client, auth_headers, choose, db_engine):
h, pid = await seed(client, auth_headers)
await _seed_photos(db_engine, pid, [("객실 A", None, 0), ("객실 B", None, 1)])
choose({"tool": "hide_photo", "args": {"name": "객실"}, "message": ""})
body = (await client.post(f"/v1/agent/chat/{pid}", headers=h, json={"message": "객실 사진 내려줘"})).json()
assert body.get("rejected") is True
assert "못 찾았" in body["reply"]
rows = await _photo_rows(db_engine, pid)
assert all(r.status != 3 for r in rows) # 아무것도 안 내려갔다
async def test_남의_가게_사진에는_닿지_못한다(client, auth_headers, db_engine):
"""서비스가 사업장 스코프를 먼저 건다 — 없는 것과 남의 것을 똑같이 답한다."""
from crud.media_crud import MediaCRUD
from crud.place_crud import PlaceCRUD
from router.v1.validator.dependencies import DecodeAccessToken
from services.media_service import MediaService
h, pid = await seed(client, auth_headers, "내가게")
await _seed_photos(db_engine, pid, [("외관", None, 0)])
async with db_engine.begin() as c:
media_id = (
await c.execute(text("SELECT media_id FROM place_photos WHERE place_id=:p"), {"p": uuid.UUID(pid)})
).scalar_one()
other = await auth_headers("photo-outsider")
outsider = DecodeAccessToken(other["Authorization"].split(" ", 1)[1])
res = await MediaService(MediaCRUD(), PlaceCRUD()).hide_media(outsider, pid, str(media_id))
assert res.result.success is False
rows = await _photo_rows(db_engine, pid)
assert rows[0].status != 3
async def test_업로드_도구는_만들지_않았다():
"""★ 이미지 재게시 권리가 미결이라 저장 경로를 일부러 안 만들어 뒀다(DECISIONS 1-2·5-3).
도구가 생기면 그 결정을 코드가 먼저 풀어 버린다."""
names = set(tools.REGISTRY)
assert not {n for n in names if "upload" in n or "replace" in n}
assert tools.REGISTRY["list_photos"].grade == ToolGrade.READ
assert tools.REGISTRY["hide_photo"].grade == ToolGrade.REVERSIBLE
assert tools.REGISTRY["set_primary_photo"].grade == ToolGrade.REVERSIBLE
+124 -7
View File
@@ -9,7 +9,7 @@
- 여기서도 금칙 게이트는 그대로 탄다 — 로그인했다고 우회되지 않는다
"""
import uuid
from datetime import date, timedelta, timezone
from datetime import date, datetime, timedelta, timezone
from sqlalchemy import text
@@ -814,9 +814,12 @@ async def test_mail_has_one_click_approve_and_autologin_edit_links(client, db_en
assert sent == 1
mail_text = sent_calls[0]["text"]
assert "/v1/site/post/approve?t=" in mail_text
assert "/blog?placeId=" in mail_text
assert f"postId={post_id}" in mail_text
assert "auto=" in mail_text
# ★ 수정 링크도 일회용 코드다(2026-09-28). 예전에는 여기 빌더 액세스 토큰을 통짜로 실어
# `/blog?placeId=..&postId=..&auto=<JWT>` 를 보냈다 — 주소가 500자였던 것은 곁가지고,
# 진짜 문제는 **메일 전달 한 번이 그날 자정까지의 권한 양도**였다는 것이다.
assert "/v1/site/post/edit?t=" in mail_text
assert "auto=" not in mail_text
assert "eyJ" not in mail_text
async def test_mail_links_use_the_builder_app_origin_not_the_published_site_origin(
@@ -825,14 +828,16 @@ async def test_mail_links_use_the_builder_app_origin_not_the_published_site_orig
"""수정·승인 링크는 빌더 앱(SOCIAL_APP_ORIGIN)으로 가야 한다 — 발행된 사이트 오리진
(site_payload.publish_origin, 로컬에선 solution-site 정적 서버 포트 80)으로 가면
404가 난다(2026-09-21 실측: 메일의 '수정하려면' 링크가 거기로 가서 404)."""
from services import blog_jobs, mail_service, site_payload
from services import blog_jobs, blog_service, mail_service, site_payload
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
sent_calls = []
monkeypatch.setattr(mail_service, "send", lambda **kwargs: sent_calls.append(kwargs) or True)
monkeypatch.setattr(site_payload, "publish_origin", lambda: "http://published-site-origin")
# ★ 오리진 계산은 blog_service.app_origin() 으로 옮겼다 — 라우터(수정 링크 리다이렉트)도
# 같은 값을 써야 해서다. 그래서 패치 대상도 거기다.
monkeypatch.setattr(
blog_jobs.social_config, "get",
blog_service.social_config, "get",
lambda name, default="": "http://builder-app-origin" if name == "SOCIAL_APP_ORIGIN" else default,
)
@@ -850,7 +855,9 @@ async def test_mail_links_use_the_builder_app_origin_not_the_published_site_orig
assert sent == 1
mail_text = sent_calls[0]["text"]
assert "http://builder-app-origin/blog?placeId=" in mail_text
# 두 링크 다 빌더 앱 오리진이어야 한다. 수정 링크는 일회용 코드를 거쳐 /blog 로
# 리다이렉트되므로(router/v1/site/post.py edit_redirect) 메일에는 /v1/site/post/edit 이 실린다.
assert "http://builder-app-origin/v1/site/post/edit?t=" in mail_text
assert "http://builder-app-origin/v1/site/post/approve?t=" in mail_text
assert "published-site-origin" not in mail_text
@@ -922,3 +929,113 @@ async def test_generate_one_is_scoped_to_owner(client, db_engine, auth_headers):
)
assert res.json()["result"]["success"] is False
# ── 메일 '고쳐서 올리려면' — 일회용 코드 ────────────────────────────────
async def _seed_edit_token(db_engine, post_id, *, expired=False):
from services import blog_service
token, token_hash, expires = blog_service.issue_token()
if expired:
expires = datetime.now(timezone.utc) - timedelta(minutes=1)
aware = expires.replace(tzinfo=timezone.utc) if expires.tzinfo is None else expires
async with db_engine.begin() as conn:
await conn.execute(
text("UPDATE place_posts SET edit_token_hash=:h, token_expires_at=:e WHERE post_id=:id"),
{"h": token_hash, "e": aware, "id": post_id},
)
return token
async def test_수정_링크는_짧고_액세스_토큰을_싣지_않는다(client, db_engine, auth_headers):
"""★ 예전에는 이 링크에 빌더 액세스 토큰을 통짜로 실었다 — 메일 전달 한 번이
그날 자정까지의 권한 양도였고, 주소는 500자였다."""
h = await auth_headers("blogedit1")
place_id = await _place(client, h)
post_id = await _seed_post(db_engine, place_id, status=PostStatus.SENT)
token = await _seed_edit_token(db_engine, post_id)
res = await client.get(f"/v1/site/post/edit?t={token}", follow_redirects=False)
assert res.status_code == 303
location = res.headers["location"]
# 액세스 토큰은 **프래그먼트**로만 간다 — 서버 로그·Referer 에 남지 않는다.
path_and_query = location.split("#", 1)[0]
assert "auto=" not in path_and_query
assert "#auto=" in location
assert str(post_id) in path_and_query and str(place_id) in path_and_query
assert res.headers["Referrer-Policy"] == "no-referrer"
async def test_수정_링크의_토큰은_그_사장님_것이다(client, db_engine, auth_headers):
"""URL 에 누구인지 싣지 않는다 — 토큰이 가리키는 글에서 사람을 끌어낸다."""
from router.v1.validator.dependencies import DecodeAccessToken
h = await auth_headers("blogedit2")
place_id = await _place(client, h)
post_id = await _seed_post(db_engine, place_id, status=PostStatus.SENT)
token = await _seed_edit_token(db_engine, post_id)
res = await client.get(f"/v1/site/post/edit?t={token}", follow_redirects=False)
auto = res.headers["location"].split("#auto=", 1)[1]
async with db_engine.begin() as conn:
owner = (
await conn.execute(text("SELECT owner_user_id FROM places WHERE place_id=:p"), {"p": place_id})
).scalar_one()
assert DecodeAccessToken(auto).user_id == str(owner)
async def test_만료된_수정_링크는_안_먹는다(client, db_engine, auth_headers):
h = await auth_headers("blogedit3")
place_id = await _place(client, h)
post_id = await _seed_post(db_engine, place_id, status=PostStatus.SENT)
token = await _seed_edit_token(db_engine, post_id, expired=True)
res = await client.get(f"/v1/site/post/edit?t={token}", follow_redirects=False)
assert res.status_code == 200 # 만료 안내 화면
assert "auto=" not in res.text
async def test_없는_수정_코드는_이유를_구분해_답하지_않는다(client, db_engine):
res = await client.get("/v1/site/post/edit?t=ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ", follow_redirects=False)
assert res.status_code == 200
assert "auto=" not in res.text
async def test_승인_코드로는_수정_링크를_열_수_없다(client, db_engine, auth_headers):
"""★ 두 코드는 서로 다른 칸에 산다. 하나로 둘 다 되면 일회성이 무의미해진다."""
from services import blog_service
h = await auth_headers("blogedit4")
place_id = await _place(client, h)
post_id = await _seed_post(db_engine, place_id, status=PostStatus.SENT)
approve_token, approve_hash, expires = blog_service.issue_token()
aware = expires.replace(tzinfo=timezone.utc) if expires.tzinfo is None else expires
async with db_engine.begin() as conn:
await conn.execute(
text("UPDATE place_posts SET approve_token_hash=:h, token_expires_at=:e WHERE post_id=:id"),
{"h": approve_hash, "e": aware, "id": post_id},
)
res = await client.get(f"/v1/site/post/edit?t={approve_token}", follow_redirects=False)
assert res.status_code == 200
assert "auto=" not in res.text
def test_메일_본문에_액세스_토큰이_없다():
"""★ 본문이 곧 유출 경로다 — 전달 한 번으로 권한이 넘어가면 안 된다."""
from types import SimpleNamespace
from services import blog_jobs
post = SimpleNamespace(post_id=uuid.uuid4(), place_id=uuid.uuid4(), body=BODY)
user = SimpleNamespace(user_id=uuid.uuid4(), id="owner", role=1, token_version=1, email="a@b.c")
body = blog_jobs._mail_body(
place_name="테스트", post=post, user=user, origin="https://example.com",
approve_token="APPROVE_CODE", edit_token="EDIT_CODE",
)
assert "APPROVE_CODE" in body and "EDIT_CODE" in body
assert "auto=" not in body # 액세스 토큰이 실리던 자리
assert "eyJ" not in body # JWT 의 머리글자
longest = max(len(word) for word in body.split())
assert longest < 120, f"링크가 아직 길다: {longest}자"
+9 -1
View File
@@ -23,11 +23,19 @@ function useRestoreSession() {
useEffect(() => {
let alive = true;
const autoToken = new URLSearchParams(window.location.search).get('auto');
// ★ 프래그먼트(#auto=)를 먼저 본다. 메일의 '고쳐서 올리려면' 링크가 그쪽으로 넘긴다 —
// 프래그먼트는 서버 로그와 Referer 에 남지 않기 때문이다. 쿼리(?auto=)도 계속 받는다:
// 이미 나간 메일이 자정까지 살아 있고, 그걸 깨면 그 링크들이 통째로 죽는다.
const hashToken = new URLSearchParams(window.location.hash.replace(/^#/, '')).get('auto');
const autoToken = hashToken ?? new URLSearchParams(window.location.search).get('auto');
const claims = autoToken ? decodeJwtSubject(autoToken) : null;
if (autoToken && claims) {
setTokens(autoToken);
setUser({userId: claims.user_id, id: claims.id, role: claims.role});
// 주소창에 토큰을 남기지 않는다 — 히스토리·스크린샷·어깨너머로 새는 자리다.
if (hashToken) {
window.history.replaceState(null, '', window.location.pathname + window.location.search);
}
finishRestore();
return;
}