develop #1

Merged
gitadmin merged 8 commits from develop into master 2026-10-27 09:04:55 +09:00
5 changed files with 407 additions and 1 deletions
Showing only changes of commit d4747b0ea0 - Show all commits

View File

@@ -1,6 +1,26 @@
import type { NextConfig } from "next";
import { createKriNextConfig } from "@kri/common/config";
const nextConfig = createKriNextConfig({}) satisfies NextConfig;
const nextConfig = createKriNextConfig({
async headers() {
return [
{
source: "/api/kric-internal/:path*",
headers: [
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET, POST, OPTIONS" },
{
key: "Access-Control-Allow-Headers",
value: "Content-Type, X-API-Key",
},
{
key: "Access-Control-Expose-Headers",
value: "Content-Disposition",
},
],
},
];
},
}) satisfies NextConfig;
export default nextConfig;

View File

@@ -0,0 +1,97 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApiWithApiKey } from "@/lib/http-server";
import {
internalTarget,
readInternalQuotaRequest,
readInternalReportBatch,
} from "@/lib/kric-internal-policy";
import { readExcelRequest } from "@/types/export";
import type { RouteContext } from "@/types/common";
export const maxDuration = 660;
const noStore = { "Cache-Control": "no-store" };
const jsonError = (message: string, status: number) =>
NextResponse.json({ message }, { status, headers: noStore });
async function handle(request: NextRequest, context: RouteContext) {
const { slug = [] } = await context.params;
const target = internalTarget(request.method, slug);
if (!target) return jsonError("지원하지 않는 경로입니다.", 404);
const apiKey = request.headers.get("x-api-key")?.trim();
if (!apiKey) return jsonError("X-API-Key는 필수입니다.", 401);
let body: unknown;
if (target.kind !== "list") {
try {
const input: unknown = await request.json();
body =
target.kind === "report"
? readInternalReportBatch(input)
: target.kind === "quota"
? readInternalQuotaRequest(input)
: readExcelRequest(input);
} catch (error) {
return jsonError(
error instanceof SyntaxError
? "요청 JSON을 확인해 주세요."
: error instanceof Error
? error.message
: "요청 내용을 확인해 주세요.",
400,
);
}
}
try {
const api = createServerApiWithApiKey(apiKey);
const options = { signal: request.signal, cache: "no-store" as const };
if (target.kind === "list" || target.kind === "quota") {
const result =
target.kind === "list"
? await api.get<unknown>(target.path, options)
: await api.post<unknown>(target.path, body, options);
return NextResponse.json(result, { headers: noStore });
}
const upstream = await api.streamPost(target.path, body, {
...options,
timeoutMs: 600_000,
idleTimeoutMs: 600_000,
...(target.kind === "report"
? { headers: { Accept: "application/x-ndjson" } }
: {}),
});
const contentType =
upstream.headers.get("content-type") ?? "application/octet-stream";
const disposition = upstream.headers.get("content-disposition");
if (
!upstream.body ||
(target.kind === "report"
? !contentType.includes("application/x-ndjson")
: !disposition || /json|text\/html/i.test(contentType))
) {
await upstream.body?.cancel();
return jsonError("서버 응답 형식을 확인해 주세요.", 502);
}
return new Response(upstream.body, {
headers: {
...noStore,
"Content-Type": contentType,
...(target.kind === "report"
? { "X-Accel-Buffering": "no" }
: disposition
? { "Content-Disposition": disposition }
: {}),
},
});
} catch (error: unknown) {
const response = errorToResponse(error);
response.headers.set("Cache-Control", "no-store");
return response;
}
}
export const GET = handle;
export const POST = handle;
export const OPTIONS = () =>
new NextResponse(null, { status: 204, headers: noStore });

View File

