[feat] solution/backend,frontend: 카카오톡 채널 신원 연결 — 에이전트 1단계
카카오 채널이 주는 발화자 식별자는 **채널 단위 익명 키**라 우리 user_id 와 관계가 없다. 다른 엔드포인트는 전부 place_crud.get_place(s, owner_user_id, place_id) 로 소유자 범위를 지키는데 채널 발화에는 그 owner_user_id 를 줄 근거가 없다 — 매핑이 없으면 채널 진입점만 소유자 범위 밖에 놓이고, 채널에 말을 건 아무나가 남의 가게를 고친다. - postgres-init: owner_kakao_links(0021 + init.sql). 부분 유니크 셋 중 uq_kakao_link_channel_key(한 카카오 계정 = 한 사장님)가 없으면 "어느 가게 이야기냐" 가 대화가 아니라 DB 에서 갈라진다 - services/kakao_link_service: 일회성은 코드 값이 아니라 WHERE status='PENDING' CAS 한 문장이 보장한다. 실패는 전부 같은 에러 — 없는 코드·만료·시도초과를 구분해 답하면 6자리의 유효성을 밖에서 탐색할 수 있다 - 코드는 sha256 만 저장. 손으로 치는 짧은 값이라 평문이면 DB 를 읽는 쪽이 곧 연결 권한이다. 글자에서 0·O·1·I·L 제외 — 잘못 읽으면 원인이 화면에 안 보인다 - router/v1/agent/kakao: 셋 다 no-store·no-referrer·noindex. ★ 소비(redeem) 엔드포인트는 일부러 없다 — 웹훅 서명 검증 전에 공개 소비 경로를 열면 누구나 6자리를 대입해 남의 계정에 자기 카톡을 붙인다 - config/agent_config: social_config 와 일부러 가름. SNS 게재는 되돌릴 수 없는 대외 발화, 에이전트는 자기 사이트를 고치는 창구 — 승인 강도가 다르다 - frontend/features/agent: /sites 의 Threads 카드 옆. 연결은 사람 단위라 같은 자리다 - docs/AGENT.md 신설, CLAUDE.md 색인·함정, DEVLOG test_kakao_link.py 15 passed. 전체 780 passed / 50 failed — 그 50건은 HEAD 에서도 동일(워크트리 대조), 기존 이슈로 이번 변경과 무관. npm run lint 통과 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
94ae4a825a
commit
16b17bc91c
16 files changed
+944
No files matched your search
@@ -0,0 +1,146 @@
|
||||
import {useCallback, useEffect, useState} from 'react';
|
||||
import {Loader2, MessageCircle, Unlink} from 'lucide-react';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {agentApi, type KakaoLinkCode, type KakaoLinkState} from './api';
|
||||
|
||||
/**
|
||||
* 카카오톡 채널 연결 — **'내 사이트' 화면에 한 자리**.
|
||||
*
|
||||
* ★ 왜 사업장 화면이 아닌가
|
||||
* 연결은 `user` 단위다(표도 그렇게 생겼다 — `owner_kakao_links`). 버튼이 사업장 안에
|
||||
* 있으면 사장님은 **업장 수만큼 연결해야 하는 줄 안다.** 연결은 한 번이다.
|
||||
* SocialConnectionCard 가 같은 이유로 여기 있다.
|
||||
*
|
||||
* ★ 코드는 화면에만 한 번 뜬다.
|
||||
* 서버는 sha256 만 들고 있어서 **다시 보여줄 수 없다.** 새로고침하면 사라지므로
|
||||
* "다시 받기" 를 항상 옆에 둔다 — 못 보여주는 것과 잃어버린 것은 다른 상태이고,
|
||||
* 화면이 그 둘을 구별해 말해야 한다.
|
||||
*
|
||||
* ★ 준비 전에도 자리는 보여주고 버튼만 죽인다.
|
||||
* 숨기면 기능이 없는 것처럼 보인다(2026-09-14, Threads 카드에서 실제로 겪었다).
|
||||
*/
|
||||
export function KakaoChannelCard() {
|
||||
const [state, setState] = useState<KakaoLinkState | null>(null);
|
||||
const [issued, setIssued] = useState<KakaoLinkCode | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setState(await agentApi<KakaoLinkState>('/kakao/link'));
|
||||
} catch {
|
||||
// 연결 상태를 못 읽는 것은 사이트 목록을 못 보여줄 이유가 아니다 — 조용히 접는다.
|
||||
setState(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
// 상태를 아직 못 읽었을 때만 접는다(로그인 직후 한순간). '준비 안 됨' 과는 다르다.
|
||||
if (!state) return null;
|
||||
|
||||
const ready = state.connection_enabled;
|
||||
const linked = state.status === 'LINKED';
|
||||
const channelUrl = issued?.channel_url || state.channel_url;
|
||||
|
||||
async function run(fn: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await fn();
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '요청을 처리하지 못했습니다.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const issue = () =>
|
||||
run(async () => {
|
||||
setIssued(await agentApi<KakaoLinkCode>('/kakao/link/code', {}));
|
||||
});
|
||||
|
||||
const disconnect = () =>
|
||||
run(async () => {
|
||||
setIssued(null);
|
||||
await agentApi('/kakao/link/disconnect', {});
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="mb-4 rounded-xl border border-border p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm font-bold">카카오톡으로 관리 · 채널 연결</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{!ready
|
||||
? '채널을 준비하고 있습니다. 열리면 여기서 연결합니다.'
|
||||
: linked
|
||||
? '연결되어 있습니다. 카카오톡에서 가게 정보를 고치고 사이트를 발행할 수 있습니다.'
|
||||
: '연결해 두면 카카오톡 대화창에서 가게 정보를 고치고 사이트를 발행할 수 있습니다.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-wrap gap-2">
|
||||
{!linked && (
|
||||
<Button size="sm" variant="primary" disabled={busy || !ready} onClick={issue}>
|
||||
{busy ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<MessageCircle className="size-4" />
|
||||
)}
|
||||
<span>{state.status === 'PENDING' ? '코드 다시 받기' : '카카오톡 연결'}</span>
|
||||
</Button>
|
||||
)}
|
||||
{(linked || state.status === 'PENDING') && (
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={disconnect}>
|
||||
<Unlink className="size-4" />
|
||||
<span>{linked ? '연결 해제' : '연결 취소'}</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{issued && !linked && (
|
||||
<div className="mt-3 border-t border-border pt-3">
|
||||
<p className="text-xs font-bold">카카오톡 채널에 이 코드를 보내 주세요</p>
|
||||
<p className="mt-2 font-mono text-2xl font-bold tracking-[0.3em]">{issued.code}</p>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{new Date(issued.expires_at).toLocaleTimeString('ko-KR', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
까지 쓸 수 있습니다. 화면을 나가면 코드를 다시 볼 수 없어요 — 그때는 다시 받으면 됩니다.
|
||||
</p>
|
||||
{channelUrl && (
|
||||
<p className="mt-2 text-xs">
|
||||
<a
|
||||
href={channelUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-bold underline underline-offset-4"
|
||||
>
|
||||
카카오톡 채널 열기 →
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 코드를 냈는데 화면을 새로 열어 코드가 사라진 경우. '기다리는 중' 을 숨기지 않는다. */}
|
||||
{!issued && state.status === 'PENDING' && (
|
||||
<p className="mt-3 text-xs text-muted-foreground">
|
||||
보낸 코드를 기다리고 있습니다. 코드를 잃어버렸다면 다시 받아 주세요.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="mt-3 text-xs text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import {getAccessToken} from '@/api';
|
||||
|
||||
/**
|
||||
* 사장님 에이전트 — 카카오톡 채널 연결.
|
||||
*
|
||||
* ★ social 과 파일을 가른 이유는 도메인이 다르기 때문이다. SNS 게재는 되돌릴 수 없는
|
||||
* 대외 발화이고, 이건 사장님이 자기 사이트를 고치는 창구다. 한 사전에 섞으면
|
||||
* 에러 문구가 어느 기능의 것인지 화면에서 구별되지 않는다.
|
||||
*/
|
||||
export type KakaoLinkState = {
|
||||
connection_enabled: boolean;
|
||||
channel_url: string;
|
||||
status: 'PENDING' | 'LINKED' | 'REVOKED' | null;
|
||||
linked_at: string | null;
|
||||
code_expires_at: string | null;
|
||||
};
|
||||
|
||||
export type KakaoLinkCode = {code: string; expires_at: string; channel_url: string};
|
||||
|
||||
const base = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800';
|
||||
|
||||
const messages: Record<string, string> = {
|
||||
KAKAO_LINK_DISABLED: '카카오톡 채널을 준비하고 있습니다. 준비되면 여기서 연결할 수 있습니다.',
|
||||
KAKAO_LINK_ALREADY: '이미 연결되어 있습니다.',
|
||||
KAKAO_LINK_CODE_INVALID: '코드가 맞지 않거나 시간이 지났습니다. 새 코드를 받아 주세요.',
|
||||
KAKAO_LINK_NOT_FOUND: '연결된 카카오톡 계정이 없습니다.',
|
||||
KAKAO_LINK_TAKEN: '그 카카오톡 계정은 다른 계정에 이미 연결되어 있습니다.',
|
||||
};
|
||||
|
||||
export async function agentApi<T>(path: string, data?: unknown): Promise<T> {
|
||||
const token = getAccessToken();
|
||||
const response = await fetch(`${base}/v1/agent${path}`, {
|
||||
method: data === undefined ? 'GET' : 'POST',
|
||||
credentials: 'include',
|
||||
// 연결 코드가 오가는 요청이다 — 리퍼러로 새거나 캐시에 남지 않게 한다.
|
||||
referrerPolicy: 'no-referrer',
|
||||
cache: 'no-store',
|
||||
headers: {'Content-Type': 'application/json', ...(token ? {Authorization: `Bearer ${token}`} : {})},
|
||||
body: data === undefined ? undefined : JSON.stringify(data),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(messages[result.detail] ?? '요청을 처리하지 못했습니다. 잠시 후 다시 확인해 주세요.');
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {SocialConnectionCard} from '@/features/social/SocialConnectionCard';
|
||||
import {KakaoChannelCard} from '@/features/agent/KakaoChannelCard';
|
||||
import {SocialConnectionNotice} from '@/features/social/SocialConnectionNotice';
|
||||
import {useMemo, useState} from 'react';
|
||||
import {Link, useNavigate} from 'react-router';
|
||||
@@ -259,6 +260,8 @@ export function SitesPage() {
|
||||
<SocialConnectionNotice />
|
||||
{/* 연결은 사업장이 아니라 사람 단위다 — 목록 위에 한 자리만 둔다(SocialConnectionCard 주석). */}
|
||||
<SocialConnectionCard />
|
||||
{/* 카카오톡 연결도 사람 단위다 — 같은 자리에 나란히 둔다(KakaoChannelCard 주석). */}
|
||||
<KakaoChannelCard />
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center py-20 text-muted-foreground">
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
|
||||
Reference in new issue
Block a user