251121_01_ENH : 로그인 및 인증 저장, api통신 시 자동으로 accessKey 붙게 조치

This commit is contained in:
2025-11-21 15:33:51 +09:00
parent 0707c91d41
commit 74de3d58f7
63 changed files with 2056 additions and 261 deletions

View File

@@ -1,8 +1,17 @@
export const clientEnv = {
API_BASE: process.env.NEXT_PUBLIC_API_BASE as string,
// 다른 클라이언트 전용 env들 추가 가능
ENV: process.env.NEXT_PUBLIC_ENV as string,
API_BASE: process.env.NEXT_PUBLIC_API_BASE as string,
STORE_KEY: process.env.NEXT_PUBLIC_STORE_KEY as string,
// 다른 클라이언트 전용 env들 추가 가능
};
if (!clientEnv.ENV) {
throw new Error("Missing env: NEXT_PUBLIC_ENV");
}
if (!clientEnv.API_BASE) {
throw new Error("Missing env: NEXT_PUBLIC_API_BASE");
}
if (!clientEnv.STORE_KEY) {
throw new Error("Missing env: NEXT_PUBLIC_STORE_KEY");
}

View File

@@ -1,10 +1,11 @@
const required = (name: string) => {
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
export const serverEnv = {
API_INTRANET: required("API_INTRANET"),
ENV: required("ENV"),
API_CONTACT_SERVER: required("API_CONTACT_SERVER"),
// 다른 서버 전용 env들 추가 가능
};

View File

@@ -1,4 +1,3 @@
// src/lib/http-client.ts
import { clientEnv } from "@/lib/env.client";
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
@@ -57,6 +56,12 @@ export type RequestOptions = {
suppressAlert?: boolean;
/** Hook for 401 responses */
onAuthError?: () => void;
/**
* 401/403(토큰 만료 포함) 수신 시 자동으로 /logout 으로 이동할지 여부
* - 기본값: true
* - 요청 단위로 false 설정하면 자동 로그아웃을 건너뜁니다.
*/
autoLogoutOnAuthError?: boolean;
/** Force treat response as text (skip JSON parse) */
expectText?: boolean;
};
@@ -116,9 +121,25 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
// 1) URL
const replaced = replacePathParams(path, options.pathParams);
const url = /^https?:\/\//i.test(replaced)
? new URL(replaced)
: new URL(replaced, baseURL);
// NOTE:
// new URL('/x', 'http://host/base') => 'http://host/x' (pathname from base is dropped)
// We want to preserve base pathname (e.g., '/api/v1') when caller passes an absolute path like '/auth/login'.
let url: URL;
if (/^https?:\/\//i.test(replaced)) {
// Fully-qualified URL: use as-is
url = new URL(replaced);
} else if (replaced.startsWith('/')) {
// Absolute-like path: merge with base's pathname
const base = new URL(baseURL);
const joinedPath = `${base.pathname.replace(/\/+$/, '')}/${replaced.replace(/^\/+/, '')}`;
url = new URL(base.toString());
url.pathname = joinedPath;
} else {
// Relative path: URL API will correctly join with base pathname
url = new URL(replaced, new URL(baseURL));
}
appendQuery(url, options.query);
// 2) headers (defaults + token + per-call)
@@ -168,9 +189,25 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
// 7) error (HTTP status 에러)
if (!res.ok) {
const autoLogout = options.autoLogoutOnAuthError ?? true;
const suppressAlert = options.suppressAlert ?? true;
// 401 훅 호출 (기존 동작 유지)
if (res.status === 401) options.onAuthError?.();
if (!options.suppressAlert && typeof window !== "undefined") {
// 401 또는 403 (토큰 만료 포함) 시 자동 로그아웃 처리
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
// 사용자 알림은 띄우지 않고 바로 로그아웃 라우팅으로 이동
try {
window.location.replace("/logout");
} catch {
// noop
}
// 이후 로직 진행을 막기 위해 에러를 던지기
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
if (!suppressAlert && typeof window !== "undefined") {
const serverMsg =
typeof parsed === "object" &&
parsed !== null &&

196
src/lib/security.ts Normal file
View File

@@ -0,0 +1,196 @@
import CryptoJS from "crypto-js";
const KEY = CryptoJS.enc.Utf8.parse("kr!-c0nTacT-fr0nT-CrypT0-Key-STR");
const IV = CryptoJS.enc.Utf8.parse("kr!-c0nTacT-IVST");
export type WordArray = CryptoJS.lib.WordArray;
export class Security {
public static encryptBase64UrlObject(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64Url(data);
}
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;
}
}
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;
}
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);
}
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);
}
}

17
src/lib/server-api.ts Normal file
View File

@@ -0,0 +1,17 @@
import { cookies } from "next/headers";
import { createHttpClient } from "@/lib/http-client";
import { serverEnv } from "@/lib/env.server";
const createServerApi = async (rootUrl: string) => {
const cookieStore = await cookies();
const accessToken = cookieStore.get("access_token")?.value ?? null;
return createHttpClient(rootUrl, {
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
defaultTimeoutMs: 10_000,
});
};
export const createContactApi = () => {
return createServerApi(serverEnv.API_CONTACT_SERVER);
}