diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx index 5564b12..a742a85 100644 --- a/frontend/src/app/layout.tsx +++ b/frontend/src/app/layout.tsx @@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next"; import localFont from "next/font/local"; import { AuthGuard } from "@/components/auth/auth-guard"; +import { ConsentGate } from "@/components/auth/consent-gate"; import { LoginRequiredProvider } from "@/components/auth/login-required"; import { BOTTOM_TAB_BAR_SPACE, BottomTabBar } from "@/components/layout/bottom-tab-bar"; import { StartupProvider } from "@/components/screens/startup-provider"; @@ -44,7 +45,9 @@ export default function RootLayout({ children }: LayoutProps<"/">) {
- {children} + + {children} +
diff --git a/frontend/src/components/auth/auth-callback-view.tsx b/frontend/src/components/auth/auth-callback-view.tsx index 7c6594d..cb6967d 100644 --- a/frontend/src/components/auth/auth-callback-view.tsx +++ b/frontend/src/components/auth/auth-callback-view.tsx @@ -6,7 +6,6 @@ import { useEffect, useRef } from "react"; import { completeLogin } from "@/lib/api/auth"; import { loginHref, parseCallbackQuery } from "@/lib/auth"; import { takeLoginReturn } from "@/lib/return-to"; -import { forgetTermsAgreement } from "@/lib/terms"; /** * 로그인 콜백 (A27 이 돌려보내는 화면). 1회용 코드를 주소에서 바로 지우고 A01 로 교환한다. @@ -26,8 +25,6 @@ export function AuthCallbackView() { window.history.replaceState(null, "", window.location.pathname); if (result.kind === "error") { - // 약관이 바뀌었으면 기억한 동의를 지우고 로그인 화면에서 다시 묻는다 - if (result.error === "terms_outdated") forgetTermsAgreement(); router.replace(loginHref(result.error)); return; } diff --git a/frontend/src/components/auth/consent-gate.tsx b/frontend/src/components/auth/consent-gate.tsx new file mode 100644 index 0000000..6a910b5 --- /dev/null +++ b/frontend/src/components/auth/consent-gate.tsx @@ -0,0 +1,294 @@ +"use client"; + +import Link from "next/link"; +import { CircleAlert, ShieldCheck } from "lucide-react"; +import { usePathname, useRouter } from "next/navigation"; +import { useEffect, useId, useState, useSyncExternalStore, type ReactNode } from "react"; + +import { SampleDataNotice } from "@/components/feedback/sample-data"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Label } from "@/components/ui/label"; +import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"; +import { ERROR_COPY, toErrorKind } from "@/lib/api/errors"; +import { isMockMode } from "@/lib/api/mock"; +import { agreeTerms, fetchTermsAgreed, isTermsOutdated, withdraw } from "@/lib/api/users"; +import { loginHref } from "@/lib/auth"; +import { + consentGateView, + forgetConsent, + getConsentStatus, + hasRememberedConsent, + rememberConsent, + setConsentStatus, + subscribeConsent, + toggleAll, +} from "@/lib/consent"; +import { getSessionStatus } from "@/lib/session"; +import { PRIVACY_HREF, TERMS_HREF, TERMS_VERSION } from "@/lib/terms"; +import { useSessionStatus } from "@/lib/use-session"; +import { cn } from "@/lib/utils"; + +/** + * 로그인 직후 약관 동의 단계 (Jira SCRUM-211, 기획 M10 R8, Notion API 명세서 A28·A34·A30). + * 로그인한 상태에서 A28 의 terms_agreed 가 false 면(신규 가입·약관 버전 변경) 닫을 수 없는 창(휴대폰 폭은 하단, 넓은 화면은 가운데)으로 동의를 받는다. + * 동의하면 A34 를 부르고 지금 화면(로그인 전에 보던 화면)을 그대로 쓴다. 거부하면 A30 으로 계정을 지우고 로그인 화면으로 간다. + * 동의하기 전에는 보호 화면을 그리지 않는다. 다른 API 가 403 terms_not_agreed 를 줘도 이 창을 다시 띄운다. + */ +export function ConsentGate({ children }: { children: ReactNode }) { + const session = useSessionStatus(); + const pathname = usePathname() ?? "/"; + const status = useSyncExternalStore(subscribeConsent, getConsentStatus, () => "unknown" as const); + + // 로그인 상태가 바뀌거나 다시 확인할 때(unknown) A28 로 동의 여부를 본다 + useEffect(() => { + if (session !== "logged_in") { + forgetConsent(); + setConsentStatus("unknown"); + return; + } + if (status !== "unknown") return; + if (hasRememberedConsent(TERMS_VERSION)) { + setConsentStatus("agreed"); + return; + } + // checking 으로 바꾸면 이 effect 가 다시 돌므로 요청을 취소하지 않고, 응답이 왔을 때 아직 로그인 상태인지 본다 + setConsentStatus("checking"); + fetchTermsAgreed() + .then((agreed) => { + if (getSessionStatus() !== "logged_in" || getConsentStatus() !== "checking") return; + if (agreed) rememberConsent(TERMS_VERSION); + setConsentStatus(agreed ? "agreed" : "needed"); + }) + .catch((error: unknown) => { + if (getSessionStatus() !== "logged_in" || getConsentStatus() !== "checking") return; + // 401 이면 세션이 지워져 위의 로그아웃 분기로 다시 온다 + setConsentStatus(toErrorKind(error) === "unauthorized" ? "unknown" : "error"); + }); + }, [session, status]); + + const view = consentGateView(session, status, pathname); + + return ( + <> + {view.holdProtected ? ( +
+

+ {status === "needed" ? "약관에 동의하면 이어서 볼 수 있어요." : "약관 동의 여부를 확인하는 중이에요…"} +

+
+ ) : ( + children + )} + + event.preventDefault()} + onInteractOutside={(event) => event.preventDefault()} + className="gap-0 overflow-y-auto" + > + {status === "error" ? ( + setConsentStatus("unknown")} /> + ) : ( + setConsentStatus("agreed")} /> + )} + + + + ); +} + +function CheckFailed({ onRetry }: { onRetry: () => void }) { + return ( + <> + + 약관 동의 여부를 확인하지 못했어요 + + 인터넷 연결을 확인한 뒤 다시 시도해 주세요. 확인되기 전에는 진단·계약서 기능을 쓸 수 없어요. + + +
+ +
+ + ); +} + +type FormError = { title: string; description: string }; + +function ConsentForm({ onAgreed }: { onAgreed: () => void }) { + const router = useRouter(); + const allId = useId(); + const termsId = useId(); + const ageId = useId(); + const [checks, setChecks] = useState({ terms: false, age: false }); + const [step, setStep] = useState<"form" | "confirmDecline">("form"); + const [busy, setBusy] = useState<"agree" | "decline" | null>(null); + const [error, setError] = useState(null); + const all = checks.terms && checks.age; + + async function agree() { + setBusy("agree"); + setError(null); + try { + await agreeTerms(TERMS_VERSION); + rememberConsent(TERMS_VERSION); + onAgreed(); + } catch (cause) { + setError( + isTermsOutdated(cause) + ? { title: "약관이 바뀌었어요", description: "화면을 새로 고친 뒤 바뀐 약관을 확인하고 다시 동의해 주세요." } + : ERROR_COPY[toErrorKind(cause)], + ); + } finally { + setBusy(null); + } + } + + async function decline() { + setBusy("decline"); + setError(null); + try { + await withdraw(); + router.replace(loginHref()); + } catch (cause) { + setError(ERROR_COPY[toErrorKind(cause)]); + setBusy(null); + } + } + + if (step === "confirmDecline") { + return ( + <> + + 동의하지 않고 나갈까요? + + 필수 항목에 동의하지 않으면 서비스를 쓸 수 없어요. 방금 만든 계정은 바로 삭제되고, 다음에 다시 로그인하면 + 처음부터 동의를 받아요. + + +
+ {error ? : null} + + +
+ + ); + } + + return ( + <> + + + + 서비스 이용에 동의해 주세요 + + 진단·계약서 확인을 쓰려면 아래 필수 항목에 동의해야 해요. 동의하면 보던 화면에서 바로 이어서 쓸 수 있어요. + + + +
+ {isMockMode() && 예시 모드라 동의 기록은 이 브라우저에만 남아요.} + +
+ 서비스 이용 동의 +
+ setChecks(toggleAll)} /> + +
+
+
+ setChecks((prev) => ({ ...prev, terms: value === true }))} + className="mt-0.5" + /> +
+ +

