(
@@ -31,7 +29,7 @@ export async function GET(_request: NextRequest, context: RouteContext) {
export async function POST(request: NextRequest, context: RouteContext) {
const { slug = [] } = await context.params;
if (!isQuotaResultPath(slug)) return notFound();
- if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
+ if (!(await getServerAccessToken())) return unauthorized();
let body;
try {
body = readQuotaRequest(await request.json());
diff --git a/src/app/api/share/[projectType]/[pkey]/route.ts b/src/app/api/share/[projectType]/[pkey]/route.ts
index a3cb4a2..c3a87b9 100644
--- a/src/app/api/share/[projectType]/[pkey]/route.ts
+++ b/src/app/api/share/[projectType]/[pkey]/route.ts
@@ -1,8 +1,6 @@
-import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
-import { createServerApi } from "@/lib/http-server";
-import { CookieKeys } from "@/store/cookie/cookie-keys";
+import { createServerApi, getServerAccessToken } from "@/lib/http-server";
import { isProjectRef, isRecord } from "@/types/kart";
import { isShareLink } from "@/types/share";
@@ -12,7 +10,7 @@ export async function POST(request: NextRequest, context: {
const params = await context.params;
const project = { projectType: params.projectType === "0" ? 0 : params.projectType === "1" ? 1 : null, pkey: params.pkey };
if (!isProjectRef(project)) return NextResponse.json({ message: "프로젝트를 확인해 주세요." }, { status: 400 });
- if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
+ if (!(await getServerAccessToken()))
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
let body: unknown;
try { body = await request.json(); } catch { body = null; }
diff --git a/src/components/app-shell/AppMainLayout.tsx b/src/components/app-shell/AppMainLayout.tsx
index b5e7769..017fb0f 100644
--- a/src/components/app-shell/AppMainLayout.tsx
+++ b/src/components/app-shell/AppMainLayout.tsx
@@ -20,13 +20,14 @@ export function AppMainLayout({ children }: { children: ReactNode }) {
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
useEffect(() => {
if (hydrated && !auth.user) router.replace("/logout");
+ else if (hydrated && external && !auth.accessToken) router.replace("/logout");
// Legacy Main sends shared-link users (isAdmin > 8) to Logout, ending the External session.
else if (hydrated && external && pathname === "/") router.replace("/logout");
else if (hydrated && !externalAllowed)
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
- }, [hydrated, auth.user, auth.external, external, externalAllowed, pathname, router]);
+ }, [hydrated, auth.user, auth.external, auth.accessToken, external, externalAllowed, pathname, router]);
const hasSidebar = sideMenus.length > 0;
- if (!hydrated || !auth.user || !externalAllowed)
+ if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken))
return (
| null>(null);
+ const pending = useRef | null>(null);
const [error, setError] = useState("");
useEffect(() => {
if (!hydrated) return;
let active = true;
const enter = async () => {
- logout();
+ setAuth({ mode: "external", user: null });
await resetSession();
- const result = await nextApi.post(`/external/${encodeURIComponent(urlKey)}/login`, null, {
+ const result = await authApi.post(`/external/${encodeURIComponent(urlKey)}/login`, null, {
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
});
- if (!isExternalSession(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
+ if (!isExternalLoginResponse(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
return result;
};
// Reuse the request during StrictMode effect replay; each entry records one landing.
@@ -37,17 +36,15 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
void pending.current.then((result) => {
if (!active) return;
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
- setAuth({ user: result.user, external: result.link });
- notifyAuthChange(result.link.realUrl);
+ setAuth({ mode: "external", user: result.user, external: result.link, accessToken: result.accessToken });
router.replace(reportUrl(result.link.realUrl) as Route);
}).catch((reason: unknown) => {
if (active) {
- notifyAuthChange("/login");
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
}
});
return () => { active = false; };
- }, [hydrated, logout, setAuth, setProject, resetSession, router, urlKey]);
+ }, [hydrated, setAuth, setProject, resetSession, router, urlKey]);
if (error) return {error}
;
return ;
}
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
index 18f8096..28e53ea 100644
--- a/src/hooks/useAuth.ts
+++ b/src/hooks/useAuth.ts
@@ -1,7 +1,8 @@
"use client";
import { useCallback } from "react";
-import { useAtom, useAtomValue } from "jotai";
+import { atom, useAtom, useAtomValue } from "jotai";
+import type { SetStateAction } from "react";
import type { LoginUser } from "@kri/common";
import { isRecord, isLoginUser } from "@/types/kart";
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
@@ -10,25 +11,27 @@ import {
getLocalStorage,
removeLocalStorage,
setLocalStorage,
+ getSessionStorage,
+ setSessionStorage,
+ removeSessionStorage,
} from "@/store/storage/secure-storage";
import { StorageKeys } from "@/store/storage/storage-keys";
-import { isExternalSession, isExternalUser, type ShareLink } from "@/types/share";
+import { isExternalUser, type ShareLink } from "@/types/share";
+import { isExternalAuth, type ExternalAuth } from "@/lib/external-auth";
-export type AuthState = CommonAuthState & { external?: ShareLink };
+export type AuthState = CommonAuthState & { external?: ShareLink; accessToken?: string; mode?: "external" };
const initialAuthState: AuthState = { user: null };
const isPersistedAuthState = (value: unknown): value is AuthState =>
- isRecord(value) && isLoginUser(value.user) &&
- (isExternalUser(value.user)
- ? isExternalSession({ user: value.user, link: value.external })
- : value.external === undefined);
+ isRecord(value) && isLoginUser(value.user) && !isExternalUser(value.user) &&
+ value.accessToken === undefined && value.external === undefined;
/*
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
*/
-export const authStateAtom = createPersistentAtom(
+const normalAuthStateAtom = createPersistentAtom(
StorageKeys.AuthState,
initialAuthState,
{
@@ -43,6 +46,48 @@ export const authStateAtom = createPersistentAtom(
},
);
+const sessionStorage = { get: getSessionStorage, set: setSessionStorage, remove: removeSessionStorage };
+const authModeAtom = createPersistentAtom<"normal" | "external">(StorageKeys.AuthMode, "normal", {
+ storage: sessionStorage,
+ validate: (value): value is "normal" | "external" => value === "normal" || value === "external",
+ shouldRemove: (value) => value === "normal",
+});
+const externalAuthStateAtom = createPersistentAtom(StorageKeys.ExternalAuth, null, {
+ storage: sessionStorage,
+ validate: (value): value is ExternalAuth | null => value === null || isExternalAuth(value),
+});
+const emptyExternalAuth: ExternalAuth = { mode: "external", user: null };
+
+export const authStateAtom = Object.assign(atom(
+ (get): AuthState => {
+ const normal = get(normalAuthStateAtom);
+ const mode = get(authModeAtom);
+ const external = get(externalAuthStateAtom);
+ if (mode === "external") return external ?? emptyExternalAuth;
+ return normal;
+ },
+ (get, set, action: SetStateAction) => {
+ const previous = get(authStateAtom);
+ const next = typeof action === "function" ? action(previous) : action;
+ if (next.mode === "external" || isExternalUser(next.user)) {
+ set(authModeAtom, "external");
+ set(externalAuthStateAtom, { ...next, mode: "external" });
+ return;
+ }
+ if (!next.user && previous.mode === "external") {
+ set(authModeAtom, "external");
+ set(externalAuthStateAtom, null);
+ return;
+ }
+ set(authModeAtom, "normal");
+ set(externalAuthStateAtom, null);
+ set(normalAuthStateAtom, { user: next.user });
+ },
+), {
+ hydratedAtom: atom((get) => get(normalAuthStateAtom.hydratedAtom) &&
+ get(authModeAtom.hydratedAtom) && get(externalAuthStateAtom.hydratedAtom)),
+});
+
export function useAuth() {
const [auth, setAuth] = useAtom(authStateAtom);
const hydrated = useAtomValue(authStateAtom.hydratedAtom);
diff --git a/src/hooks/useSelectedProject.ts b/src/hooks/useSelectedProject.ts
index 53c8d84..504f235 100644
--- a/src/hooks/useSelectedProject.ts
+++ b/src/hooks/useSelectedProject.ts
@@ -6,7 +6,6 @@ import { createPersistentAtom } from "@kri/common/jotai";
import { useAuth } from "@/hooks/useAuth";
import { isExternalUser } from "@/types/share";
import {
- getLocalStorage,
getSessionStorage,
removeSessionStorage,
setSessionStorage,
@@ -24,25 +23,13 @@ const isSelectedProject = (value: unknown): value is SelectedProject =>
value.userId !== "" &&
isProjectRef(value.project));
-/** Each tab owns its selection; copy a legacy selection only on its first hydration. */
+/** Each tab owns its selection. */
export const selectedProjectAtom = createPersistentAtom(
StorageKeys.SelectedProject,
null,
{
storage: {
- get: (key: string): T | null => {
- const stored = getSessionStorage(key);
- if (stored !== null) return stored;
- const migrationKey = key + ":session-migrated";
- if (getSessionStorage(migrationKey)) return null;
- setSessionStorage(migrationKey, true);
- const legacy = getLocalStorage(key);
- if (isSelectedProject(legacy) && legacy !== null) {
- setSessionStorage(key, legacy);
- return legacy;
- }
- return null;
- },
+ get: getSessionStorage,
set: setSessionStorage,
remove: removeSessionStorage,
},
diff --git a/src/lib/auth-change.ts b/src/lib/auth-change.ts
index d240bff..1d555fd 100644
--- a/src/lib/auth-change.ts
+++ b/src/lib/auth-change.ts
@@ -1,8 +1,8 @@
-import { reportUrl } from "@/types/share";
+import { readExternalAuth } from "@/lib/external-auth";
// Set false to disable only cross-tab notifications and their listener.
const AUTH_CHANGE_SYNC_ENABLED = true;
-const CHANNEL = "kart:auth-change";
+const CHANNEL = "kart:internal-auth-change";
let channel: BroadcastChannel | undefined;
function authChannel() {
@@ -15,7 +15,7 @@ function authChannel() {
}
}
-export function notifyAuthChange(path: string) {
+export function notifyAuthChange(path: "/" | "/login") {
authChannel()?.postMessage(path);
}
@@ -23,10 +23,11 @@ export function subscribeToAuthChanges() {
const listener = authChannel();
if (!listener) return;
listener.onmessage = (event: MessageEvent) => {
- const path = event.data === "/" || event.data === "/login"
- ? event.data : reportUrl(event.data);
+ // A normal-login change must not navigate an independently authenticated link tab.
+ if (readExternalAuth()) return;
+ if (event.data !== "/" && event.data !== "/login") return;
// A full navigation discards this tab's cache/state without clearing the new cookie.
- if (path) window.location.replace(path);
+ window.location.replace(event.data);
};
return () => {
listener.close();
diff --git a/src/lib/auth-cookie.ts b/src/lib/auth-cookie.ts
index aa0954f..64a8b96 100644
--- a/src/lib/auth-cookie.ts
+++ b/src/lib/auth-cookie.ts
@@ -7,9 +7,7 @@ import { CookieKeys } from "@/store/cookie/cookie-keys";
/** Issue/renew the normal-login cookie, or expire it when the token is empty. */
export function setAuthCookie(response: NextResponse, token: string): void {
const production = serverEnv.ENV === "prod";
- const domain = production ? serverEnv.AUTH_COOKIE_DOMAIN : undefined;
- if (production && !domain)
- throw new Error("AUTH_COOKIE_DOMAIN must be configured when ENV is prod.");
+ const domain = serverEnv.AUTH_COOKIE_DOMAIN;
const options = {
httpOnly: true,
@@ -30,6 +28,6 @@ export function setAuthCookie(response: NextResponse, token: string): void {
response.headers.append("Set-Cookie", header);
};
- if (production) append("", undefined, 0);
+ if (domain) append("", undefined, 0);
append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0);
}
diff --git a/src/lib/external-auth.ts b/src/lib/external-auth.ts
new file mode 100644
index 0000000..4f942ba
--- /dev/null
+++ b/src/lib/external-auth.ts
@@ -0,0 +1,29 @@
+"use client";
+
+import type { LoginUser } from "@kri/common";
+import { getSessionStorage } from "@/store/storage/secure-storage";
+import { StorageKeys } from "@/store/storage/storage-keys";
+import { isRecord } from "@/types/kart";
+import { isExternalSession, type ShareLink } from "@/types/share";
+
+export type ExternalAuth = {
+ mode: "external";
+ user: LoginUser | null;
+ external?: ShareLink;
+ accessToken?: string;
+};
+
+export function isExternalAuth(value: unknown): value is ExternalAuth {
+ if (!isRecord(value) || value.mode !== "external") return false;
+ if (value.user === null) return value.external === undefined && value.accessToken === undefined;
+ return isExternalSession({ user: value.user, link: value.external }) &&
+ (value.accessToken === undefined || typeof value.accessToken === "string");
+}
+
+/** The mode survives missing/invalid token data so requests never fall back to the normal cookie. */
+export function readExternalAuth(): ExternalAuth | null {
+ if (getSessionStorage(StorageKeys.AuthMode) !== "external") return null;
+ const value = getSessionStorage(StorageKeys.ExternalAuth);
+ if (isExternalAuth(value)) return value;
+ return { mode: "external", user: null };
+}
diff --git a/src/lib/http-client.ts b/src/lib/http-client.ts
index 0b16b81..2fba008 100644
--- a/src/lib/http-client.ts
+++ b/src/lib/http-client.ts
@@ -1,6 +1,7 @@
-import { apiError, createHttpClient, redirectToLogout } from "@kri/common/http";
+import { apiError, createHttpClient, HttpError, redirectToLogout } from "@kri/common/http";
import { clientEnv } from "@/lib/env.client";
import { announceProjectAccess, projectFromRequest } from "@/lib/project-access";
+import { readExternalAuth } from "@/lib/external-auth";
const resolveBaseUrl = () =>
typeof window === "undefined"
@@ -8,9 +9,18 @@ const resolveBaseUrl = () =>
: new URL(clientEnv.API_BASE, window.location.origin).toString();
export const nextApi = createHttpClient(resolveBaseUrl(), {
+ getToken: () => {
+ const external = readExternalAuth();
+ if (!external) return null;
+ if (!external.accessToken) {
+ redirectToLogout();
+ throw new HttpError(401, { message: "공유 링크 인증이 필요합니다." }, "");
+ }
+ return external.accessToken;
+ },
onForbidden: (error) => {
const info = apiError(error);
- if (info.code === "EXTERNAL_SCOPE_DENIED" || info.code === "PROJECT_IDENTITY_REQUIRED") {
+ if (readExternalAuth() || info.code === "EXTERNAL_SCOPE_DENIED" || info.code === "PROJECT_IDENTITY_REQUIRED") {
redirectToLogout();
return;
}
@@ -20,3 +30,10 @@ export const nextApi = createHttpClient(resolveBaseUrl(), {
},
onResponseError: false,
});
+
+// Login/logout BFF operations must also work before an External JWT is available.
+export const authApi = createHttpClient(resolveBaseUrl(), {
+ onUnauthorized: false,
+ onForbidden: false,
+ onResponseError: false,
+});
diff --git a/src/lib/http-server.ts b/src/lib/http-server.ts
index cf0fa11..1d5aa8d 100644
--- a/src/lib/http-server.ts
+++ b/src/lib/http-server.ts
@@ -1,11 +1,19 @@
-import { cookies } from "next/headers";
+import { cookies, headers } from "next/headers";
import { createHttpClient } from "@kri/common/http";
import { serverEnv } from "@/lib/env.server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
+export async function getServerAccessToken(): Promise {
+ const authorization = (await headers()).get("authorization");
+ // Explicit credentials take precedence even when malformed; never use the normal
+ // cookie as a fallback for an External request. The backend verifies the JWT.
+ if (authorization !== null) return /^Bearer ([^\s]+)$/i.exec(authorization)?.[1] ?? null;
+ return (await cookies()).get(CookieKeys.AuthToken)?.value ?? null;
+}
+
export async function createServerApi(authenticated = true) {
- const cookieStore = await cookies();
- const accessToken = authenticated ? cookieStore.get(CookieKeys.AuthToken)?.value ?? null : null;
+ let accessToken: string | null = null;
+ if (authenticated) accessToken = await getServerAccessToken();
return createHttpClient(serverEnv.API_SERVER, {
getToken: () => accessToken,
defaultHeaders: { "content-type": "application/json" },
diff --git a/src/query/auth.ts b/src/query/auth.ts
index 2c51db5..24ffadd 100644
--- a/src/query/auth.ts
+++ b/src/query/auth.ts
@@ -5,15 +5,16 @@ import { useMutation } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { useResetSession } from "@/hooks/useResetSession";
import { notifyAuthChange } from "@/lib/auth-change";
-import { nextApi } from "@/lib/http-client";
+import { authApi } from "@/lib/http-client";
import { isLoginUser } from "@/types/kart";
+import { readExternalAuth } from "@/lib/external-auth";
export function useLoginMutation() {
const { setFromLoginResponse } = useAuth();
const resetSession = useResetSession();
return useMutation({
mutationFn: async (request: LoginRequest) => {
- const user = await nextApi.post("/login", request, {
+ const user = await authApi.post("/login", request, {
skipUnauthorizedHandler: true,
skipForbiddenHandler: true,
skipResponseErrorHandler: true,
@@ -32,17 +33,21 @@ export function useLoginMutation() {
export function useLogoutMutation() {
const { logout } = useAuth();
const resetSession = useResetSession();
+ const externalSession = () => !!readExternalAuth();
return useMutation({
- mutationFn: () =>
- nextApi.post("/logout", null, {
+ onMutate: () => ({ external: externalSession() }),
+ mutationFn: async () => {
+ if (externalSession()) return;
+ await authApi.post("/logout", null, {
skipUnauthorizedHandler: true,
skipForbiddenHandler: true,
skipResponseErrorHandler: true,
- }),
- onSettled: async () => {
+ });
+ },
+ onSettled: async (_data, _error, _variables, context) => {
await resetSession();
logout();
- notifyAuthChange("/login");
+ if (!context?.external) notifyAuthChange("/login");
},
});
}
diff --git a/src/store/storage/storage-keys.ts b/src/store/storage/storage-keys.ts
index 985598f..20be54e 100644
--- a/src/store/storage/storage-keys.ts
+++ b/src/store/storage/storage-keys.ts
@@ -1,10 +1,14 @@
export const StorageKeys = {
AuthState: "kri:authState",
+ AuthMode: "kart:authMode",
+ ExternalAuth: "kart:externalAuth",
SelectedProject: "kart:selectedProject",
} as const;
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
export const StorageType: Record = {
[StorageKeys.AuthState]: "local",
+ [StorageKeys.AuthMode]: "session",
+ [StorageKeys.ExternalAuth]: "session",
[StorageKeys.SelectedProject]: "session",
};
diff --git a/src/types/share.ts b/src/types/share.ts
index 8554e57..d035f3d 100644
--- a/src/types/share.ts
+++ b/src/types/share.ts
@@ -15,6 +15,12 @@ export type ShareLink = ProjectRef & {
pageOnly: boolean;
};
export type ExternalSession = { user: LoginUser; link: ShareLink };
+export type ExternalLoginResponse = ExternalSession & { accessToken: string };
+
+export function isExternalLoginResponse(value: unknown): value is ExternalLoginResponse {
+ return isRecord(value) && typeof value.accessToken === "string" &&
+ value.accessToken.length > 0 && isExternalSession(value);
+}
export function isExternalUser(user: LoginUser | null | undefined): boolean {
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
From c2a26af0dc67dc391dd0059a5b4364ecea382538 Mon Sep 17 00:00:00 2001
From: kric_jspark
Date: Mon, 2 Nov 2026 16:19:50 +0900
Subject: [PATCH 3/4] =?UTF-8?q?261102=5F03=5FFIX:=20=ED=94=84=EB=A1=9C?=
=?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EC=A0=84=ED=99=98=20=EC=8B=9C=20=EB=AA=A9?=
=?UTF-8?q?=EB=A1=9D=20=EC=A1=B0=ED=9A=8C=20=EC=BF=BC=EB=A6=AC=20=EC=B7=A8?=
=?UTF-8?q?=EC=86=8C=20=EB=AC=B8=EC=A0=9C=20=EC=88=98=EC=A0=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
AGENTS.md | 1 +
src/components/project/ProjectEntry.tsx | 7 ++++---
src/hooks/useProjectNavigation.ts | 4 ++--
src/query/project.ts | 25 ++++++++++++++++++++++++-
4 files changed, 31 insertions(+), 6 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index ea8c723..728a888 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -229,6 +229,7 @@ When implementation is complete, report in Korean:
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
+- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable.
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
diff --git a/src/components/project/ProjectEntry.tsx b/src/components/project/ProjectEntry.tsx
index a422ede..46cf481 100644
--- a/src/components/project/ProjectEntry.tsx
+++ b/src/components/project/ProjectEntry.tsx
@@ -6,9 +6,9 @@ import type { Route } from "next";
import { useStore } from "jotai";
import { useQueryClient } from "@tanstack/react-query";
import { authStateAtom, useAuth } from "@/hooks/useAuth";
-import { useSelectedProject } from "@/hooks/useSelectedProject";
+import { selectedProjectAtom, useSelectedProject } from "@/hooks/useSelectedProject";
import { projectSelectionAtom } from "@/hooks/useProjectNavigation";
-import { checkProjectAccess } from "@/query/project";
+import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
import { isProjectPage } from "@/lib/report-navigation";
import {
announceProjectAccess, PROJECT_ACCESS_EVENT, projectAccessMessage, projectFromSearch,
@@ -50,7 +50,8 @@ export function ProjectEntry({ children }: { children: ReactNode }) {
if (!candidate) throw new Error("projectType과 pkey를 올바르게 지정해 주세요.");
await checkProjectAccess(candidate);
if (!current()) return;
- await queryClient.cancelQueries();
+ if (!auth.user) return;
+ await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), candidate);
if (!current()) return;
select(candidate);
announceProjectAccess({ project: candidate, allowed: true });
diff --git a/src/hooks/useProjectNavigation.ts b/src/hooks/useProjectNavigation.ts
index 5f25267..0cf31c1 100644
--- a/src/hooks/useProjectNavigation.ts
+++ b/src/hooks/useProjectNavigation.ts
@@ -8,7 +8,7 @@ import { toast } from "sonner";
import { useQueryClient } from "@tanstack/react-query";
import { authStateAtom } from "@/hooks/useAuth";
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
-import { checkProjectAccess } from "@/query/project";
+import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
import { announceProjectAccess, projectAccessMessage } from "@/lib/project-access";
import { isExternalUser } from "@/types/share";
import type { ProjectRef } from "@/types/kart";
@@ -37,7 +37,7 @@ export function useProjectNavigation() {
try {
await checkProjectAccess(project);
if (!current()) return;
- await queryClient.cancelQueries();
+ await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), project);
if (!current()) return;
store.set(selectedProjectAtom, { userId: auth.user.userId, project: { projectType: project.projectType, pkey: project.pkey } });
announceProjectAccess({ project, allowed: true });
diff --git a/src/query/project.ts b/src/query/project.ts
index 5c7e517..081bdd3 100644
--- a/src/query/project.ts
+++ b/src/query/project.ts
@@ -1,6 +1,8 @@
"use client";
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, type QueryClient } from "@tanstack/react-query";
+import type { LoginUser } from "@kri/common";
+import type { SelectedProject } from "@/hooks/useSelectedProject";
import { HttpError } from "@kri/common/http";
import { useAuth } from "@/hooks/useAuth";
import { isExternalUser } from "@/types/share";
@@ -19,6 +21,27 @@ import {
type DateRange,
} from "@/types/kart";
+export async function cancelPreviousProjectQueries(
+ queryClient: QueryClient,
+ user: LoginUser,
+ selected: SelectedProject,
+ next: ProjectRef,
+): Promise {
+ if (!selected || selected.userId !== user.userId) return;
+ const previous = selected.project;
+ if (previous.projectType === next.projectType && previous.pkey === next.pkey) return;
+
+ await queryClient.cancelQueries({
+ predicate: ({ queryKey }) => {
+ if (queryKey[0] !== "kart" || queryKey[1] !== user.userId ||
+ queryKey[2] !== user.userRole || queryKey[3] !== user.userTeam) return false;
+ // Project-scoped keys put type/pkey at positions 4/5 or 5/6.
+ return (queryKey[4] === previous.projectType && queryKey[5] === previous.pkey) ||
+ (queryKey[5] === previous.projectType && queryKey[6] === previous.pkey);
+ },
+ });
+}
+
/** Always check the server; a cached permission is not an authorization decision. */
export async function checkProjectAccess(project: ProjectRef): Promise {
const result = await nextApi.get(
From 1a70cbbad934d34231e0e1cedb7228a2cb0dd0ad Mon Sep 17 00:00:00 2001
From: kric_jspark
Date: Mon, 2 Nov 2026 18:10:57 +0900
Subject: [PATCH 4/4] =?UTF-8?q?261102=5F04=5FFIX:=20=EB=A1=9C=EC=BB=AC?=
=?UTF-8?q?=EC=97=90=20=EB=B9=88=EA=B0=92=EC=9D=B4=EB=9D=BC=EB=8F=84=20?=
=?UTF-8?q?=EC=9E=88=EC=96=B4=EC=95=BC=20=ED=95=B4=EC=84=9C=20=EB=B9=88?=
=?UTF-8?q?=EA=B0=92=20=EC=A3=BC=EC=9E=85?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.env.local | 1 +
1 file changed, 1 insertion(+)
diff --git a/.env.local b/.env.local
index f50767d..f85033d 100644
--- a/.env.local
+++ b/.env.local
@@ -1,3 +1,4 @@
NEXT_PUBLIC_ENV=local
ENV=local
API_SERVER=http://localhost:4015/api/v1
+AUTH_COOKIE_DOMAIN=
\ No newline at end of file