From 13a82db342b270dda81c41f58b3be530536a6018 Mon Sep 17 00:00:00 2001 From: s26011-cloud Date: Sun, 22 Nov 2026 23:15:44 +0900 Subject: [PATCH 1/3] =?UTF-8?q?refactor:=20=ED=86=A0=ED=81=B0=EC=9D=84=20h?= =?UTF-8?q?ttpOnly=20=EC=BF=A0=ED=82=A4=EC=99=80=20=EB=A9=94=EB=AA=A8?= =?UTF-8?q?=EB=A6=AC=EB=A1=9C=20=EC=98=AE=EA=B8=B0=EA=B3=A0=20=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=20=EB=B3=B4=ED=98=B8=20(#40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/features/auth/api.test.ts | 4 +- src/features/auth/api.ts | 10 ++--- src/lib/api.test.ts | 77 ++++++++++++++++++++++------------- src/lib/api.ts | 63 ++++++++++++++-------------- src/lib/session.ts | 15 +++++++ src/proxy.test.ts | 32 +++++++++++++++ src/proxy.ts | 14 +++++++ 7 files changed, 144 insertions(+), 71 deletions(-) create mode 100644 src/lib/session.ts create mode 100644 src/proxy.test.ts create mode 100644 src/proxy.ts diff --git a/src/features/auth/api.test.ts b/src/features/auth/api.test.ts index 5c12b2f..9e718d9 100644 --- a/src/features/auth/api.test.ts +++ b/src/features/auth/api.test.ts @@ -11,7 +11,6 @@ const assign = vi.fn(); const ORIGIN = "http://admin.test"; beforeEach(() => { - localStorage.clear(); sessionStorage.clear(); vi.stubGlobal("location", { assign, @@ -30,7 +29,7 @@ afterEach(() => { function serverWithRole(role: "ADMIN" | "KEEPER" | "ME_FAILS") { setServer((config) => { if (config.url === "/auth/oauth/callback") - return [200, { data: { accessToken: "a1", refreshToken: "r1" } }]; + return [200, { data: { accessToken: "a1" } }]; if (config.url === "/auth/me") return role === "ME_FAILS" ? [500, {}] @@ -93,7 +92,6 @@ test("내 정보를 못 불러오면 토큰을 지우고 실패한다", async () await expect(finishLogin("code-1", state)).rejects.toThrow(); expect(tokens.access).toBeNull(); - expect(tokens.refresh).toBeNull(); }); test("state가 다르면 서버에 보내지 않고 실패한다", async () => { diff --git a/src/features/auth/api.ts b/src/features/auth/api.ts index 39e2e1a..4c18c07 100644 --- a/src/features/auth/api.ts +++ b/src/features/auth/api.ts @@ -1,4 +1,4 @@ -import { api, loginHref, tokens } from "@/lib/api"; +import { api, loginHref, signIn, signOut } from "@/lib/api"; export type Me = { id: number; nickname: string; role: "KEEPER" | "ADMIN" }; @@ -69,7 +69,7 @@ export async function finishLogin(code: string | undefined, state: string) { code, redirectUri: redirectUri(), }); - tokens.save(data.data); + signIn(data.data.accessToken); let me: Me; try { @@ -91,8 +91,6 @@ export async function getMe() { // 서버 폐기에 실패해도 이 브라우저에서는 로그아웃한다 export async function logout() { - await api - .post("/auth/logout", { refreshToken: tokens.refresh }) - .catch(() => {}); - tokens.clear(); + await api.post("/auth/logout").catch(() => {}); + signOut(); } diff --git a/src/lib/api.test.ts b/src/lib/api.test.ts index 0dd753a..f9dda8c 100644 --- a/src/lib/api.test.ts +++ b/src/lib/api.test.ts @@ -8,10 +8,9 @@ const reissues = () => requests.filter((r) => r.url?.endsWith("/reissue")); const authOf = (url: string) => sent(url).map((r) => r.headers.Authorization); beforeEach(() => { - localStorage.clear(); sessionStorage.clear(); vi.stubGlobal("location", { assign, pathname: "/species", search: "" }); - tokens.save({ accessToken: "old", refreshToken: "r1" }); + tokens.access = "old"; }); afterEach(() => { @@ -29,7 +28,7 @@ const okWithNewToken = ( const reissueOk = (config: InternalAxiosRequestConfig): [number, unknown] => config.url?.endsWith("/reissue") - ? [200, { data: { accessToken: "new", refreshToken: "r2" } }] + ? [200, { data: { accessToken: "new" } }] : okWithNewToken(config); test("401이면 한 번 재발급하고 새 토큰으로 다시 보낸다", async () => { @@ -40,8 +39,8 @@ test("401이면 한 번 재발급하고 새 토큰으로 다시 보낸다", asyn expect(res.data).toEqual({ data: "ok" }); expect(authOf("/animals")).toEqual(["Bearer old", "Bearer new"]); expect(reissues()).toHaveLength(1); - expect(JSON.parse(reissues()[0].data)).toEqual({ refreshToken: "r1" }); - expect(tokens.refresh).toBe("r2"); + expect(reissues()[0].withCredentials).toBe(true); + expect(tokens.access).toBe("new"); }); test("401이 동시에 여러 개 와도 재발급은 한 번만 한다", async () => { @@ -61,11 +60,10 @@ test("재발급이 401이면 토큰을 지우고 만료 화면으로 보내며 expect(assign).toHaveBeenCalledWith("/login?error=expired"), ); expect(tokens.access).toBeNull(); - expect(tokens.refresh).toBeNull(); expect(sessionStorage.getItem("returnTo")).toBe("/species"); }); -test("재발급이 서버 오류면 토큰을 남기고 원래 에러를 던진다", async () => { +test("재발급이 서버 오류면 로그인 화면으로 보내지 않고 원래 에러를 던진다", async () => { setServer((config) => config.url?.endsWith("/reissue") ? [500, {}] : [401, {}], ); @@ -73,40 +71,61 @@ test("재발급이 서버 오류면 토큰을 남기고 원래 에러를 던진 await expect(api.get("/animals")).rejects.toMatchObject({ response: { status: 401 }, }); - expect(tokens.refresh).toBe("r1"); expect(assign).not.toHaveBeenCalled(); }); -test("다른 탭이 먼저 재발급했으면 그 토큰으로 다시 보낸다", async () => { - setServer((config) => { - if (!config.url?.endsWith("/reissue")) return okWithNewToken(config); - // 다른 탭이 r1을 먼저 써서 새 토큰을 저장한 상황 - tokens.save({ accessToken: "new", refreshToken: "r2" }); - return [401, {}]; - }); +test("소셜 로그인의 401은 재발급하지 않는다", async () => { + setServer(() => [401, {}]); + + await expect(api.post("/auth/oauth/callback")).rejects.toBeInstanceOf( + AxiosError, + ); + expect(reissues()).toHaveLength(0); +}); + +test("액세스 토큰이 만료돼 로그아웃이 401이면 재발급한 뒤 다시 보낸다", async () => { + setServer((config) => + config.url === "/auth/logout" && + config.headers.Authorization === "Bearer new" + ? [204, null] + : reissueOk(config), + ); + + await api.post("/auth/logout"); + + expect(authOf("/auth/logout")).toEqual(["Bearer old", "Bearer new"]); +}); + +test("새로고침해 액세스 토큰이 없어도 첫 401에서 쿠키로 재발급해 복구한다", async () => { + tokens.access = null; + setServer(reissueOk); const res = await api.get("/animals"); expect(res.data).toEqual({ data: "ok" }); - expect(assign).not.toHaveBeenCalled(); + expect(authOf("/animals")).toEqual([undefined, "Bearer new"]); }); -test("소셜 로그인과 로그아웃의 401은 재발급하지 않는다", async () => { - setServer(() => [401, {}]); +test("모든 요청과 재발급에 웹 표시 헤더와 쿠키 전송을 붙인다", async () => { + setServer(reissueOk); - await expect(api.post("/auth/oauth/callback")).rejects.toBeInstanceOf( - AxiosError, - ); - await expect(api.post("/auth/logout")).rejects.toBeInstanceOf(AxiosError); - expect(reissues()).toHaveLength(0); + await api.get("/animals"); + + for (const r of requests) { + expect(r.withCredentials).toBe(true); + expect(r.headers["X-Client-Type"]).toBe("WEB"); + } + expect(reissues()).toHaveLength(1); }); -test("리프레시 토큰이 없으면 재발급 없이 로그인 화면으로 보낸다", async () => { - tokens.clear(); - setServer(() => [401, {}]); +test("로그인 표시 쿠키는 재발급 성공 때 남고 만료되면 지운다", async () => { + setServer(reissueOk); + await api.get("/animals"); + expect(document.cookie).toContain("signedIn=1"); + setServer(() => [401, {}]); + tokens.access = null; void api.get("/animals"); - - await vi.waitFor(() => expect(assign).toHaveBeenCalledWith("/login")); - expect(reissues()).toHaveLength(0); + await vi.waitFor(() => expect(assign).toHaveBeenCalled()); + expect(document.cookie).not.toContain("signedIn"); }); diff --git a/src/lib/api.ts b/src/lib/api.ts index ed52c94..d1d0507 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,7 +1,15 @@ import axios, { type InternalAxiosRequestConfig } from "axios"; +import { markSignedIn, markSignedOut } from "./session"; + +// 서버는 X-Client-Type: WEB이면 리프레시 토큰을 응답 본문 대신 httpOnly 쿠키로 주고받는다 +const webRequest = { + withCredentials: true, + headers: { "X-Client-Type": "WEB" }, +}; export const api = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL, + ...webRequest, }); // 로그인 화면 주소. error는 login/page.tsx가 보여 주는 화면 종류 @@ -9,38 +17,32 @@ export type LoginError = "forbidden" | "failed" | "expired"; export const loginHref = (error?: LoginError) => error ? `/login?error=${error}` : "/login"; -type Tokens = { accessToken: string; refreshToken: string }; -const ACCESS = "accessToken"; -const REFRESH = "refreshToken"; - -// shortcut: 토큰을 localStorage에 둬서 XSS에 노출되고 서버에서 로그인 여부를 볼 수 없다. 서버가 httpOnly 쿠키를 주면 옮긴다 +// 액세스 토큰은 메모리에만 둔다. 새로고침으로 사라지면 첫 401에서 쿠키로 재발급해 복구한다. +// 리프레시 토큰은 서버가 준 httpOnly 쿠키라 JS는 보지 못한다 export const tokens = { - get access() { - return localStorage.getItem(ACCESS); - }, - get refresh() { - return localStorage.getItem(REFRESH); - }, - save({ accessToken, refreshToken }: Tokens) { - localStorage.setItem(ACCESS, accessToken); - localStorage.setItem(REFRESH, refreshToken); - }, - clear() { - localStorage.removeItem(ACCESS); - localStorage.removeItem(REFRESH); - }, + access: null as string | null, }; +export function signIn(accessToken: string) { + tokens.access = accessToken; + markSignedIn(); +} + +export function signOut() { + tokens.access = null; + markSignedOut(); +} + api.interceptors.request.use((config) => { - const token = tokens.access; - if (token) config.headers.Authorization = `Bearer ${token}`; + if (tokens.access) config.headers.Authorization = `Bearer ${tokens.access}`; return config; }); -// 소셜 로그인 실패(OAUTH_FAILED)도 401이고, 로그아웃은 실패해도 로그인 화면으로 가면 되므로 재발급하지 않는다 -const noReissue = ["/auth/oauth/callback", "/auth/logout"]; +// 소셜 로그인 실패(OAUTH_FAILED)도 401이라 재발급하지 않는다. 로그아웃은 인증이 필요해서, +// 액세스 토큰이 만료됐으면 서버 요구대로 재발급한 뒤 다시 보낸다 +const noReissue = ["/auth/oauth/callback"]; -// 동시에 401이 여러 개 나도 재발급은 한 번만 한다 (쓴 리프레시 토큰은 서버가 지운다) +// 동시에 401이 여러 개 나도 재발급은 한 번만 한다 (쓴 리프레시 토큰은 서버가 바꾼다) let reissuing: Promise | null = null; api.interceptors.response.use(undefined, async (error) => { @@ -53,26 +55,21 @@ api.interceptors.response.use(undefined, async (error) => { ) { throw error; } - const used = tokens.refresh; - if (!used) return leave(loginHref()); - config.retried = true; reissuing ??= axios - .put(`${api.defaults.baseURL}/auth/reissue`, { refreshToken: used }) - .then((res) => tokens.save(res.data.data)) + .put(`${api.defaults.baseURL}/auth/reissue`, undefined, webRequest) + .then((res) => signIn(res.data.data.accessToken)) .finally(() => (reissuing = null)); try { await reissuing; } catch (reissueError) { - // 다른 탭이 먼저 재발급했으면 그 토큰으로 다시 보낸다 - if (tokens.refresh && tokens.refresh !== used) return api(config); - // 서버·네트워크 장애는 만료가 아니므로 토큰을 남긴다 + // 서버·네트워크 장애는 만료가 아니므로 원래 에러를 던진다 if ( !axios.isAxiosError(reissueError) || reissueError.response?.status !== 401 ) throw error; - tokens.clear(); + signOut(); return leave(loginHref("expired")); } return api(config); diff --git a/src/lib/session.ts b/src/lib/session.ts new file mode 100644 index 0000000..5cdfa27 --- /dev/null +++ b/src/lib/session.ts @@ -0,0 +1,15 @@ +// 서버의 리프레시 쿠키(refresh_token)는 Path=/api/v1/auth라 페이지 요청에는 오지 않아 proxy가 읽지 못한다. +// 그래서 로그인했다는 표시를 따로 남겨 proxy가 페이지를 그리기 전에 /login으로 보낸다. +// 화면 이동용 힌트일 뿐이고 진짜 인증은 API가 한다. 만료됐으면 첫 API 401에서 재발급 실패로 정리된다 +export const SESSION_COOKIE = "signedIn"; + +// shortcut: 서버 리프레시 토큰 만료(JWT_REFRESH_TOKEN_EXPIRATION 기본 14d)를 따로 적어 둔다. 서버 값을 바꾸면 같이 바꾼다 +const MAX_AGE = 60 * 60 * 24 * 14; + +export const markSignedIn = () => { + document.cookie = `${SESSION_COOKIE}=1; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax`; +}; + +export const markSignedOut = () => { + document.cookie = `${SESSION_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`; +}; diff --git a/src/proxy.test.ts b/src/proxy.test.ts new file mode 100644 index 0000000..e4ae920 --- /dev/null +++ b/src/proxy.test.ts @@ -0,0 +1,32 @@ +import { NextRequest } from "next/server"; +import { expect, test } from "vitest"; +import { config, proxy } from "./proxy"; + +const call = (cookie?: string) => + proxy( + new NextRequest("http://admin.test/species", { + headers: cookie ? { cookie } : {}, + }), + ); + +test("로그인 표시 쿠키가 없으면 로그인으로 보낸다", () => { + const res = call(); + expect(res.headers.get("location")).toBe("http://admin.test/login"); +}); + +test("로그인 표시 쿠키가 있으면 통과시킨다", () => { + expect(call("signedIn=1").headers.get("location")).toBeNull(); +}); + +test("로그인·정적 파일은 보호하지 않고 나머지 페이지는 보호한다", () => { + const re = new RegExp(`^${config.matcher[0]}$`); + for (const path of ["/", "/species", "/guides/1", "/login-help"]) + expect(re.test(path), path).toBe(true); + for (const path of [ + "/login", + "/_next/static/a.js", + "/favicon.ico", + "/robots.txt", + ]) + expect(re.test(path), path).toBe(false); +}); diff --git a/src/proxy.ts b/src/proxy.ts new file mode 100644 index 0000000..ea93e94 --- /dev/null +++ b/src/proxy.ts @@ -0,0 +1,14 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { SESSION_COOKIE } from "@/lib/session"; + +// 로그인 표시 쿠키(lib/session.ts)가 없으면 페이지를 그리기 전에 로그인으로 보낸다. +// 유효한지는 보지 않는다(만료는 첫 API 401에서 처리) +export function proxy(request: NextRequest) { + if (request.cookies.has(SESSION_COOKIE)) return NextResponse.next(); + return NextResponse.redirect(new URL("/login", request.url)); +} + +// /login, _next, 점이 든 정적 파일(favicon.ico, robots.txt, public/ 이미지)은 제외한다 +export const config = { + matcher: ["/((?!login$|_next/|.*\\.).*)"], +}; From 38e8a96ef6095cdd56bf60599b4d78f8461b8352 Mon Sep 17 00:00:00 2001 From: s26011-cloud Date: Mon, 23 Nov 2026 11:34:45 +0900 Subject: [PATCH 2/3] =?UTF-8?q?docs:=20=EC=9A=B4=EC=98=81=20=EB=B0=B0?= =?UTF-8?q?=ED=8F=AC=20=EB=AC=B8=EC=84=9C=EB=A5=BC=20=EB=8F=84=EB=A9=94?= =?UTF-8?q?=EC=9D=B8=EA=B3=BC=20HTTPS=20=EA=B8=B0=EC=A4=80=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EA=B3=A0=EC=B9=A8=20(#40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/deploy.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/deploy.md b/docs/deploy.md index 9b5b393..1ca465d 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -25,12 +25,14 @@ sudo mkdir -p /opt/tail-client sudo chown deploy:deploy /opt/tail-client ``` -방화벽에서 3001 포트를 연다. (서버의 3000은 tail-server의 그라파나가 127.0.0.1에서 쓰고 있어 웹은 3001로 연다.) +웹은 서버(tail-server)의 caddy가 HTTPS로 받아 3001로 넘긴다(tail-server `docs/deploy.md` 1-6). 방화벽에서 3001은 열지 않는다. (서버의 3000은 tail-server의 그라파나가 127.0.0.1에서 쓰고 있어 웹은 3001로 연다.) -웹의 origin을 서버의 CORS에 추가한다. `/opt/tail-server/.env`의 `CORS_ALLOWED_ORIGINS`에 `http://<서버 주소>:3001`을 쉼표로 이어 넣고 서버를 다시 띄운다. +도메인은 API와 웹을 같은 상위 도메인 아래에 둔다(`api.<도메인>`, `admin.<도메인>`). 서버가 리프레시 토큰을 `SameSite=Lax` httpOnly 쿠키로 주고, 로그인 표시 쿠키(`signedIn`)로 페이지를 보호하므로 서로 다른 사이트면 로그인이 되지 않는다. + +웹의 origin을 서버의 CORS에 추가한다. `/opt/tail-server/.env`의 `CORS_ALLOWED_ORIGINS`에 `https://`을 넣고 서버를 다시 띄운다. 쿠키를 쓰므로 `*`는 안 된다. ```bash -sudo -u deploy nano /opt/tail-server/.env # CORS_ALLOWED_ORIGINS=기존값,http://<서버 주소>:3001 +sudo -u deploy nano /opt/tail-server/.env # CORS_ALLOWED_ORIGINS=https:// cd /opt/tail-server && sudo -u deploy env IMAGE_TAG="$(cat current_tag)" docker compose up -d app ``` @@ -42,11 +44,11 @@ Settings → Secrets and variables → Actions → **Variables** → New reposit | 이름 | 값 | | ------------------------------ | ------------------------------------------------------------ | -| `NEXT_PUBLIC_API_URL` | 운영 서버 API 주소. 예: `http://<서버 주소>:8080/api/v1` | +| `NEXT_PUBLIC_API_URL` | 운영 서버 API 주소. 예: `https:///api/v1` | | `NEXT_PUBLIC_KAKAO_CLIENT_ID` | 카카오 REST API 키 (서버 `KAKAO_CLIENT_ID`와 같은 값) | | `NEXT_PUBLIC_GOOGLE_CLIENT_ID` | 구글 OAuth 클라이언트 ID (서버 `GOOGLE_CLIENT_ID`와 같은 값) | -카카오 디벨로퍼스와 구글 클라우드 콘솔의 Redirect URI에 `<웹 주소>/login`을 등록한다. +카카오 디벨로퍼스와 구글 클라우드 콘솔의 Redirect URI에 `https:///login`을 등록한다. ### prod environment @@ -68,7 +70,7 @@ GHCR 로그인은 워크플로의 `GITHUB_TOKEN`으로 하므로 따로 등록 ## 3. 첫 배포 1. `develop`을 `main`으로 PR해서 머지한다. CI가 성공하면 Deploy가 자동으로 시작된다. -2. 로그에 `OK: sha-xxxxxxx 배포 완료`가 나오면 `http://<서버 주소>:3001`에서 확인한다. +2. 로그에 `OK: sha-xxxxxxx 배포 완료`가 나오면 `https://`에서 로그인까지 확인한다. 첫 배포는 `current_tag`가 없어서 실패해도 롤백할 이전 버전이 없다. From 052aa49faba3ca0ce037b9730de1a3226183d72e Mon Sep 17 00:00:00 2001 From: s26011-cloud Date: Mon, 23 Nov 2026 12:21:24 +0900 Subject: [PATCH 3/3] =?UTF-8?q?fix:=20=EB=A1=9C=EA=B7=B8=EC=95=84=EC=9B=83?= =?UTF-8?q?=20=EC=A4=91=20=EC=9E=AC=EB=B0=9C=EA=B8=89=EC=9D=B4=20=EC=8B=A4?= =?UTF-8?q?=ED=8C=A8=ED=95=B4=EB=8F=84=20=EB=A7=8C=EB=A3=8C=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=EC=9C=BC=EB=A1=9C=20=EB=B3=B4=EB=82=B4=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EC=9D=8C=20(#40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/api.test.ts | 9 +++++++++ src/lib/api.ts | 2 ++ 2 files changed, 11 insertions(+) diff --git a/src/lib/api.test.ts b/src/lib/api.test.ts index f9dda8c..a92f0ed 100644 --- a/src/lib/api.test.ts +++ b/src/lib/api.test.ts @@ -96,6 +96,15 @@ test("액세스 토큰이 만료돼 로그아웃이 401이면 재발급한 뒤 expect(authOf("/auth/logout")).toEqual(["Bearer old", "Bearer new"]); }); +test("로그아웃 중 재발급까지 401이면 만료 화면으로 보내지 않고 에러를 던진다", async () => { + setServer(() => [401, {}]); + + await expect(api.post("/auth/logout")).rejects.toBeInstanceOf(AxiosError); + + expect(assign).not.toHaveBeenCalled(); + expect(tokens.access).toBeNull(); +}); + test("새로고침해 액세스 토큰이 없어도 첫 401에서 쿠키로 재발급해 복구한다", async () => { tokens.access = null; setServer(reissueOk); diff --git a/src/lib/api.ts b/src/lib/api.ts index d1d0507..16bf75e 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -70,6 +70,8 @@ api.interceptors.response.use(undefined, async (error) => { ) throw error; signOut(); + // 로그아웃은 만료 화면 없이 호출한 쪽이 마무리한다 (사용자가 직접 나간 것이고, 관리자 아님 안내를 덮지 않는다) + if (config.url === "/auth/logout") throw error; return leave(loginHref("expired")); } return api(config);