@@ -0,0 +1,220 @@
import type { ReportFilter } from "@/types/report";
type Token = { text: string; position: number } & (
| { kind: "word" | "symbol" | "end" }
| { kind: "value"; value: string | number }
);
const fail = (position: number, message: string): never => {
throw new Error(`필터 ${position + 1}번째 문자: ${message}`);
};
/** A bounded expression grammar, never SQL or JavaScript execution. */
function tokenize(source: string): Token[] {
if (source.length > 8192) fail(0, "조건식은 8192자 이내로 작성해 주세요.");
const tokens: Token[] = [];
let position = 0;
while (position < source.length) {
if (/\s/.test(source[position])) {
position++;
continue;
}
if (tokens.length >= 2048) fail(position, "조건식이 너무 복잡합니다.");
const start = position;
const char = source[position];
if (char === "'" || char === '"') {
position++;
let value = "",
closed = false;
while (position < source.length) {
const next = source[position++];
if (next !== char) {
value += next;
continue;
}
if (source[position] === char) {
value += char;
position++;
} else {
closed = true;
break;
}
}
if (!closed) fail(start, "문자열의 닫는 따옴표가 필요합니다.");
tokens.push({
kind: "value",
text: source.slice(start, position),
value,
position: start,
});
continue;
}
const rest = source.slice(position);
const number = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest);
if (number) {
const value = Number(number[0]);
if (
!Number.isFinite(value) ||
(Number.isInteger(value) && !Number.isSafeInteger(value))
)
fail(
start,
"숫자 범위를 확인해 주세요. 큰 코드값은 따옴표로 감싸 주세요.",
);
tokens.push({ kind: "value", text: number[0], value, position: start });
position += number[0].length;
continue;
}
const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest);
const symbol = /^(?:>=|<=|<>|!=|[=><(),])/.exec(rest);
const match = word ?? symbol;
if (!match)
return fail(
start,
"지원하지 않는 문자입니다. 문항 ID, 비교식, AND·OR·괄호를 사용해 주세요.",
);
tokens.push({
kind: word ? "word" : "symbol",
text: match[0],
position: start,
});
position += match[0].length;
}
tokens.push({ kind: "end", text: "", position });
return tokens;
}
/** Precedence: parentheses, NOT, AND, OR. Identifiers refer to QIDs. */
export function parseFilterExpression(source: string): ReportFilter | null {
const tokens = tokenize(source);
let cursor = 0;
const peek = () => tokens[cursor];
const take = (text: string) => {
const token = peek();
if (token.kind !== "value" && token.text.toUpperCase() === text) {
cursor++;
return true;
}
return false;
};
const expect = (text: string) => {
if (!take(text)) fail(peek().position, `${text} 토큰이 필요합니다.`);
};
const value = (): string | number => {
const token = peek();
if (token.kind !== "value")
return fail(
token.position,
"비교할 숫자 또는 따옴표로 감싼 문자열이 필요합니다.",
);
cursor++;
return token.value;
};
const group = (
operator: "AND" | "OR",
children: ReportFilter[],
): ReportFilter =>
children.length === 1 ? children[0] : { operator, children };
function condition(): ReportFilter {
const id = peek();
if (
id.kind !== "word" ||
/^(AND|OR|NOT|IN|BETWEEN|IS|NULL)$/i.test(id.text)
)
return fail(id.position, "비교할 문항 ID가 필요합니다.");
cursor++;
const base = { dimensionId: id.text, reference: "QID" as const };
if (take("IS")) {
const not = take("NOT");
expect("NULL");
return {
...base,
operator: not ? "IS_ANSWERED" : "IS_UNANSWERED",
values: [],
};
}
const not = take("NOT");
if (take("IN")) {
expect("(");
const values = [value()];
while (take(",")) {
if (values.length >= 128)
fail(peek().position, "IN 목록은 128개 이내로 작성해 주세요.");
values.push(value());
}
expect(")");
return { ...base, operator: not ? "NOT_IN" : "IN", values };
}
if (take("BETWEEN")) {
const low = value();
expect("AND");
const result: ReportFilter = {
...base,
operator: "BETWEEN",
values: [low, value()],
};
return not ? { operator: "NOT", children: [result] } : result;
}
if (not)
return fail(peek().position, "NOT 뒤에는 IN 또는 BETWEEN이 필요합니다.");
const token = peek();
const operators: Record<string, ReportFilter["operator"]> = {
"=": "EQ",
"!=": "NE",
"<>": "NE",
">": "GT",
">=": "GE",
"<": "LT",
"<=": "LE",
};
const operator =
token.kind === "symbol" ? operators[token.text] : undefined;
if (!operator)
return fail(
token.position,
"비교 연산자(=, !=, <>, >, >=, <, <=, IN 등)가 필요합니다.",
);
cursor++;
return { ...base, operator, values: [value()] };
}
function primary(depth: number): ReportFilter {
if (depth > 32)
return fail(peek().position, "괄호와 NOT은 32단계 이내로 작성해 주세요.");
if (take("NOT")) return { operator: "NOT", children: [primary(depth + 1)] };
if (!take("(")) return condition();
const result = expression(depth + 1);
expect(")");
return result;
}
function and(depth: number): ReportFilter {
const children = [primary(depth)];
while (take("AND")) {
if (children.length >= 128)
fail(
peek().position,
"AND 조건은 한 그룹에 128개 이내로 작성해 주세요.",
);
children.push(primary(depth));
}
return group("AND", children);
}
function expression(depth: number): ReportFilter {
const children = [and(depth)];
while (take("OR")) {
if (children.length >= 128)
fail(
peek().position,
"OR 조건은 한 그룹에 128개 이내로 작성해 주세요.",
);
children.push(and(depth));
}
return group("OR", children);
}
if (peek().kind === "end") return null;
const result = expression(0);
if (peek().kind !== "end")
fail(peek().position, "조건 사이의 AND·OR 또는 괄호를 확인해 주세요.");
return result;
}

