st: 기본 셋팅
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
import Cookies from "js-cookie";
|
||||
|
||||
export function getCookie(name: string): string | undefined {
|
||||
if (typeof window === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
return Cookies.get(name);
|
||||
}
|
||||
|
||||
export function setCookie(
|
||||
name: string,
|
||||
value: string,
|
||||
options?: Cookies.CookieAttributes,
|
||||
): void {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
Cookies.set(name, value, options);
|
||||
}
|
||||
|
||||
export function removeCookie(
|
||||
name: string,
|
||||
options?: Cookies.CookieAttributes,
|
||||
): void {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
Cookies.remove(name, options);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// CSP 위반 모니터링 및 보고 스크립트
|
||||
|
||||
interface CSPViolation {
|
||||
documentURI: string;
|
||||
blockedURI: string;
|
||||
violatedDirective: string;
|
||||
originalPolicy: string;
|
||||
sourceFile?: string;
|
||||
lineNumber?: number;
|
||||
columnNumber?: number;
|
||||
}
|
||||
|
||||
class CSPMonitor {
|
||||
private reportEndpoint: string;
|
||||
|
||||
constructor(reportEndpoint: string = '/api/csp-violation') {
|
||||
this.reportEndpoint = reportEndpoint;
|
||||
this.init();
|
||||
}
|
||||
|
||||
private init(): void {
|
||||
// CSP 위반 이벤트 리스너 등록
|
||||
document.addEventListener('securitypolicyviolation', (event) => {
|
||||
this.handleViolation(event);
|
||||
});
|
||||
|
||||
// 페이지 로드 시 CSP 정책 확인
|
||||
this.checkCSPPolicy();
|
||||
}
|
||||
|
||||
private handleViolation(event: SecurityPolicyViolationEvent): void {
|
||||
const violation: CSPViolation = {
|
||||
documentURI: event.documentURI,
|
||||
blockedURI: event.blockedURI,
|
||||
violatedDirective: event.violatedDirective,
|
||||
originalPolicy: event.originalPolicy,
|
||||
sourceFile: event.sourceFile,
|
||||
lineNumber: event.lineNumber,
|
||||
columnNumber: event.columnNumber
|
||||
};
|
||||
|
||||
// 콘솔에 위반 정보 출력
|
||||
console.warn('CSP Violation detected:', violation);
|
||||
|
||||
// 서버로 위반 정보 전송
|
||||
this.reportViolation(violation);
|
||||
}
|
||||
|
||||
private async reportViolation(violation: CSPViolation): Promise<void> {
|
||||
try {
|
||||
const response = await fetch(this.reportEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(violation),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Failed to report CSP violation:', response.statusText);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reporting CSP violation:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private checkCSPPolicy(): void {
|
||||
// CSP 헤더 확인
|
||||
const cspHeader = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
|
||||
if (cspHeader) {
|
||||
console.log('CSP Policy found in meta tag:', cspHeader.getAttribute('content'));
|
||||
} else {
|
||||
console.log('No CSP meta tag found, relying on HTTP headers');
|
||||
}
|
||||
}
|
||||
|
||||
// CSP 정책 테스트 함수
|
||||
public testCSPPolicy(): void {
|
||||
console.log('Testing CSP policy...');
|
||||
|
||||
// 인라인 스크립트 테스트
|
||||
try {
|
||||
eval('console.log("CSP test: inline script execution")');
|
||||
} catch {
|
||||
console.log('CSP blocked inline script execution');
|
||||
}
|
||||
|
||||
// 외부 스크립트 로드 테스트
|
||||
const testScript = document.createElement('script');
|
||||
testScript.src = 'https://example.com/test.js';
|
||||
testScript.onload = () => console.log('External script loaded successfully');
|
||||
testScript.onerror = () => console.log('CSP blocked external script');
|
||||
document.head.appendChild(testScript);
|
||||
}
|
||||
|
||||
// CSP 위반 통계 수집
|
||||
public getViolationStats(): Promise<unknown> {
|
||||
return fetch(`${this.reportEndpoint}/stats`)
|
||||
.then(response => response.json())
|
||||
.catch(error => {
|
||||
console.error('Error fetching CSP violation stats:', error);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 전역 CSP 모니터 인스턴스 생성
|
||||
export const cspMonitor = new CSPMonitor();
|
||||
|
||||
// 개발 환경에서만 CSP 테스트 실행
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// 페이지 로드 후 CSP 정책 테스트
|
||||
window.addEventListener('load', () => {
|
||||
setTimeout(() => {
|
||||
cspMonitor.testCSPPolicy();
|
||||
}, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
export default CSPMonitor;
|
||||
@@ -0,0 +1,61 @@
|
||||
import { generateCSPHeader } from '../config/csp';
|
||||
|
||||
// CSP 위반 인터페이스 정의
|
||||
interface CSPViolationData {
|
||||
documentURI: string;
|
||||
blockedURI: string;
|
||||
violatedDirective: string;
|
||||
originalPolicy: string;
|
||||
sourceFile?: string;
|
||||
lineNumber?: number;
|
||||
columnNumber?: number;
|
||||
}
|
||||
|
||||
// CSP 헤더를 설정하는 유틸리티 함수 (img-src만)
|
||||
export function setCSPHeaders(response: Response): Response {
|
||||
const environment = process.env.NODE_ENV as 'development' | 'production';
|
||||
const cspValue = generateCSPHeader(environment);
|
||||
|
||||
response.headers.set('Content-Security-Policy', cspValue);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// CSP 위반을 로깅하는 함수
|
||||
export function logCSPViolation(violation: CSPViolationData): void {
|
||||
console.warn('CSP Violation:', {
|
||||
documentURI: violation.documentURI,
|
||||
blockedURI: violation.blockedURI,
|
||||
violatedDirective: violation.violatedDirective,
|
||||
originalPolicy: violation.originalPolicy,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
// img-src 정책을 검증하는 함수
|
||||
export function validateImgSrcPolicy(policy: string): boolean {
|
||||
return policy.includes('img-src');
|
||||
}
|
||||
|
||||
// 개발 환경에서 CSP를 비활성화하는 함수 (디버깅용)
|
||||
export function disableCSPForDevelopment(): boolean {
|
||||
return process.env.NODE_ENV === 'development' &&
|
||||
process.env.DISABLE_CSP === 'true';
|
||||
}
|
||||
|
||||
// img-src에 도메인 추가하는 함수
|
||||
export function addDomainToImgSrc(
|
||||
currentPolicy: string,
|
||||
domain: string
|
||||
): string {
|
||||
if (currentPolicy.includes('img-src')) {
|
||||
// 기존 img-src에 도메인 추가
|
||||
return currentPolicy.replace(
|
||||
/img-src ([^;]+)/,
|
||||
`img-src $1 ${domain}`
|
||||
);
|
||||
} else {
|
||||
// img-src가 없으면 새로 생성
|
||||
return `${currentPolicy}; img-src 'self' ${domain};`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export { getCookie, setCookie, removeCookie } from "./cookie";
|
||||
export { useMutationWrapper } from "./use-mutation-wrapper";
|
||||
export { useAlertStore } from "./use-alert-store";
|
||||
export { useDataTable } from "./use-data-table";
|
||||
export { useMenuStore } from "./use-menu-store";
|
||||
export { useUserStore } from "./use-user-store";
|
||||
export { usePrompt } from "./use-prompt";
|
||||
export { useSelectPrompt } from "./use-select-prompt";
|
||||
@@ -0,0 +1,65 @@
|
||||
import { type UseQueryResult } from "@tanstack/react-query";
|
||||
import type { PageableList } from "../model";
|
||||
|
||||
/**
|
||||
* Match the state of a query to a set of components.
|
||||
*
|
||||
* Useful for rendering different UI based on the state of a query.
|
||||
*/
|
||||
export function matchQueryStatus<T>(
|
||||
query: UseQueryResult<PageableList<T>>,
|
||||
options: {
|
||||
Loading?: JSX.Element;
|
||||
Errored?: JSX.Element | ((error: unknown) => JSX.Element);
|
||||
Empty?: JSX.Element;
|
||||
Success: (
|
||||
data: UseQueryResult<PageableList<T>> & {
|
||||
data: NonNullable<UseQueryResult<T>["data"]>;
|
||||
},
|
||||
) => JSX.Element;
|
||||
},
|
||||
): JSX.Element;
|
||||
export function matchQueryStatus<T>(
|
||||
query: UseQueryResult<PageableList<T>>,
|
||||
options: {
|
||||
Loading?: JSX.Element;
|
||||
Errored?: JSX.Element | ((error: unknown) => JSX.Element);
|
||||
Success: (data: UseQueryResult<PageableList<T>>) => JSX.Element;
|
||||
},
|
||||
): JSX.Element;
|
||||
export function matchQueryStatus<T>(
|
||||
query: UseQueryResult<PageableList<T>>,
|
||||
{
|
||||
Loading,
|
||||
Errored,
|
||||
Empty,
|
||||
Success,
|
||||
}: {
|
||||
Loading?: JSX.Element;
|
||||
Errored?: JSX.Element | ((error: unknown) => JSX.Element);
|
||||
Empty?: JSX.Element;
|
||||
Success: (data: UseQueryResult<PageableList<T>>) => JSX.Element;
|
||||
},
|
||||
): JSX.Element {
|
||||
if (query.isLoading && Loading) {
|
||||
return Loading;
|
||||
}
|
||||
|
||||
if (query.isError && Errored) {
|
||||
if (typeof Errored === "function") {
|
||||
return Errored(query.error);
|
||||
}
|
||||
return Errored;
|
||||
}
|
||||
|
||||
const isEmpty =
|
||||
query.data?.content === undefined ||
|
||||
query.data?.content === null ||
|
||||
(Array.isArray(query.data?.content) && query.data?.content.length === 0);
|
||||
|
||||
if (isEmpty && Empty) {
|
||||
return Empty;
|
||||
}
|
||||
|
||||
return Success(query);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useStore } from "zustand";
|
||||
import { useContext } from "react";
|
||||
import type { AlertStore } from "../store/alert-store";
|
||||
import { StoreContext } from "../providers/store-provider";
|
||||
|
||||
export const useAlertStore = <T>(selector: (store: AlertStore) => T): T => {
|
||||
const storeContext = useContext(StoreContext);
|
||||
|
||||
if (!storeContext) {
|
||||
throw new Error("useAlertStore must be used within StoreProvider");
|
||||
}
|
||||
|
||||
return useStore(storeContext.alertStore, selector);
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useStore } from "zustand";
|
||||
import { useContext } from "react";
|
||||
import type { AttachmentStore } from "../store/attachment-store";
|
||||
import { StoreContext } from "../providers/store-provider";
|
||||
|
||||
export const useAttachmentStore = <T>(
|
||||
selector: (store: AttachmentStore) => T,
|
||||
): T => {
|
||||
const store = useContext(StoreContext);
|
||||
if (!store) {
|
||||
throw new Error("useAttachmentStore must be used within StoreProvider");
|
||||
}
|
||||
return useStore(store.attachmentStore, selector);
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import type { UseQueryResult } from "@tanstack/react-query";
|
||||
import { useReactTable, type TableOptions } from "@tanstack/react-table";
|
||||
import { DataTable } from "@common/components";
|
||||
import { NoData } from "../ui/no-data";
|
||||
import type { PageableList } from "../model";
|
||||
import { matchQueryStatus } from "./match-query-status";
|
||||
|
||||
type UseDataTableOptions<T> = {
|
||||
query: UseQueryResult<PageableList<T>>;
|
||||
tableOptions: Omit<TableOptions<T>, "data" | "rowCount">;
|
||||
dataTableOptions?: DataTableOptions<T>;
|
||||
};
|
||||
|
||||
type DataTableOptions<T> = {
|
||||
variant?: "default" | "secondary" | "line";
|
||||
className?: HTMLAttributes<HTMLTableElement>["className"];
|
||||
viewPagination?: boolean;
|
||||
onRowClick?: (row: T) => void;
|
||||
};
|
||||
|
||||
export const useDataTable = <T,>({
|
||||
query,
|
||||
tableOptions,
|
||||
dataTableOptions,
|
||||
}: UseDataTableOptions<T>) => {
|
||||
const table = useReactTable({
|
||||
...tableOptions,
|
||||
data: query.data?.content ?? [],
|
||||
rowCount: query.data?.totalElements ?? 0,
|
||||
});
|
||||
|
||||
return {
|
||||
tableComponent: matchQueryStatus(query, {
|
||||
Empty: <NoData />,
|
||||
Success: () => {
|
||||
return <DataTable table={table} {...dataTableOptions} />;
|
||||
},
|
||||
}),
|
||||
tableInstance: table,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useStore } from "zustand";
|
||||
import { useContext } from "react";
|
||||
import type { MenuStore } from "../store/menu-store";
|
||||
import { StoreContext } from "../providers/store-provider";
|
||||
|
||||
export const useMenuStore = <T>(selector: (store: MenuStore) => T): T => {
|
||||
const storeContext = useContext(StoreContext);
|
||||
|
||||
if (!storeContext) {
|
||||
throw new Error("useMenuStore must be used within StoreProvider");
|
||||
}
|
||||
|
||||
return useStore(storeContext.menuStore, selector);
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import { AxiosError } from "axios";
|
||||
import { useMutation, type UseMutationOptions } from "@tanstack/react-query";
|
||||
import { useAlertStore } from "./use-alert-store";
|
||||
|
||||
export const useMutationWrapper = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
TVariables = void,
|
||||
TContext = unknown,
|
||||
>(
|
||||
mutationOptions: UseMutationOptions<TData, TError, TVariables, TContext>,
|
||||
) => {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
return useMutation({
|
||||
...mutationOptions,
|
||||
onError: (error) => {
|
||||
let errorMessage = "";
|
||||
|
||||
if (error instanceof AxiosError) {
|
||||
if (error.response?.data?.message)
|
||||
errorMessage += `${error.response.data.message}\n`;
|
||||
if (error.response?.data?.errors[0]?.message)
|
||||
errorMessage += `${error.response.data.errors[0].message}\n`;
|
||||
}
|
||||
|
||||
alert(`${errorMessage}`);
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useContext } from "react";
|
||||
import { PromptContext } from "../providers/prompt-provider";
|
||||
|
||||
export const usePrompt = () => {
|
||||
const { message, resolve, setMessage, setResolve } =
|
||||
useContext(PromptContext);
|
||||
|
||||
const prompt = (message: string) => {
|
||||
setMessage(message);
|
||||
return new Promise<{ resolved: boolean; value?: string }>((resolve) => {
|
||||
setResolve(() => resolve);
|
||||
});
|
||||
};
|
||||
|
||||
const onSubmit = (value: string) => {
|
||||
resolve?.({ resolved: true, value });
|
||||
setMessage("");
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
resolve?.({ resolved: false });
|
||||
setMessage("");
|
||||
};
|
||||
|
||||
return { message, isOpen: !!message, prompt, onSubmit, onCancel };
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useContext, useEffect } from "react";
|
||||
import { PromptContext } from "../providers/prompt-provider";
|
||||
|
||||
type SelectData = {
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export const useSelectPrompt = (data?: SelectData[]) => {
|
||||
const {
|
||||
selectData,
|
||||
selectionGuide,
|
||||
resolve,
|
||||
setResolve,
|
||||
setSelectData,
|
||||
setSelectionGuide,
|
||||
} = useContext(PromptContext);
|
||||
|
||||
const prompt = (message: string) => {
|
||||
setSelectionGuide(message);
|
||||
return new Promise<{ resolved: boolean; value?: string }>((resolve) => {
|
||||
setResolve(() => resolve);
|
||||
});
|
||||
};
|
||||
|
||||
const onSubmit = (value: string) => {
|
||||
resolve?.({ resolved: true, value });
|
||||
setSelectionGuide("");
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
resolve?.({ resolved: false });
|
||||
setSelectionGuide("");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (data) setSelectData(data);
|
||||
}, [data]);
|
||||
|
||||
return {
|
||||
selectData,
|
||||
selectionGuide,
|
||||
isOpen: !!selectionGuide,
|
||||
prompt,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { type HttpResponse, Upload } from "tus-js-client";
|
||||
import { AUTH_USER_ID, CLAIM_NAME, ENDPOINT } from "../config";
|
||||
import { useAttachmentStore } from "./use-attachment-store";
|
||||
import { useAlertStore } from "./use-alert-store";
|
||||
import { getCookie } from "./cookie";
|
||||
|
||||
type TusProps = {
|
||||
accept?: string;
|
||||
};
|
||||
|
||||
export const useTus = ({ accept }: TusProps = {}) => {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { attachmentFileCode, setAttachmentFileCode } = useAttachmentStore(
|
||||
(state) => state,
|
||||
);
|
||||
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [upload, setUpload] = useState<Upload | null>(null);
|
||||
const [response, setResponse] = useState<HttpResponse | null>(null);
|
||||
const [progress, setProgress] = useState<number>(0);
|
||||
const [isValid, setIsValid] = useState<boolean>(false);
|
||||
|
||||
const metadata = {
|
||||
filename: file?.name ?? "",
|
||||
filetype: file?.type ?? "",
|
||||
atflCd: attachmentFileCode,
|
||||
};
|
||||
|
||||
const validFileType = (file: File) => {
|
||||
const allowedExtensions = accept?.split(",") ?? [];
|
||||
const fileName = file.name;
|
||||
const fileExtension = fileName
|
||||
.substring(fileName.lastIndexOf("."))
|
||||
.toLowerCase();
|
||||
|
||||
if (!allowedExtensions.includes(fileExtension)) {
|
||||
alert("파일 형식이 올바르지 않습니다.");
|
||||
setIsValid(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
setIsValid(true);
|
||||
return true;
|
||||
};
|
||||
|
||||
const createUpload = () => {
|
||||
return new Upload(file!, {
|
||||
endpoint: `${ENDPOINT.ATTACH_SERVICE.TUS_UPLOAD}`,
|
||||
chunkSize: 10 * 1024 * 1024,
|
||||
headers: {
|
||||
[CLAIM_NAME]: getCookie(CLAIM_NAME) ?? "",
|
||||
[AUTH_USER_ID]: getCookie(AUTH_USER_ID) ?? "",
|
||||
},
|
||||
metadata,
|
||||
onError(error) {
|
||||
throw new Error(`Failed because: ${error}`);
|
||||
},
|
||||
onProgress(bytesUploaded, bytesTotal) {
|
||||
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
|
||||
setProgress(parseInt(percentage));
|
||||
},
|
||||
onAfterResponse(req, res) {
|
||||
const fileInfo = res.getHeader("X-File-Info");
|
||||
if (fileInfo === undefined || fileInfo === null) return;
|
||||
|
||||
setAttachmentFileCode(JSON.parse(fileInfo)?.atflCd ?? "");
|
||||
setResponse(res);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!file) return;
|
||||
if (!validFileType(file)) return;
|
||||
|
||||
const upload = createUpload();
|
||||
upload.start();
|
||||
setUpload(upload);
|
||||
}, [file]);
|
||||
|
||||
return {
|
||||
file,
|
||||
upload,
|
||||
response,
|
||||
progress,
|
||||
isValid,
|
||||
setFile,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useStore } from "zustand";
|
||||
import { useContext } from "react";
|
||||
import type { UserStore } from "../store/user-store";
|
||||
import { StoreContext } from "../providers/store-provider";
|
||||
|
||||
export const useUserStore = <T>(selector: (store: UserStore) => T): T => {
|
||||
const storeContext = useContext(StoreContext);
|
||||
|
||||
if (!storeContext) {
|
||||
throw new Error("useUserStore must be used within StoreProvider");
|
||||
}
|
||||
|
||||
return useStore(storeContext.userStore, selector);
|
||||
};
|
||||
Reference in New Issue
Block a user