261102_02_ENH: 공용 인증 쿠키 도메인 적용 조건 수정 및 외부 링크 인증 탭별 분리
This commit is contained in:
@@ -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<unknown>) => {
|
||||
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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
29
src/lib/external-auth.ts
Normal file
29
src/lib/external-auth.ts
Normal file
@@ -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 };
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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<string | null> {
|
||||
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" },
|
||||
|
||||
Reference in New Issue
Block a user