+ + 이용약관 보기 + + + 개인정보 처리방침 보기 + +

+
+
+
+ setChecks((prev) => ({ ...prev, age: value === true }))} + className="mt-0.5" + /> + +
+
+ + {error ? : null} + +
+ + +
+
+ + ); +} + +function FormAlert({ error }: { error: FormError }) { + return ( +
+
+ ); +} diff --git a/frontend/src/components/auth/login-panel.tsx b/frontend/src/components/auth/login-panel.tsx index 762ba28..561c9ff 100644 --- a/frontend/src/components/auth/login-panel.tsx +++ b/frontend/src/components/auth/login-panel.tsx @@ -3,27 +3,16 @@ import Link from "next/link"; import { CircleAlert } from "lucide-react"; import { useRouter } from "next/navigation"; -import { useId, useState, useSyncExternalStore } from "react"; +import { useState } from "react"; import { SocialLoginButton } from "@/components/auth/social-login-button"; import { SampleDataNotice } from "@/components/feedback/sample-data"; -import { Checkbox } from "@/components/ui/checkbox"; -import { Label } from "@/components/ui/label"; import { completeLogin, prepareLogin } from "@/lib/api/auth"; import { isMockMode } from "@/lib/api/mock"; import { callApp, getAppInfo, isInApp } from "@/lib/bridge"; import { LOGIN_ERROR_COPY, parseCallbackQuery, type LoginError, type LoginProvider } from "@/lib/auth"; import { takeLoginReturn } from "@/lib/return-to"; -import { - forgetTermsAgreement, - hasAgreedTerms, - PRIVACY_HREF, - rememberTermsAgreement, - TERMS_HREF, - TERMS_VERSION, -} from "@/lib/terms"; - -const noSubscribe = () => () => {}; +import { PRIVACY_HREF, TERMS_HREF } from "@/lib/terms"; type LoginPanelProps = { /** 로그인에 실패하고 돌아온 경우의 오류 (로그인 화면의 주소 쿼리) */ @@ -33,32 +22,21 @@ type LoginPanelProps = { }; /** - * 로그인 본문. 약관 동의와 만 14세 이상 확인 뒤 구글·카카오 로그인을 시작한다 (스펙 R1·R4·R8). + * 로그인 본문. 구글·카카오 로그인을 시작한다 (스펙 R1·R4). + * 약관 동의는 로그인 직후 신규 가입자에게만 받는다(ConsentGate, SCRUM-211). * 로그인 화면(S13)과 하단 로그인 창이 함께 쓴다. 돌아갈 주소는 여는 쪽이 saveLoginReturn 으로 먼저 기억한다. */ export function LoginPanel({ initialError = null, onDone }: LoginPanelProps) { - const termsId = useId(); - const ageId = useId(); - const [agreed, setAgreed] = useState(false); - const [over14, setOver14] = useState(false); const [pending, setPending] = useState(null); const [localError, setLocalError] = useState(null); const [dismissed, setDismissed] = useState(false); const error = localError ?? (dismissed ? null : initialError); const router = useRouter(); - // 이 브라우저에서 같은 버전에 동의했으면 다시 묻지 않는다 (API 명세서 A26) - const remembered = useSyncExternalStore( - noSubscribe, - () => hasAgreedTerms(), - () => false, - ); - const consented = remembered || (agreed && over14); - const ready = consented && pending === null; + const ready = pending === null; async function start(provider: LoginProvider) { - if (!consented) return; - rememberTermsAgreement(); + if (!ready) return; setPending(provider); setLocalError(null); setDismissed(true); @@ -97,7 +75,6 @@ export function LoginPanel({ initialError = null, onDone }: LoginPanelProps) { } const callbackResult = parseCallbackQuery(callback.searchParams); if (callbackResult.kind === "error") { - if (callbackResult.error === "terms_outdated") forgetTermsAgreement(); setLocalError(callbackResult.error); setPending(null); return; @@ -135,55 +112,7 @@ export function LoginPanel({ initialError = null, onDone }: LoginPanelProps) { )} - {remembered ? ( -

- 이 브라우저에서 이용약관·개인정보 처리방침(버전 {TERMS_VERSION})에 동의하고 만 14세 이상임을 확인했어요.{" "} - - 이용약관 보기 - -

- ) : ( -
- 로그인 전 확인 -
- setAgreed(value === true)} - className="mt-0.5" - /> -
- -

- - 이용약관 보기 - - - 개인정보 처리방침 보기 - -

-
-
-
- setOver14(value === true)} - className="mt-0.5" - /> - -
-
- )} -
- {!consented ? ( -

두 항목을 모두 확인하면 로그인할 수 있어요.

- ) : null} {(["kakao", "google"] as const).map((provider) => ( ))}
+ +

