260702_01_ENH: 리스트 작업 도중 공용 ui를 적용하기 위한 중간 커밋
This commit is contained in:
@@ -1,17 +1,11 @@
|
||||
const required = <K extends keyof typeof RAW_PUBLIC_ENV>(name: K) => {
|
||||
const v = RAW_PUBLIC_ENV[name];
|
||||
if (!v) throw new Error(`Missing env: ${name}`);
|
||||
return v;
|
||||
};
|
||||
import { createEnv, env } from "@kri/common/config";
|
||||
|
||||
const RAW_PUBLIC_ENV = {
|
||||
NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV,
|
||||
NEXT_PUBLIC_API_BASE: process.env.NEXT_PUBLIC_API_BASE,
|
||||
NEXT_PUBLIC_STORE_KEY: process.env.NEXT_PUBLIC_STORE_KEY,
|
||||
} as const;
|
||||
export const clientEnv = createEnv({
|
||||
ENV: env.required("NEXT_PUBLIC_ENV", process.env.NEXT_PUBLIC_ENV),
|
||||
|
||||
export const clientEnv = {
|
||||
ENV: required("NEXT_PUBLIC_ENV"),
|
||||
API_BASE: required("NEXT_PUBLIC_API_BASE"),
|
||||
STORE_KEY: required("NEXT_PUBLIC_STORE_KEY"),
|
||||
};
|
||||
API_BASE: env.required("NEXT_PUBLIC_API_BASE", process.env.NEXT_PUBLIC_API_BASE),
|
||||
|
||||
API_INTERNAL: env.required("NEXT_PUBLIC_API_INTERNAL", process.env.NEXT_PUBLIC_API_INTERNAL),
|
||||
|
||||
STORE_KEY: env.required("NEXT_PUBLIC_STORE_KEY", process.env.NEXT_PUBLIC_STORE_KEY),
|
||||
});
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
const required = (name: string) => {
|
||||
const v = process.env[name];
|
||||
if (!v) throw new Error(`Missing env: ${name}`);
|
||||
return v;
|
||||
};
|
||||
import "server-only";
|
||||
|
||||
export const serverEnv = {
|
||||
ENV: required("ENV"),
|
||||
CONTACT_SERVER: required("CONTACT_SERVER"),
|
||||
API_CONTACT_SERVER: required("API_CONTACT_SERVER"),
|
||||
API_NOTIHUB_SERVER: required("API_NOTIHUB_SERVER"),
|
||||
API_INTRANET_SERVER: required("API_INTRANET_SERVER"),
|
||||
API_KART_SERVER: required("API_KART_SERVER"),
|
||||
KART_API_KEY: required("KART_API_KEY"),
|
||||
// 다른 서버 전용 env들 추가 가능
|
||||
};
|
||||
import { createEnv, env } from "@kri/common/config";
|
||||
|
||||
export const serverEnv = createEnv({
|
||||
ENV: env.required("ENV", process.env.ENV),
|
||||
|
||||
CONTACT_SERVER: env.required("CONTACT_SERVER", process.env.CONTACT_SERVER),
|
||||
|
||||
API_CONTACT_SERVER: env.required("API_CONTACT_SERVER", process.env.API_CONTACT_SERVER),
|
||||
|
||||
API_NOTIHUB_SERVER: env.required("API_NOTIHUB_SERVER", process.env.API_NOTIHUB_SERVER),
|
||||
|
||||
API_INTRANET_SERVER: env.required("API_INTRANET_SERVER", process.env.API_INTRANET_SERVER),
|
||||
|
||||
API_KART_SERVER: env.required("API_KART_SERVER", process.env.API_KART_SERVER),
|
||||
|
||||
KART_API_KEY: env.required("KART_API_KEY", process.env.KART_API_KEY),
|
||||
});
|
||||
|
||||
@@ -1,327 +1,8 @@
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import {DEFAULT_API_TIMEOUT_MS} from "@/const/commonConst";
|
||||
|
||||
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
||||
|
||||
export class HttpError extends Error {
|
||||
public readonly status: number;
|
||||
public readonly data: unknown;
|
||||
public readonly url: string;
|
||||
private readonly headerMap: Record<string, string>;
|
||||
|
||||
constructor(status: number, data: unknown, url: string, headers?: Headers) {
|
||||
super(`HTTP ${status}`);
|
||||
this.name = "HttpError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
this.url = url;
|
||||
this.headerMap =
|
||||
headers && typeof headers.entries === "function"
|
||||
? Object.fromEntries(headers.entries())
|
||||
: {};
|
||||
}
|
||||
|
||||
get headers(): Record<string, string> {
|
||||
return this.headerMap;
|
||||
}
|
||||
|
||||
get traceId(): string | undefined {
|
||||
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
|
||||
}
|
||||
}
|
||||
|
||||
export type QueryValue = string | string[] | undefined;
|
||||
export type Query = Record<string, QueryValue>;
|
||||
export type PathParams = Record<string, string | number | boolean>;
|
||||
|
||||
export type NextFetchOptions = {
|
||||
revalidate?: number;
|
||||
tags?: string[];
|
||||
};
|
||||
|
||||
export type RequestOptions = {
|
||||
method?: HttpMethod;
|
||||
pathParams?: PathParams;
|
||||
query?: Query;
|
||||
json?: unknown;
|
||||
rawBody?: string;
|
||||
form?: FormData;
|
||||
headers?: Record<string, string>;
|
||||
timeoutMs?: number;
|
||||
suppressAlert?: boolean;
|
||||
onAuthError?: () => void;
|
||||
autoLogoutOnAuthError?: boolean;
|
||||
expectText?: boolean;
|
||||
expectBinary?: boolean;
|
||||
cache?: RequestCache; // "force-cache" | "no-store" | ...
|
||||
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
|
||||
};
|
||||
|
||||
export type HttpClientOptions = {
|
||||
getToken?: () => string | null;
|
||||
defaultTimeoutMs?: number;
|
||||
defaultHeaders?: Record<string, string>;
|
||||
setErrorMessage?: (status: number, serverMsg?: string) => string;
|
||||
};
|
||||
|
||||
let logoutRedirectStarted = false;
|
||||
|
||||
const canRedirectToLogout = (): boolean => {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (logoutRedirectStarted) return false;
|
||||
|
||||
const { pathname } = window.location;
|
||||
if (pathname === "/logout" || pathname === "/login") return false;
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const redirectToLogout = (): void => {
|
||||
if (!canRedirectToLogout()) return;
|
||||
|
||||
logoutRedirectStarted = true;
|
||||
|
||||
try {
|
||||
window.location.replace("/logout");
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const replacePathParams = (path: string, params?: PathParams): string => {
|
||||
if (!params) return path;
|
||||
let out = path;
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
const ph = `:${k}`;
|
||||
if (out.includes(ph)) out = out.replace(ph, encodeURIComponent(String(v)));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const appendQuery = (u: URL, query?: Query): void => {
|
||||
if (!query) return;
|
||||
for (const [k, v] of Object.entries(query)) {
|
||||
if (Array.isArray(v)) v.forEach((it) => u.searchParams.append(k, it));
|
||||
else if (v !== undefined) u.searchParams.set(k, v);
|
||||
}
|
||||
};
|
||||
|
||||
const buildHeaders = (base: Record<string, string>, extra?: Record<string, string>): Headers => {
|
||||
const h = new Headers(base);
|
||||
if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v);
|
||||
return h;
|
||||
};
|
||||
|
||||
const isAbortError = (err: unknown): boolean => {
|
||||
if (!err || typeof err !== "object") return false;
|
||||
const e = err as { name?: unknown; code?: unknown; message?: unknown };
|
||||
return (
|
||||
e.name === "AbortError" || // browser fetch abort
|
||||
e.code === "ABORT_ERR" || // some runtimes
|
||||
(typeof e.message === "string" && e.message.toLowerCase().includes("aborted"))
|
||||
);
|
||||
};
|
||||
|
||||
const isJsonContentType = (ctype: string) => {
|
||||
const ct = (ctype ?? "").toLowerCase()
|
||||
return ct.includes("application/json") || ct.includes("+json")
|
||||
}
|
||||
|
||||
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
|
||||
const {
|
||||
getToken,
|
||||
defaultTimeoutMs = DEFAULT_API_TIMEOUT_MS,
|
||||
defaultHeaders = { "content-type": "application/json" },
|
||||
setErrorMessage,
|
||||
} = opts;
|
||||
|
||||
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
|
||||
const replaced = replacePathParams(path, options.pathParams);
|
||||
|
||||
let url: URL;
|
||||
if (/^https?:\/\//i.test(replaced)) {
|
||||
url = new URL(replaced);
|
||||
} else if (replaced.startsWith("/")) {
|
||||
const base = new URL(baseURL);
|
||||
const joinedPath = `${base.pathname.replace(/\/+$/, "")}/${replaced.replace(/^\/+/, "")}`;
|
||||
url = new URL(base.toString());
|
||||
url.pathname = joinedPath;
|
||||
} else {
|
||||
url = new URL(replaced, new URL(baseURL));
|
||||
}
|
||||
|
||||
appendQuery(url, options.query);
|
||||
|
||||
const base: Record<string, string> = { ...defaultHeaders };
|
||||
const token = getToken?.();
|
||||
if (token) base["authorization"] = `Bearer ${token}`;
|
||||
const headers = buildHeaders(base, options.headers);
|
||||
|
||||
let body: BodyInit | undefined;
|
||||
if (options.form) {
|
||||
headers.delete("content-type");
|
||||
body = options.form;
|
||||
} else if (options.rawBody !== undefined) {
|
||||
if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=utf-8");
|
||||
body = options.rawBody;
|
||||
} else if (options.json !== undefined) {
|
||||
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
||||
body = typeof options.json === "string" ? options.json : JSON.stringify(options.json);
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
|
||||
|
||||
const isServer = typeof window === "undefined";
|
||||
const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
|
||||
const nextOpt = isServer ? options.next : undefined;
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString(), {
|
||||
method: options.method ?? (body ? "POST" : "GET"),
|
||||
headers,
|
||||
body,
|
||||
cache: cacheMode,
|
||||
// TS에서 RequestInit에 next가 없어서 캐스팅 필요
|
||||
...(nextOpt ? ({ next: nextOpt } as any) : {}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (options.expectBinary) {
|
||||
if (!res.ok) {
|
||||
const rawText = await res.text().catch(() => "");
|
||||
const ctype = res.headers.get("content-type") ?? ""
|
||||
const isJson = isJsonContentType(ctype)
|
||||
|
||||
let parsedError: unknown;
|
||||
if (isJson && rawText) {
|
||||
try {
|
||||
parsedError = JSON.parse(rawText);
|
||||
} catch {
|
||||
parsedError = rawText;
|
||||
}
|
||||
} else {
|
||||
parsedError = rawText || null;
|
||||
}
|
||||
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
|
||||
redirectToLogout();
|
||||
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsedError === "object" && parsedError !== null && "message" in parsedError
|
||||
? String((parsedError as { message?: unknown }).message ?? "")
|
||||
: typeof parsedError === "string"
|
||||
? parsedError
|
||||
: undefined;
|
||||
|
||||
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
}
|
||||
|
||||
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
const buffer = await res.arrayBuffer();
|
||||
return buffer as T;
|
||||
}
|
||||
|
||||
const ctype = res.headers.get("content-type") ?? "";
|
||||
const isJson = isJsonContentType(ctype)
|
||||
const rawText = await res.text().catch(() => "");
|
||||
|
||||
const parsed: unknown = options.expectText
|
||||
? rawText
|
||||
: isJson
|
||||
? rawText
|
||||
? JSON.parse(rawText)
|
||||
: null
|
||||
: rawText;
|
||||
|
||||
if (!res.ok) {
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
|
||||
redirectToLogout();
|
||||
throw new HttpError(res.status, parsed, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsed === "object" && parsed !== null && "message" in parsed
|
||||
? String((parsed as { message?: unknown }).message ?? "")
|
||||
: typeof parsed === "string"
|
||||
? parsed
|
||||
: undefined;
|
||||
|
||||
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
}
|
||||
|
||||
throw new HttpError(res.status, parsed, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
return parsed as T;
|
||||
} catch (err: unknown) {
|
||||
if (isAbortError(err)) {
|
||||
throw new HttpError(
|
||||
408,
|
||||
{ message: "요청 시간이 초과되었습니다.", timeoutMs: options.timeoutMs ?? defaultTimeoutMs },
|
||||
url.toString()
|
||||
);
|
||||
}
|
||||
|
||||
let code: string | undefined;
|
||||
if (typeof err === "object" && err !== null) {
|
||||
const anyErr = err as { cause?: unknown; code?: unknown };
|
||||
|
||||
if (anyErr.cause && typeof anyErr.cause === "object") {
|
||||
const cause = anyErr.cause as { code?: unknown };
|
||||
if (typeof cause.code === "string") code = cause.code;
|
||||
}
|
||||
if (!code && typeof anyErr.code === "string") code = anyErr.code;
|
||||
}
|
||||
|
||||
if (code === "ECONNREFUSED") {
|
||||
throw new HttpError(404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString());
|
||||
}
|
||||
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
const get = <T = unknown>(path: string, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "GET" });
|
||||
|
||||
const post = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "POST", json });
|
||||
|
||||
const put = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "PUT", json });
|
||||
|
||||
const patch = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "PATCH", json });
|
||||
|
||||
const del = <T = unknown>(path: string, o?: Omit<RequestOptions, "method">) =>
|
||||
request<T>(path, { ...o, method: "DELETE" });
|
||||
|
||||
const postForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "POST", form });
|
||||
|
||||
const putForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "PUT", form });
|
||||
|
||||
return { request, get, post, put, patch, del, postForm, putForm };
|
||||
};
|
||||
import { createHttpClient } from "@kri/common/http";
|
||||
|
||||
export const nextApi = createHttpClient(clientEnv.API_BASE);
|
||||
|
||||
export const internalApi = createHttpClient(clientEnv.API_INTERNAL, {
|
||||
defaultHeaders: {},
|
||||
});
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { createHttpClient } from "@/lib/http-client";
|
||||
import { createHttpClient } from "@kri/common/http";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||
|
||||
const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string, string>) => {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get("access_token")?.value ?? null;
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value ?? null;
|
||||
|
||||
return createHttpClient(rootUrl, {
|
||||
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
|
||||
getToken: () => accessToken,
|
||||
defaultHeaders: {
|
||||
"content-type": "application/json",
|
||||
...(defaultHeaders ?? {}),
|
||||
@@ -17,18 +18,18 @@ const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string,
|
||||
|
||||
export const createContactApi = () => {
|
||||
return createServerApi(serverEnv.API_CONTACT_SERVER);
|
||||
}
|
||||
};
|
||||
|
||||
export const createNotihubApi = () => {
|
||||
return createServerApi(serverEnv.API_NOTIHUB_SERVER);
|
||||
}
|
||||
};
|
||||
|
||||
export const createIntranetApi = () => {
|
||||
return createServerApi(serverEnv.API_INTRANET_SERVER);
|
||||
}
|
||||
};
|
||||
|
||||
export const createKartApi = () => {
|
||||
return createServerApi(serverEnv.API_KART_SERVER, {
|
||||
"X-API-Key": serverEnv.KART_API_KEY,
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
import {NextResponse} from "next/server";
|
||||
import {HttpError} from "@/lib/http-client";
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@/const/commonConst";
|
||||
|
||||
export type ApiError = {
|
||||
status: number
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export const errorToResponse = (error: unknown) => {
|
||||
if (error instanceof HttpError) {
|
||||
const payload = error.data ?? { message: "서버에서 오류 응답을 받았습니다." }
|
||||
return NextResponse.json(payload, { status: error.status })
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: "서버 내부 오류가 발생했습니다." },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const isDev = clientEnv.ENV !== "prod"
|
||||
|
||||
export const apiError = (e: unknown): ApiError => {
|
||||
if (e instanceof HttpError) {
|
||||
const d = e.data as any
|
||||
const code = typeof d?.code === "string" ? d.code : UNKNOWN_HTTP_ERROR
|
||||
const message =
|
||||
(typeof d?.detail === "string" && d.detail) ||
|
||||
(typeof d?.message === "string" && d.message) ||
|
||||
(typeof d?.errMessage === "string" && d.errMessage) ||
|
||||
(typeof d === "string" && d) ||
|
||||
`HTTP ${e.status}`
|
||||
|
||||
if (isDev) {
|
||||
console.groupCollapsed(
|
||||
`[API ERROR] ${e.status}${code ? ` / ${code}` : ""}`
|
||||
)
|
||||
console.log("url:", e.url)
|
||||
if (e.traceId) console.log("traceId:", e.traceId)
|
||||
console.log("raw data:", d)
|
||||
console.groupEnd()
|
||||
}
|
||||
|
||||
return { status: e.status, code, message }
|
||||
}
|
||||
|
||||
if (isDev) console.error("[NON-HTTP ERROR]", e)
|
||||
return { status: 500, code: NONE_HTTP_ERROR, message: "저장에 실패했습니다." }
|
||||
}
|
||||
@@ -1,196 +1,28 @@
|
||||
import CryptoJS from "crypto-js";
|
||||
import { createSecurity } from "@kri/common/security";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
|
||||
const KEY = CryptoJS.enc.Utf8.parse("kr!-c0nTacT-fr0nT-CrypT0-Key-STR");
|
||||
const IV = CryptoJS.enc.Utf8.parse("kr!-c0nTacT-IVST");
|
||||
const KEY = "kr!-c0nTacT-fr0nT-CrypT0-Key-STR";
|
||||
|
||||
export type WordArray = CryptoJS.lib.WordArray;
|
||||
const IV = "kr!-c0nTacT-IVST";
|
||||
|
||||
export class Security {
|
||||
public static encryptBase64UrlObject(input: unknown): string {
|
||||
const data = JSON.stringify(input);
|
||||
return this.encryptBase64Url(data);
|
||||
}
|
||||
export const Security = createSecurity({
|
||||
key: KEY,
|
||||
iv: IV,
|
||||
|
||||
public static decryptBase64UrlObject(input: string): unknown {
|
||||
const data = this.decryptBase64Url(input);
|
||||
return JSON.parse(data);
|
||||
}
|
||||
|
||||
public static encryptBase64Object(input: unknown): string {
|
||||
const data = JSON.stringify(input);
|
||||
return this.encryptBase64(data);
|
||||
}
|
||||
|
||||
public static decryptBase64Object(input: string): unknown {
|
||||
const data = this.decryptBase64(input);
|
||||
return JSON.parse(data);
|
||||
}
|
||||
|
||||
public static encryptBase64Url(input: string): string {
|
||||
const data = this.decodeUtf8(input);
|
||||
const params = this.encrypt(data);
|
||||
return this.encodeBase64Url(params);
|
||||
}
|
||||
|
||||
public static decryptBase64Url(input: string): string {
|
||||
const data = this.decodeBase64Url(input);
|
||||
const decryptedData = this.decrypt(data);
|
||||
return this.encodeUtf8(decryptedData);
|
||||
}
|
||||
|
||||
public static encryptBase64(input: string): string {
|
||||
const data = this.decodeUtf8(input);
|
||||
const params = this.encrypt(data);
|
||||
return this.encodeBase64(params);
|
||||
}
|
||||
public static decryptBase64(input: string): string {
|
||||
try {
|
||||
const data = this.decodeBase64(input);
|
||||
const decryptedData = this.decrypt(data);
|
||||
return this.encodeUtf8(decryptedData);
|
||||
} catch (error) {
|
||||
console.error("SecurityFunction.decryptBase64 오류:", {
|
||||
input: input?.substring(0, 50) + "...", // 처음 50자만 로그
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
throw error;
|
||||
onInvalidConfig: ({ message }) => {
|
||||
if (typeof window === "undefined" || clientEnv.ENV !== "local") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public static encrypt(input: WordArray): WordArray {
|
||||
const params = CryptoJS.AES.encrypt(input, KEY, {
|
||||
iv: IV,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
});
|
||||
return params.ciphertext;
|
||||
}
|
||||
const target = window as Window & {
|
||||
__kfpaCryptoConfigAlerted?: boolean;
|
||||
};
|
||||
|
||||
public static decrypt(input: WordArray): WordArray {
|
||||
const params = CryptoJS.lib.CipherParams.create({
|
||||
ciphertext: input,
|
||||
});
|
||||
return CryptoJS.AES.decrypt(params, KEY, {
|
||||
iv: IV,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
});
|
||||
}
|
||||
|
||||
public static convertUint8ArrayToWordArray(input: Uint8Array): WordArray {
|
||||
const words: number[] = [];
|
||||
let i = 0;
|
||||
while (i < input.length) {
|
||||
const word =
|
||||
(input[i++] << 24) |
|
||||
(input[i++] << 16) |
|
||||
(input[i++] << 8) |
|
||||
input[i++];
|
||||
words.push(word);
|
||||
if (target.__kfpaCryptoConfigAlerted) {
|
||||
return;
|
||||
}
|
||||
return CryptoJS.lib.WordArray.create(words, words.length * 4);
|
||||
}
|
||||
|
||||
public static convertWordArrayToUint8Array(input: WordArray): Uint8Array {
|
||||
const array = new Uint8Array(input.words.length << 2);
|
||||
for (let i = 0, j = 0; i < input.words.length; i++) {
|
||||
const word = input.words[i];
|
||||
array[j++] = word >> 24;
|
||||
array[j++] = (word >> 16) & 0xff;
|
||||
array[j++] = (word >> 8) & 0xff;
|
||||
array[j++] = word & 0xff;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public static computeHmacSha256Hex(input: WordArray, key: WordArray): string {
|
||||
return this.encodeHex(this.computeHmacSha256(input, key));
|
||||
}
|
||||
|
||||
public static computeHmacSha256(input: WordArray, key: WordArray): WordArray {
|
||||
return CryptoJS.HmacSHA256(input, key);
|
||||
}
|
||||
|
||||
public static computeSha256Hex(input: WordArray): string {
|
||||
return this.encodeHex(this.computeSha256(input));
|
||||
}
|
||||
|
||||
public static computeSha256(input: WordArray): WordArray {
|
||||
return CryptoJS.SHA256(input);
|
||||
}
|
||||
|
||||
private static convertToSpecialChars(base64: string): string {
|
||||
return Array.from(base64)
|
||||
.map((char) => char.charCodeAt(0).toString(2).padStart(16, "0"))
|
||||
.map((binary) => binary.replace(/0/g, "\u200b").replace(/1/g, "\u200c"))
|
||||
.join("ㅤ");
|
||||
}
|
||||
|
||||
private static convertFromSpecialChars(input: string): string {
|
||||
return input
|
||||
.split("ㅤ")
|
||||
.map((bin) => bin.replace(/\u200b/g, "0").replace(/\u200c/g, "1"))
|
||||
.map((binary) => String.fromCharCode(parseInt(binary, 2)))
|
||||
.join("");
|
||||
}
|
||||
|
||||
public static encodeBase64UrlUtf8(input: string): string {
|
||||
return this.encodeBase64Url(this.decodeUtf8(input));
|
||||
}
|
||||
|
||||
public static decodeBase64UrlUtf8(input: string): string {
|
||||
return this.encodeUtf8(this.decodeBase64Url(input));
|
||||
}
|
||||
|
||||
public static encodeBase64Url(input: WordArray): string {
|
||||
const base64url = CryptoJS.enc.Base64url.stringify(input);
|
||||
return this.convertToSpecialChars(base64url);
|
||||
}
|
||||
|
||||
public static decodeBase64Url(input: string): WordArray {
|
||||
try {
|
||||
const base64url = this.convertFromSpecialChars(input);
|
||||
return CryptoJS.enc.Base64url.parse(base64url);
|
||||
} catch {
|
||||
return CryptoJS.enc.Base64url.parse(input);
|
||||
}
|
||||
}
|
||||
|
||||
public static encodeBase64Utf8(input: string): string {
|
||||
return this.encodeBase64(this.decodeUtf8(input));
|
||||
}
|
||||
|
||||
public static decodeBase64Utf8(input: string): string {
|
||||
return this.encodeUtf8(this.decodeBase64(input));
|
||||
}
|
||||
|
||||
public static encodeBase64(input: WordArray): string {
|
||||
const base64 = CryptoJS.enc.Base64.stringify(input);
|
||||
return this.convertToSpecialChars(base64);
|
||||
}
|
||||
|
||||
public static decodeBase64(input: string): WordArray {
|
||||
try {
|
||||
const base64 = this.convertFromSpecialChars(input);
|
||||
return CryptoJS.enc.Base64.parse(base64);
|
||||
} catch {
|
||||
return CryptoJS.enc.Base64.parse(input);
|
||||
}
|
||||
}
|
||||
|
||||
public static encodeHex(input: WordArray): string {
|
||||
return CryptoJS.enc.Hex.stringify(input);
|
||||
}
|
||||
|
||||
public static decodeHex(input: string): WordArray {
|
||||
return CryptoJS.enc.Hex.parse(input);
|
||||
}
|
||||
|
||||
public static encodeUtf8(input: WordArray): string {
|
||||
return CryptoJS.enc.Utf8.stringify(input);
|
||||
}
|
||||
|
||||
public static decodeUtf8(input: string): WordArray {
|
||||
return CryptoJS.enc.Utf8.parse(input);
|
||||
}
|
||||
}
|
||||
target.__kfpaCryptoConfigAlerted = true;
|
||||
window.alert(message);
|
||||
},
|
||||
});
|
||||
|
||||
139
src/lib/utils.ts
139
src/lib/utils.ts
@@ -1,137 +1,2 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import type {NextRequest} from "next/server";
|
||||
|
||||
export type ValueOf<T> = T[keyof T];
|
||||
|
||||
export type EnumLikeKey<T extends Record<string, unknown>> = keyof T;
|
||||
export type EnumLikeValue<T extends Record<string, unknown>> = ValueOf<T>;
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function getKeyByValue<
|
||||
const T extends Record<PropertyKey, string>
|
||||
>(map: T, value: T[keyof T]) {
|
||||
const entry = Object.entries(map).find(([, v]) => v === value);
|
||||
return entry ? (entry[0] as keyof T) : undefined;
|
||||
}
|
||||
|
||||
export function getNumberKeyByValue(
|
||||
map: Record<number, string>,
|
||||
value: string
|
||||
): number | undefined {
|
||||
const entry = Object.entries(map).find(([, v]) => v === value);
|
||||
return entry ? Number(entry[0]) : undefined;
|
||||
}
|
||||
|
||||
export function buildUrlWithParams(
|
||||
targetPath: string,
|
||||
from: Record<string, string | string[] | undefined>,
|
||||
extra?: Record<string, string | undefined>,
|
||||
) {
|
||||
const qs = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(from)) {
|
||||
if (Array.isArray(v)) v.forEach((val) => qs.append(k, val));
|
||||
else if (v !== undefined) qs.set(k, v);
|
||||
}
|
||||
if (extra) for (const [k, v] of Object.entries(extra)) if (v) qs.set(k, v);
|
||||
return `${targetPath}${qs.toString() ? `?${qs}` : ""}`;
|
||||
}
|
||||
|
||||
export const downloadFile = (blob: Blob, filename: string) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
export const downloadBase64File = (base64: string, filename: string) => {
|
||||
const byteString = atob(base64);
|
||||
const arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
for (let i = 0; i < byteString.length; i++) {
|
||||
uint8Array[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
|
||||
const blob = new Blob([arrayBuffer], {
|
||||
type:
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
|
||||
downloadFile(blob, filename);
|
||||
};
|
||||
|
||||
export type DateTimeFormatOption =
|
||||
| "date" // 1-1. 날짜만
|
||||
| "dateHour" // 1-2. 날짜 + 시
|
||||
| "dateHourMin" // 1-3. 날짜 + 시 분
|
||||
| "dateTime"; // 1-4. 날짜 + 시 분 초
|
||||
|
||||
/**
|
||||
* 서버에서 받은 시간(ISO 문자열/Date/number)을 한국시간 기준으로 포맷팅
|
||||
* - 예: "2025-11-28T03:15:50Z" -> "2025-11-28 12:15:50" (KST)
|
||||
*/
|
||||
export const formatKst = (
|
||||
input: string | number | Date | null | undefined,
|
||||
opt: DateTimeFormatOption = "dateTime"
|
||||
): string => {
|
||||
if (!input) return "";
|
||||
|
||||
const d = input instanceof Date ? input : new Date(input);
|
||||
if (Number.isNaN(d.getTime())) return "";
|
||||
|
||||
// UTC -> KST(UTC+9) 변환
|
||||
const kst = new Date(d.getTime() + 9 * 60 * 60 * 1000);
|
||||
|
||||
const pad2 = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
const yyyy = kst.getUTCFullYear();
|
||||
const MM = pad2(kst.getUTCMonth() + 1);
|
||||
const dd = pad2(kst.getUTCDate());
|
||||
const HH = pad2(kst.getUTCHours());
|
||||
const mm = pad2(kst.getUTCMinutes());
|
||||
const ss = pad2(kst.getUTCSeconds());
|
||||
|
||||
if (opt === "date") return `${yyyy}-${MM}-${dd}`;
|
||||
if (opt === "dateHour") return `${yyyy}-${MM}-${dd} ${HH}`;
|
||||
if (opt === "dateHourMin") return `${yyyy}-${MM}-${dd} ${HH}:${mm}`;
|
||||
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
|
||||
};
|
||||
|
||||
export const isBlank = (v?: string | null) => !v || v.trim().length === 0;
|
||||
|
||||
export const getClientIp = (req: NextRequest): string | null => {
|
||||
const h = req.headers;
|
||||
|
||||
// 가장 흔한 케이스: 프록시/호스팅이 넣어줌
|
||||
const xff = h.get("x-forwarded-for");
|
||||
if (xff) {
|
||||
// "client, proxy1, proxy2" 형태. 보통 첫 번째가 client IP로 쓰이지만,
|
||||
// 프록시가 헤더를 덮어쓰지 않고 append만 하는 환경이면 spoof 가능성 있음.
|
||||
return xff.split(",")[0].trim();
|
||||
}
|
||||
|
||||
// 일부 인프라/프록시에서 쓰는 헤더들
|
||||
const xRealIp = h.get("x-real-ip");
|
||||
if (xRealIp) return xRealIp.trim();
|
||||
|
||||
// (Cloudflare 등) 사용 환경이면
|
||||
const cf = h.get("cf-connecting-ip");
|
||||
if (cf) return cf.trim();
|
||||
|
||||
// RFC 7239 Forwarded: for=1.2.3.4;proto=https;by=...
|
||||
const forwarded = h.get("forwarded");
|
||||
if (forwarded) {
|
||||
const m = forwarded.match(/for="?([^;,\s"]+)"?/i);
|
||||
if (m?.[1]) return m[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
//shadcn에서 이 경로의 cn을 사용하기 때문에 생성
|
||||
export { cn } from "@kri/common/ui";
|
||||
|
||||
Reference in New Issue
Block a user