View File

@@ -14,3 +14,13 @@ export async function createServerApi(authenticated = true) {
onResponseError: false,
});
}
/** Internal integrations authenticate with their supplied key, never the browser session. */
export function createServerApiWithApiKey(apiKey: string) {
return createHttpClient(serverEnv.API_SERVER, {
defaultHeaders: { "content-type": "application/json", "X-API-Key": apiKey },
onUnauthorized: false,
onForbidden: false,
onResponseError: false,
});
}

View File

@@ -0,0 +1,59 @@
import {
exportTarget,
isQuotaListPath,
isQuotaResultPath,
isReportStreamPath,
} from "@/lib/project-proxy-policy";
import { isRecord, validDateRange } from "@/types/kart";
import { readReportBatch } from "@/lib/report-contract";
import { parseFilterExpression } from "@/lib/filter-expression";
type Target = { path: string; kind: "list" | "quota" | "report" | "excel" };
/** Adapt integration input to the existing report contract without coupling the parser to HTTP. */
export function readInternalReportBatch(value: unknown) {
return readReportBatch(
isRecord(value) && typeof value.filter === "string"
? { ...value, filter: parseFilterExpression(value.filter) }
: value,
);
}
/** Only the five approved integration operations; no arbitrary upstream forwarding. */
export function internalTarget(method: string, slug: string[]): Target | null {
const [area, ...parts] = slug;
const path = "/" + slug.map(encodeURIComponent).join("/");
if (method === "GET" && area === "quota" && isQuotaListPath(parts))
return { path, kind: "list" };
if (method !== "POST") return null;
if (area === "project" && isReportStreamPath(parts))
return { path, kind: "report" };
if (area === "quota" && isQuotaResultPath(parts))
return { path, kind: "quota" };
if (
area === "export" &&
parts.length === 3 &&
["table", "quota"].includes(parts[2])
) {
const target = exportTarget("POST", parts);
if (target) return { path: target.path, kind: "excel" };
}
return null;
}
/** Broader backend quota contract, without changing the ordinary screen's request policy. */
export function readInternalQuotaRequest(value: unknown) {
if (!isRecord(value)) throw new Error("쿼터 조회 조건을 확인해 주세요.");
const dataScope = value.dataScope ?? "ACTUAL";
const startDate = value.startDate ?? "";
const endDate = value.endDate ?? "";
if (
!["ACTUAL", "TEST", "ALL"].includes(String(dataScope)) ||
typeof dataScope !== "string" ||
typeof startDate !== "string" ||
typeof endDate !== "string" ||
!validDateRange({ startDate, endDate })
)
throw new Error("쿼터 데이터 범위와 조회 날짜를 확인해 주세요.");
return { dataScope, ...(startDate ? { startDate, endDate } : {}) };
}