+ 처음 로그인하면{" "} + + 이용약관 + + · + + 개인정보 처리방침 + {" "} + 동의를 받아요. +

); } diff --git a/frontend/src/components/ui/sheet.tsx b/frontend/src/components/ui/sheet.tsx index 217c59e..a616e3d 100644 --- a/frontend/src/components/ui/sheet.tsx +++ b/frontend/src/components/ui/sheet.tsx @@ -14,10 +14,13 @@ function SheetContent({ className, children, side = "right", + hideClose = false, ...props }: React.ComponentProps & { /** adaptive: 휴대폰 폭(앱·모바일 웹)은 아래에서 올라오는 창, 640px 이상은 화면 가운데 모달 */ side?: "top" | "right" | "bottom" | "left" | "adaptive"; + /** 반드시 끝내야 하는 단계(예: 약관 동의)처럼 닫기 버튼을 두지 않을 때 */ + hideClose?: boolean; }) { return ( @@ -41,10 +44,12 @@ function SheetContent({ {...props} > {children} - - - 닫기 - + {hideClose ? null : ( + + + 닫기 + + )} ); diff --git a/frontend/src/lib/api/auth.ts b/frontend/src/lib/api/auth.ts index 88230c4..7497120 100644 --- a/frontend/src/lib/api/auth.ts +++ b/frontend/src/lib/api/auth.ts @@ -13,7 +13,6 @@ import { type LoginProvider, } from "@/lib/auth"; import { saveSession } from "@/lib/session"; -import { TERMS_VERSION } from "@/lib/terms"; export type TokenRequest = components["schemas"]["TokenRequest"]; export type TokenResponse = components["schemas"]["TokenResponse"]; @@ -33,7 +32,6 @@ export async function prepareLogin(provider: LoginProvider, client: "web" | "app return loginStartUrl(provider, { baseUrl: apiBaseUrl(), codeChallenge: await codeChallengeFor(verifier), - termsVersion: TERMS_VERSION, client, }); } diff --git a/frontend/src/lib/api/client.ts b/frontend/src/lib/api/client.ts index 9659348..ced9fe2 100644 --- a/frontend/src/lib/api/client.ts +++ b/frontend/src/lib/api/client.ts @@ -1,6 +1,7 @@ import { ApiError, errorKindFromStatus } from "./errors"; import { findMock, isMockMode, MOCK_DELAY_MS, type HttpMethod } from "./mock"; import type { components } from "./schema"; +import { notifyTermsNotAgreed } from "@/lib/consent"; import { clearSession, getSessionToken } from "@/lib/session"; // 예시 응답 등록 (실제 데이터 구축 전). NEXT_PUBLIC_API_MODE=live 면 쓰지 않는다 import "@/lib/mock"; @@ -21,6 +22,8 @@ export function apiBaseUrl(): string { return `http://${host}:8000`; } +const TERMS_NOT_AGREED = "terms_not_agreed"; + type UnauthorizedHandler = () => void; let unauthorizedHandler: UnauthorizedHandler | null = null; @@ -89,6 +92,7 @@ async function fromMock( return handler({ method, path, query, body, authenticated: token !== null }) as T; } catch (error) { if (error instanceof ApiError && error.kind === "unauthorized") handleUnauthorized(redirect); + if (error instanceof ApiError && error.code === TERMS_NOT_AGREED) notifyTermsNotAgreed(); throw error; } } @@ -133,7 +137,10 @@ export async function apiRequest(path: string, options: RequestOptions = {}): if (!response.ok) { const kind = errorKindFromStatus(response.status); if (kind === "unauthorized") handleUnauthorized(redirect); - throw new ApiError(kind, response.status, await readErrorCode(response)); + const code = await readErrorCode(response); + // 약관에 동의하지 않은 사용자: 동의 창을 다시 띄운다 (API 명세서 1장, A28) + if (response.status === 403 && code === TERMS_NOT_AGREED) notifyTermsNotAgreed(); + throw new ApiError(kind, response.status, code); } if (response.status === 204) return undefined as T; return (await response.json()) as T; diff --git a/frontend/src/lib/api/users.ts b/frontend/src/lib/api/users.ts index 7bed45b..b39e2e0 100644 --- a/frontend/src/lib/api/users.ts +++ b/frontend/src/lib/api/users.ts @@ -2,6 +2,7 @@ import { apiRequest } from "./client"; import { ApiError } from "./errors"; import type { components } from "./schema"; import { clearSession } from "@/lib/session"; +import { TERMS_VERSION } from "@/lib/terms"; /** * A02 DELETE /api/v1/users/me/data (Notion API 명세서 3장). 로그인 필요. @@ -74,3 +75,26 @@ export async function withdraw( throw error; } } + +// ---- 로그인 직후 약관 동의 (A28 terms_agreed, A34) ---- + +export type ConsentRequest = components["schemas"]["ConsentRequest"]; + +/** A28 의 terms_agreed. false 면 신규 가입이거나 약관 버전이 바뀐 사용자라 동의 창을 띄운다 (SCRUM-211) */ +export async function fetchTermsAgreed(signal?: AbortSignal): Promise { + return (await getMe(signal)).terms_agreed; +} + +/** + * A34 POST /api/v1/users/me/consent. 약관·개인정보 처리방침·만 14세 이상 확인을 묶어 동의한다. + * 422 terms_outdated 면 화면의 약관 버전이 서버의 현재 버전과 다르다. 200 은 A28 과 같은 응답이다. + */ +export const agreeTerms = (version: string = TERMS_VERSION) => { + const body: ConsentRequest = { terms_version: version }; + return apiRequest("/api/v1/users/me/consent", { method: "POST", body }); +}; + +/** A34 가 422 terms_outdated 를 줬는지 */ +export function isTermsOutdated(error: unknown): boolean { + return error instanceof ApiError && error.code === "terms_outdated"; +} diff --git a/frontend/src/lib/auth.ts b/frontend/src/lib/auth.ts index b190a2a..ba82832 100644 --- a/frontend/src/lib/auth.ts +++ b/frontend/src/lib/auth.ts @@ -71,17 +71,15 @@ export function takeVerifier({ storage = defaultStorage() }: { storage?: Session } } -/** A26 GET /api/v1/auth/{provider}/start. 브라우저가 직접 연다 */ +/** + * A26 GET /api/v1/auth/{provider}/start. 브라우저가 직접 연다. + * 약관 동의는 로그인 직후 동의 단계(A34)에서 받으므로 terms_version 을 보내지 않는다(API 명세서 A26, 2026-11-30 변경). + */ export function loginStartUrl( provider: LoginProvider, - { - baseUrl, - codeChallenge, - termsVersion, - client = "web", - }: { baseUrl: string; codeChallenge: string; termsVersion: string; client?: "web" | "app" }, + { baseUrl, codeChallenge, client = "web" }: { baseUrl: string; codeChallenge: string; client?: "web" | "app" }, ): string { - const params = new URLSearchParams({ client, code_challenge: codeChallenge, terms_version: termsVersion }); + const params = new URLSearchParams({ client, code_challenge: codeChallenge }); return `${baseUrl.replace(/\/+$/, "")}/api/v1/auth/${provider}/start?${params.toString()}`; } diff --git a/frontend/src/lib/consent.ts b/frontend/src/lib/consent.ts new file mode 100644 index 0000000..6593994 --- /dev/null +++ b/frontend/src/lib/consent.ts @@ -0,0 +1,108 @@ +/** + * 로그인 직후 약관 동의 단계 (Jira SCRUM-211, Notion API 명세서 A28·A34, 기획 M10 R8). + * 신규 가입자와 약관 버전이 바뀐 사용자만 A28 의 terms_agreed 가 false 다. 이때 동의 창을 띄우고, + * 동의하기 전에는 보호 화면을 그리지 않는다. 서버도 403 terms_not_agreed 로 막는다. + */ + +import type { SessionStatus, SessionStorageLike } from "@/lib/session"; +import { isProtectedPath } from "@/lib/return-to"; + +export type ConsentStatus = "unknown" | "checking" | "agreed" | "needed" | "error"; + +/** 약관 문서와 로그인 화면은 동의 창 없이 볼 수 있어야 한다 */ +const CONSENT_FREE_PATHS = ["/terms", "/privacy", "/login", "/auth"] as const; + +function isConsentFreePath(pathname: string): boolean { + const path = pathname.replace(/\.html$/, "").replace(/\/+$/, "") || "/"; + return CONSENT_FREE_PATHS.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)); +} + +export type ConsentGateView = { + /** 동의 창(또는 확인 실패 안내)을 띄운다 */ + sheet: boolean; + /** 보호 화면 대신 확인 중 안내를 그린다 */ + holdProtected: boolean; +}; + +export function consentGateView(session: SessionStatus, status: ConsentStatus, pathname: string): ConsentGateView { + if (session !== "logged_in" || status === "agreed") return { sheet: false, holdProtected: false }; + const free = isConsentFreePath(pathname); + return { + sheet: !free && (status === "needed" || status === "error"), + holdProtected: isProtectedPath(pathname), + }; +} + +/** 모두 동의: 둘 다 체크돼 있으면 해제, 아니면 모두 체크 */ +export function toggleAll(items: { terms: boolean; age: boolean }): { terms: boolean; age: boolean } { + const next = !(items.terms && items.age); + return { terms: next, age: next }; +} + +// ---- 이 탭에서 확인한 결과 ---- + +/** 같은 탭에서 화면을 옮길 때마다 A28 을 다시 부르지 않도록 동의한 버전을 기억한다. 로그아웃하면 지운다 */ +const AGREED_STORAGE_KEY = "jcs.consent.agreed.v1"; + +function defaultStorage(): SessionStorageLike | null { + try { + return typeof window === "undefined" ? null : window.sessionStorage; + } catch { + return null; + } +} + +type StorageOption = { storage?: SessionStorageLike | null }; + +export function rememberConsent(version: string, { storage = defaultStorage() }: StorageOption = {}): void { + try { + storage?.setItem(AGREED_STORAGE_KEY, version); + } catch { + // 기억하지 못하면 다음 화면에서 다시 확인한다 + } +} + +export function hasRememberedConsent(version: string, { storage = defaultStorage() }: StorageOption = {}): boolean { + try { + return storage?.getItem(AGREED_STORAGE_KEY) === version; + } catch { + return false; + } +} + +export function forgetConsent({ storage = defaultStorage() }: StorageOption = {}): void { + try { + storage?.removeItem(AGREED_STORAGE_KEY); + } catch { + // 지우지 못해도 다음 로그인에서 다시 확인한다 + } +} + +// ---- 화면이 함께 읽는 동의 상태 ---- + +type Listener = () => void; +const listeners = new Set(); +let current: ConsentStatus = "unknown"; + +export function getConsentStatus(): ConsentStatus { + return current; +} + +export function setConsentStatus(status: ConsentStatus): void { + if (current === status) return; + current = status; + listeners.forEach((listener) => listener()); +} + +export function subscribeConsent(listener: Listener): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** API 가 403 terms_not_agreed 를 주면 API 클라이언트가 부른다. 기억을 지우고 동의 창을 다시 띄운다 */ +export function notifyTermsNotAgreed(): void { + forgetConsent(); + setConsentStatus("needed"); +} diff --git a/frontend/src/lib/mock/users.ts b/frontend/src/lib/mock/users.ts index c795516..7acce68 100644 --- a/frontend/src/lib/mock/users.ts +++ b/frontend/src/lib/mock/users.ts @@ -1,5 +1,6 @@ import { ApiError } from "@/lib/api/errors"; import { defineMock } from "@/lib/api/mock"; +import { TERMS_VERSION } from "@/lib/terms"; // A02: 로그인 필요. 예시로 원본 정리가 남아 202(삭제 처리 중)로 답한다 defineMock("DELETE", "/api/v1/users/me/data", ({ authenticated }) => { @@ -7,15 +8,51 @@ defineMock("DELETE", "/api/v1/users/me/data", ({ authenticated }) => { return { status: "deleting" }; }); -// A28: 예시 계정 -defineMock("GET", "/api/v1/users/me", ({ authenticated }) => { - if (!authenticated) throw new ApiError("unauthorized", 401, "unauthorized"); +/** + * 예시 계정의 약관 동의 버전. 이 브라우저에 남겨 처음 로그인은 신규 가입(동의 창), + * 동의한 뒤 다시 로그인하면 기존 가입자(동의 창 없음)로 흉내 낸다. 탈퇴(A30)하면 지운다. + */ +const MOCK_AGREED_KEY = "jcs.mock.terms-agreed.v1"; + +function mockAgreedVersion(): string | null { + try { + return typeof window === "undefined" ? null : window.localStorage.getItem(MOCK_AGREED_KEY); + } catch { + return null; + } +} + +function setMockAgreedVersion(version: string | null): void { + try { + if (version === null) window.localStorage.removeItem(MOCK_AGREED_KEY); + else window.localStorage.setItem(MOCK_AGREED_KEY, version); + } catch { + // 저장하지 못하면 다음 로그인도 신규 가입처럼 보인다 + } +} + +function mockMe() { return { id: "00000000-0000-4000-8000-000000000010", provider: "kakao", - terms_agreed: true, + terms_agreed: mockAgreedVersion() === TERMS_VERSION, created_at: "2026-11-25T00:00:00Z", }; +} + +// A28: 예시 계정 +defineMock("GET", "/api/v1/users/me", ({ authenticated }) => { + if (!authenticated) throw new ApiError("unauthorized", 401, "unauthorized"); + return mockMe(); +}); + +// A34: 현재 버전이 아니면 422 terms_outdated, 맞으면 동의를 기록하고 A28 과 같은 응답 +defineMock("POST", "/api/v1/users/me/consent", ({ authenticated, body }) => { + if (!authenticated) throw new ApiError("unauthorized", 401, "unauthorized"); + const version = typeof body === "object" && body !== null && "terms_version" in body ? body.terms_version : undefined; + if (version !== TERMS_VERSION) throw new ApiError("validation", 422, "terms_outdated"); + setMockAgreedVersion(TERMS_VERSION); + return mockMe(); }); // A29: 204 는 본문이 없어 null 로 흉내 낸다 @@ -24,8 +61,9 @@ defineMock("POST", "/api/v1/auth/logout", ({ authenticated }) => { return null; }); -// A30: 예시로 자료 정리가 남아 202(처리 중)로 답한다 +// A30: 예시로 자료 정리가 남아 202(처리 중)로 답한다. 다음 로그인은 신규 가입처럼 보인다 defineMock("DELETE", "/api/v1/users/me", ({ authenticated }) => { if (!authenticated) throw new ApiError("unauthorized", 401, "unauthorized"); + setMockAgreedVersion(null); return { status: "deleting" }; }); diff --git a/frontend/src/lib/terms.ts b/frontend/src/lib/terms.ts index 248f573..c335db2 100644 --- a/frontend/src/lib/terms.ts +++ b/frontend/src/lib/terms.ts @@ -1,58 +1,10 @@ -import type { SessionStorageLike } from "@/lib/session"; - /** * 약관·개인정보 처리방침 버전과 경로 (스펙 specs/social-login R8). - * 로그인 시작(A26)에 동의한 버전으로 보내고, 약관 화면(SCRUM-173)이 같은 값을 표시한다. + * 로그인 직후 동의 단계(A34)에 동의한 버전으로 보내고, 약관 화면(SCRUM-173)이 같은 값을 표시한다. + * 서버 설정의 현재 약관 버전과 같아야 한다. 다르면 A34 가 422 terms_outdated 를 준다. * 확정 전이라 초안 버전이다. 문구를 바꾸면 버전도 함께 바꾼다. */ export const TERMS_VERSION = "draft-2026-11"; -/** - * 동의한 버전을 이 브라우저에 기억해 같은 버전은 다시 묻지 않는다. 새 브라우저에서는 다시 확인받는다 (API 명세서 A26). - * 약관·개인정보 처리방침·만 14세 이상 확인을 묶은 동의다. - */ -const AGREED_STORAGE_KEY = "jcs.terms.agreed.v1"; - -function defaultStorage(): SessionStorageLike | null { - try { - return typeof window === "undefined" ? null : window.localStorage; - } catch { - return null; - } -} - -export function rememberTermsAgreement( - version: string = TERMS_VERSION, - { storage = defaultStorage() }: { storage?: SessionStorageLike | null } = {}, -): void { - try { - storage?.setItem(AGREED_STORAGE_KEY, version); - } catch { - // 기억하지 못하면 다음에 다시 묻는다 - } -} - -export function hasAgreedTerms( - version: string = TERMS_VERSION, - { storage = defaultStorage() }: { storage?: SessionStorageLike | null } = {}, -): boolean { - try { - return storage?.getItem(AGREED_STORAGE_KEY) === version; - } catch { - return false; - } -} - -/** 서버가 약관이 바뀌었다고 하면(terms_outdated) 기억을 지우고 다시 묻는다 */ -export function forgetTermsAgreement({ - storage = defaultStorage(), -}: { storage?: SessionStorageLike | null } = {}): void { - try { - storage?.removeItem(AGREED_STORAGE_KEY); - } catch { - // 지우지 못해도 버전이 다르면 다시 묻는다 - } -} - export const TERMS_HREF = "/terms"; export const PRIVACY_HREF = "/privacy"; diff --git a/frontend/tests/unit/auth.test.ts b/frontend/tests/unit/auth.test.ts index bbb0228..5ded51f 100644 --- a/frontend/tests/unit/auth.test.ts +++ b/frontend/tests/unit/auth.test.ts @@ -18,7 +18,6 @@ import { VERIFIER_STORAGE_KEY, } from "@/lib/auth"; import { getSessionToken, type SessionStorageLike } from "@/lib/session"; -import { forgetTermsAgreement, hasAgreedTerms, rememberTermsAgreement, TERMS_VERSION } from "@/lib/terms"; function memoryStorage(): SessionStorageLike & { data: Map } { const data = new Map(); @@ -64,12 +63,10 @@ describe("verifier 보관", () => { }); describe("로그인 시작 주소 (A26)", () => { - it("웹 클라이언트, challenge, 약관 버전을 붙인다", () => { - const url = new URL( - loginStartUrl("kakao", { baseUrl: "https://api.example.com/", codeChallenge: "abc", termsVersion: "v1" }), - ); + it("웹 클라이언트와 challenge 를 붙이고, 약관 버전은 보내지 않는다(동의는 로그인 직후 A34)", () => { + const url = new URL(loginStartUrl("kakao", { baseUrl: "https://api.example.com/", codeChallenge: "abc" })); expect(url.origin + url.pathname).toBe("https://api.example.com/api/v1/auth/kakao/start"); - expect(Object.fromEntries(url.searchParams)).toEqual({ client: "web", code_challenge: "abc", terms_version: "v1" }); + expect(Object.fromEntries(url.searchParams)).toEqual({ client: "web", code_challenge: "abc" }); }); it("앱 클라이언트는 client=app 을 붙인다", () => { @@ -77,7 +74,6 @@ describe("로그인 시작 주소 (A26)", () => { loginStartUrl("google", { baseUrl: "https://api.example.com", codeChallenge: "abc", - termsVersion: "v1", client: "app", }), ); @@ -171,20 +167,3 @@ describe("코드 교환 (A01)", () => { expect(getSessionToken()).toBeNull(); }); }); - -describe("약관 동의 기억 (API 명세서 A26)", () => { - it("같은 버전에 동의했으면 다시 묻지 않고, 버전이 바뀌거나 지우면 다시 묻는다", () => { - const storage = memoryStorage(); - expect(hasAgreedTerms(TERMS_VERSION, { storage })).toBe(false); - rememberTermsAgreement(TERMS_VERSION, { storage }); - expect(hasAgreedTerms(TERMS_VERSION, { storage })).toBe(true); - expect(hasAgreedTerms("next-version", { storage })).toBe(false); - forgetTermsAgreement({ storage }); - expect(hasAgreedTerms(TERMS_VERSION, { storage })).toBe(false); - }); - - it("저장소를 못 쓰면 매번 묻는다", () => { - rememberTermsAgreement(TERMS_VERSION, { storage: null }); - expect(hasAgreedTerms(TERMS_VERSION, { storage: null })).toBe(false); - }); -}); diff --git a/frontend/tests/unit/consent.test.ts b/frontend/tests/unit/consent.test.ts new file mode 100644 index 0000000..b7d54d4 --- /dev/null +++ b/frontend/tests/unit/consent.test.ts @@ -0,0 +1,89 @@ +import { afterEach, describe, expect, it } from "vitest"; + +import { + consentGateView, + forgetConsent, + getConsentStatus, + hasRememberedConsent, + notifyTermsNotAgreed, + rememberConsent, + setConsentStatus, + subscribeConsent, + toggleAll, +} from "@/lib/consent"; +import type { SessionStorageLike } from "@/lib/session"; + +function memoryStorage(): SessionStorageLike { + const data = new Map(); + return { + getItem: (key) => data.get(key) ?? null, + setItem: (key, value) => void data.set(key, value), + removeItem: (key) => void data.delete(key), + }; +} + +afterEach(() => setConsentStatus("unknown")); + +describe("동의 창과 보호 화면 (기획 M10 R8)", () => { + it("로그아웃 상태나 동의한 사용자는 막지 않는다", () => { + expect(consentGateView("logged_out", "needed", "/diagnose")).toEqual({ sheet: false, holdProtected: false }); + expect(consentGateView("logged_in", "agreed", "/diagnose")).toEqual({ sheet: false, holdProtected: false }); + }); + + it("동의가 필요하면 창을 띄우고 보호 화면은 그리지 않는다", () => { + expect(consentGateView("logged_in", "needed", "/diagnose")).toEqual({ sheet: true, holdProtected: true }); + expect(consentGateView("logged_in", "needed", "/")).toEqual({ sheet: true, holdProtected: false }); + }); + + it("확인 중에는 창 없이 보호 화면만 잠시 막는다", () => { + expect(consentGateView("logged_in", "checking", "/contract")).toEqual({ sheet: false, holdProtected: true }); + expect(consentGateView("logged_in", "checking", "/")).toEqual({ sheet: false, holdProtected: false }); + }); + + it("확인에 실패하면 다시 시도 창을 띄운다", () => { + expect(consentGateView("logged_in", "error", "/").sheet).toBe(true); + }); + + it("약관 문서와 로그인 화면에서는 창을 띄우지 않아 약관을 읽을 수 있다", () => { + for (const path of ["/terms", "/privacy", "/privacy.html", "/login", "/auth/callback"]) { + expect(consentGateView("logged_in", "needed", path).sheet).toBe(false); + } + }); +}); + +describe("모두 동의", () => { + it("하나라도 비어 있으면 모두 체크하고, 모두 체크돼 있으면 모두 해제한다", () => { + expect(toggleAll({ terms: false, age: false })).toEqual({ terms: true, age: true }); + expect(toggleAll({ terms: true, age: false })).toEqual({ terms: true, age: true }); + expect(toggleAll({ terms: true, age: true })).toEqual({ terms: false, age: false }); + }); +}); + +describe("이 탭의 동의 기억", () => { + it("같은 버전만 기억으로 인정하고 지우면 다시 확인한다", () => { + const storage = memoryStorage(); + expect(hasRememberedConsent("v1", { storage })).toBe(false); + rememberConsent("v1", { storage }); + expect(hasRememberedConsent("v1", { storage })).toBe(true); + expect(hasRememberedConsent("v2", { storage })).toBe(false); + forgetConsent({ storage }); + expect(hasRememberedConsent("v1", { storage })).toBe(false); + }); + + it("저장소를 못 쓰면 기억하지 않는다", () => { + rememberConsent("v1", { storage: null }); + expect(hasRememberedConsent("v1", { storage: null })).toBe(false); + }); +}); + +describe("403 terms_not_agreed", () => { + it("동의 상태를 needed 로 바꾸고 화면에 알린다", () => { + setConsentStatus("agreed"); + let calls = 0; + const stop = subscribeConsent(() => calls++); + notifyTermsNotAgreed(); + expect(getConsentStatus()).toBe("needed"); + expect(calls).toBe(1); + stop(); + }); +});