fix(security): KVE-2026-1914/1915/1919 remediation 전건

위임 관리자(부관리자)가 권한·역할·표현식·비밀 콘텐츠 경계를 우회하던
결함군을 계층 대칭성 원칙으로 전건 차단한다. 약한 경로가 정상 응답을
내보내는 것이 유일한 증상이라, 게이트를 생산 지점 한 곳(SSoT)에 두고
같은 데이터를 내보내는 소비 경로 전부가 그 게이트를 경유하도록 맞췄다.

- 등급 상한(rank ceiling): 슈퍼관리자 보호·역할/사용자 역할 배정(추가·제거
 대칭)·일괄 상태변경·순서변경을 상세 경로와 동일 강도로 재적용. 가드는
 DB 쓰기에 선행하여 거부 시 상태 불변.
- 레이아웃 표현식: new Function/with 실행을 AST 화이트리스트 평가기로 교체.
 비-문자열 computed 키 정규화(normalizeKey)·Object facade(리플렉션 static
 제거)·legacy 접근자 차단. 저장측 검증·정적 검사와 3계층 동형.
- secret 게이트: 비밀글의 댓글·첨부·문의 독립 경로 재적용, hash 파일서빙
 소유권·비밀·발행 상태 검사 통일.
- 신뢰 스크립트 호스트: 확장 선언 기반 + same-origin 브라우저 정규화를
 런타임·저장측·정적검사 3층 동형화.
- 회귀 감지: 단위·Feature·E2E·시나리오 매니페스트 전축 + audit 룰 4종 신설.
This commit is contained in:
HeuJung committed 2026-08-17 01:45:09 +09:00
1 parent cd84b63d2b
commit 71abdeaf60
249 files changed
+14354 -1134

No files matched your search

+131 -27
View File
@@ -11,6 +11,7 @@ import type { Route } from './routing/Router';
import { LayoutLoader, LayoutLoaderError } from './template-engine/LayoutLoader';
import type { InitActionDefinition, LayoutScript, ComputedSwitchDefinition } from './template-engine/LayoutLoader';
import { DataBindingEngine } from './template-engine/DataBindingEngine';
import { evaluateSafeExpression } from './template-engine/SafeExpressionEvaluator';
import { extractSingleBinding } from './template-engine/BindingShape';
import { hasPipes } from './template-engine/PipeRegistry';
import { evaluateRenderCondition } from './template-engine/helpers/RenderHelpers';
@@ -2039,6 +2040,17 @@ export class TemplateApp {
continue;
}
// 원격 스크립트 차단 (KVE-2026-1915 B-2 + 신뢰 출처 허용목록): src 는 same-origin
// path-only 이거나, 확장이 manifest 로 선언한 신뢰 호스트(G7Config.trustedScriptHosts)에
// 속한 외부 스크립트만 허용한다. 미선언 외부 origin(`//`·scheme 포함)은 원격 코드
// 로드 경로이므로 skip + 경고. (AuthManager.updateConfig loginPath same-origin 정책과 동형)
if (!this.isAllowedScriptSrc(script.src)) {
logger.warn(
`Blocked untrusted external script src (same-origin path or declared trusted host required): ${script.id} (${script.src})`
);
continue;
}
// 스크립트 동적 로드 (Promise로 래핑)
const loadPromise = new Promise<void>((resolve, reject) => {
const scriptEl = document.createElement('script');
@@ -2070,6 +2082,118 @@ export class TemplateApp {
}
}
/**
* 레이아웃 스크립트 src 가 로드 허용 대상인지 판정합니다
* (KVE-2026-1915 B-2 + 신뢰 출처 허용목록).
*
* 허용:
* 1. `/` 로 시작하는 same-origin 절대 경로.
* 2. 확장이 manifest(`trusted_script_hosts`)로 선언한 신뢰 호스트에 속한 외부 스크립트
* — 코어가 집계해 `window.G7Config.trustedScriptHosts` 로 노출한다. 예: CKEditor5
* (cdn.ckeditor.com), Daum 우편번호(t1.daumcdn.net).
* 차단: 그 외 `//`(protocol-relative)·scheme 포함 외부 origin(미선언 원격 코드 로드).
*
* @param src 스크립트 src 문자열
* @returns 로드 허용이면 true
*/
private isAllowedScriptSrc(src: string): boolean {
if (typeof src !== 'string') {
return false;
}
const trimmed = src.trim();
if (trimmed === '') {
return false;
}
// 접두 검사 전에 브라우저 URL 파서와 동일하게 정규화한다 (아래 메서드 주석 참조)
const normalized = TemplateApp.normalizeScriptSrcForOriginCheck(trimmed);
const isProtocolRelative = normalized.startsWith('//');
const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(normalized);
// same-origin path-only 절대 경로 (`/api/...`) — 항상 허용
if (!isProtocolRelative && !hasScheme && normalized.startsWith('/')) {
return true;
}
// 외부 origin — 확장이 선언한 신뢰 호스트만 허용
const host = this.extractScriptHost(normalized);
return host !== null && this.getTrustedScriptHosts().includes(host);
}
/**
* origin 판정 전에 스크립트 src 를 브라우저 URL 파서와 동일하게 정규화합니다.
*
* 문자열 접두 검사만으로는 authority 우회를 막지 못합니다. 브라우저(WHATWG URL)는
* 파싱 전에 ASCII tab·개행을 제거하고, special scheme(http/https)에서 백슬래시를
* 슬래시와 동등하게 처리하기 때문입니다. 그래서 `/\/evil.com/x.js` ·
* `/{tab}/evil.com/x.js` 는 `//` 로 시작하지 않고 scheme 도 없는데 실제로는
* `https://evil.com/x.js` 로 해석되어 원격 스크립트가 로드됩니다.
*
* 정규화 후 판정하면 경로 중간의 백슬래시·탭(`/js/a\b.js`)은 authority 를 만들지
* 않으므로 그대로 same-origin 으로 통과합니다(과차단 없음).
*
* 저장측 `SafeLayoutExpressions::normalizeForOriginCheck` · 정적 검사
* `layout-scripts-src-same-origin` 과 3층 동형이어야 합니다.
*
* @since engine-v1.60.2
* @param src 원본 src 문자열
* @returns 정규화된 src
*/
private static normalizeScriptSrcForOriginCheck(src: string): string {
// ASCII tab / LF / CR 제거 (브라우저 파서가 파싱 전에 제거하는 문자)
// → 백슬래시를 슬래시로 (special scheme 에서 등가)
const slashed = src.replace(/[\t\n\r]/g, '').replace(/\\/g, '/');
// 선행 슬래시가 3개 이상이어도 브라우저는 authority 시작으로 접는다
// (`///host/x` ≡ `//host/x`, `https:///host/x` ≡ `https://host/x`).
// 경로 중간의 연속 슬래시(`/js//a.js`)는 브라우저도 경로로 두므로 건드리지 않는다.
// @since engine-v1.60.3
return slashed.replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i, '$1//');
}
/**
* 스크립트 src 에서 http(s) 호스트명을 추출합니다.
*
* `//host/...`(protocol-relative)·`https://host/...` 를 처리하며, http/https 가 아닌
* scheme(`javascript:`·`data:` 등)은 null 을 반환해 신뢰 호스트 판정 대상에서 제외합니다.
*
* @param src 스크립트 src 문자열
* @returns 소문자 호스트명 (판정 불가 시 null)
*/
private extractScriptHost(src: string): string | null {
try {
const normalized = src.startsWith('//')
? `${window.location.protocol}${src}`
: src;
const url = new URL(normalized, window.location.origin);
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return null;
}
return url.hostname.toLowerCase();
} catch {
return null;
}
}
/**
* 코어가 집계해 노출한 신뢰 외부 스크립트 호스트 목록을 반환합니다.
*
* @returns 소문자 호스트명 배열 (window.G7Config.trustedScriptHosts)
*/
private getTrustedScriptHosts(): string[] {
const hosts = (window as any).G7Config?.trustedScriptHosts;
return Array.isArray(hosts)
? hosts.map((host: unknown) => String(host).toLowerCase())
: [];
}
/**
* 스크립트 조건 평가
*
@@ -2085,20 +2209,9 @@ export class TemplateApp {
if (condition.startsWith('{{') && condition.endsWith('}}')) {
const expression = condition.slice(2, -2).trim();
// 간단한 표현식 평가 (점 표기법, 옵셔널 체이닝, 메서드 호출)
// Function 생성자를 사용하여 안전하게 평가
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const fn = new Function('ctx', `
with(ctx) {
try {
return Boolean(${expression});
} catch (e) {
return false;
}
}
`);
return fn(context);
// 화이트리스트 AST 평가기로 안전하게 평가(KVE-2026-1915).
// 종전의 `new Function('ctx','with(ctx){return Boolean(...)}')` 폐기.
return Boolean(evaluateSafeExpression(expression, context));
}
// {{}} 형태가 아니면 truthy 체크
@@ -4060,19 +4173,10 @@ export class TemplateApp {
*/
private evaluateComputedExpression(expression: string, context: Record<string, any>): any {
try {
// 안전한 표현식 평가를 위해 with 문과 Function 생성자 사용
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const fn = new Function('ctx', `
with(ctx) {
try {
return ${expression};
} catch (e) {
return undefined;
}
}
`);
return fn(context);
// 화이트리스트 AST 평가기로 안전하게 평가한다(KVE-2026-1915).
// 종전의 `new Function('ctx', 'with(ctx){return ...}')` 는 필터조차 거치지 않아
// `''.constructor.constructor(...)` 샌드박스 탈출이 가능했으므로 폐기한다.
return evaluateSafeExpression(expression, context);
} catch (error) {
logger.warn(`Expression evaluation failed: ${expression}`, error);
return undefined;
@@ -7,6 +7,7 @@
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { evaluateSafeExpression } from '../template-engine/SafeExpressionEvaluator';
/**
* calculateComputed 함수 로직을 테스트하기 위한 헬퍼 함수
@@ -43,22 +44,17 @@ function calculateComputed(
/**
* evaluateComputedExpression 함수 로직
*
* TemplateApp.evaluateComputedExpression 과 동일하게 화이트리스트 AST
* 평가기(evaluateSafeExpression)에 위임한다. 폐기된
* `new Function('ctx','with(ctx){…}')` 사본을 로컬에 두면 실제 싱크(안전 평가기)를
* 검증하지 못하고, 엔진이 취약한 구현으로 회귀해도 이 테스트가 잡지 못한다
* (KVE-2026-1915). 그래서 사본을 제거하고 실제 평가기를 직접 호출한다.
*/
function evaluateComputedExpression(expression: string, context: Record<string, any>): any {
try {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const fn = new Function('ctx', `
with(ctx) {
try {
return ${expression};
} catch (e) {
return undefined;
}
}
`);
return fn(context);
} catch (error) {
return evaluateSafeExpression(expression, context);
} catch {
return undefined;
}
}
@@ -365,6 +361,35 @@ describe('Computed 기능', () => {
});
});
describe('보안 회귀 — computed 표현식 샌드박스 탈출 차단(KVE-2026-1915)', () => {
it("''.constructor.constructor 로 함수를 생성하려 하면 평가가 막혀 undefined 여야 함", () => {
expect(
evaluateComputedExpression("''.constructor.constructor('return 1')()", {})
).toBeUndefined();
});
it('__proto__ 접근은 차단되어 undefined 여야 함', () => {
expect(evaluateComputedExpression('({}).__proto__', {})).toBeUndefined();
});
it('prototype 접근은 차단되어 undefined 여야 함', () => {
expect(evaluateComputedExpression('[].constructor.prototype', {})).toBeUndefined();
});
it('전역 Function/eval 참조는 차단되어 undefined 여야 함', () => {
expect(evaluateComputedExpression("Function('return 1')()", {})).toBeUndefined();
expect(evaluateComputedExpression("eval('1')", {})).toBeUndefined();
});
it('calculateComputed 경로에서도 위험 토큰은 undefined 로 폴백되어야 함', () => {
const result = calculateComputed(
{ pwn: "{{''.constructor.constructor('return 2')()}}" },
{}
);
expect(result.pwn).toBeUndefined();
});
});
describe('LayoutLoader defines/computed 인터페이스', () => {
it('LayoutData 인터페이스에 defines 필드가 포함되어야 함', () => {
// TypeScript 인터페이스 검증을 위한 타입 테스트
@@ -0,0 +1,196 @@
/**
* TemplateApp 안전 평가기 경로 테스트 (KVE-2026-1915 B-2)
*
* computed(`evaluateComputedExpression`) 와 scripts[].if(`evaluateScriptCondition`)
* 두 싱크가 실제 TemplateApp 경로에서 화이트리스트 AST 평가기(evaluateSafeExpression)를
* 사용함을 검증한다. 종전의 `new Function('ctx','with(ctx){…}')` 로 회귀하면
* `''.constructor.constructor('return …')()` 가 값으로 평가되어 아래 단언이 깨진다.
*
* DefinesComputed.test.ts 는 평가기 자체(evaluateSafeExpression)를 직접 호출하지만,
* 이 파일은 실제 TemplateApp private 메서드를 거쳐 "엔진이 이 싱크에서 안전 평가기를
* 실제로 쓰는지" 를 고정한다.
*
* 효과 요약(마커 아님 — 평문): sandbox_escape_blocked, same_expression_same_value_across_paths.
* 실제 마커는 그 효과를 단언하는 개별 테스트에만 둔다 — 파일 레벨에 몰아 적으면 테스트를
* 전부 지워도 커버리지가 green 으로 남는다.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { TemplateApp } from '../TemplateApp';
import type { TemplateAppConfig } from '../TemplateApp';
import { AuthManager } from '../auth/AuthManager';
const mockApiClient = {
post: vi.fn().mockResolvedValue({}),
get: vi.fn().mockResolvedValue({}),
removeToken: vi.fn(),
setToken: vi.fn(),
getToken: vi.fn().mockReturnValue(null),
setOnUnauthorized: vi.fn(),
};
vi.mock('../api/ApiClient', () => ({
getApiClient: () => mockApiClient,
}));
const { sharedActionDispatcher } = vi.hoisted(() => ({
sharedActionDispatcher: {
setNavigate: vi.fn(),
setGlobalState: vi.fn(),
setDefaultContext: vi.fn(),
setGlobalStateUpdater: vi.fn(),
registerHandler: vi.fn(),
customHandlers: new Map(),
},
}));
vi.mock('../template-engine', () => ({
initTemplateEngine: vi.fn().mockResolvedValue(undefined),
renderTemplate: vi.fn().mockResolvedValue(undefined),
destroyTemplate: vi.fn(),
getActionDispatcher: vi.fn().mockReturnValue(sharedActionDispatcher),
getState: vi.fn().mockReturnValue({
actionDispatcher: sharedActionDispatcher,
reactRoot: null,
currentLayoutJson: null,
}),
}));
vi.mock('../template-engine/TransitionManager', () => ({
transitionManager: {
setPending: vi.fn(),
getIsPending: vi.fn(() => false),
subscribe: vi.fn(() => vi.fn()),
clearSubscribers: vi.fn(),
},
}));
vi.mock('../routing/Router', () => ({
Router: vi.fn(function (this: any) {
this.loadRoutes = vi.fn().mockResolvedValue(undefined);
this.on = vi.fn();
this.navigateToCurrentPath = vi.fn();
this.getRoutes = vi.fn().mockReturnValue([]);
}),
}));
vi.mock('../template-engine/LayoutLoader', async () => {
const actual = await vi.importActual<any>('../template-engine/LayoutLoader');
return {
...actual,
LayoutLoader: vi.fn(function (this: any) {
this.loadLayout = vi.fn().mockResolvedValue({ components: [] });
}),
};
});
vi.mock('../template-engine/ComponentRegistry', () => {
const mockInstance = {
loadComponents: vi.fn().mockResolvedValue(undefined),
getComponent: vi.fn().mockReturnValue(() => null),
hasComponent: vi.fn().mockReturnValue(true),
getInstance: vi.fn(),
};
mockInstance.getInstance.mockReturnValue(mockInstance);
return {
ComponentRegistry: {
getInstance: vi.fn(() => mockInstance),
},
};
});
describe('TemplateApp 안전 평가기 경로 (computed / scripts[].if)', () => {
let app: TemplateApp;
const build = (): TemplateApp => {
(window as any).G7Config = { trustedScriptHosts: [] };
const config: TemplateAppConfig = {
templateId: 'sirsoft-admin_basic',
templateType: 'admin',
locale: 'ko',
debug: false,
};
return new TemplateApp(config);
};
// computed 싱크: 이미 {{}} 가 제거된 내부 표현식을 받는다
const computed = (a: TemplateApp, expr: string, ctx: Record<string, any> = {}): any =>
(a as any).evaluateComputedExpression(expr, ctx);
// scripts[].if 싱크: {{...}} 형태의 조건을 받아 boolean 을 돌려준다
const condition = (a: TemplateApp, cond: string, ctx: Record<string, any> = {}): boolean =>
(a as any).evaluateScriptCondition(cond, ctx);
beforeEach(() => {
document.body.innerHTML = '<div id="app"></div>';
Object.defineProperty(window, 'location', {
value: {
href: '',
origin: 'https://g7.test',
protocol: 'https:',
pathname: '/',
search: '',
},
writable: true,
configurable: true,
});
(AuthManager as any).instance = undefined;
(window as any).G7Core = { devTools: { trackAuthEvent: vi.fn() } };
vi.clearAllMocks();
app = build();
});
afterEach(() => {
delete (window as any).G7Core;
delete (window as any).G7Config;
});
describe('computed 정상 평가', () => {
/** @effects same_expression_same_value_across_paths */
it('속성 접근/산술/삼항/옵셔널 체이닝을 평가한다', () => {
expect(computed(app, 'user.name', { user: { name: '홍길동' } })).toBe('홍길동');
expect(computed(app, 'price * qty', { price: 1000, qty: 3 })).toBe(3000);
expect(computed(app, "role === 'admin' ? 'Y' : 'N'", { role: 'admin' })).toBe('Y');
expect(computed(app, "user?.profile?.name ?? '없음'", { user: { profile: null } })).toBe('없음');
});
});
describe('computed 보안 회귀 — 샌드박스 탈출 차단', () => {
/** @effects sandbox_escape_blocked */
it("''.constructor.constructor 함수 생성은 undefined 로 막힌다", () => {
expect(computed(app, "''.constructor.constructor('return 1')()")).toBeUndefined();
});
/** @effects sandbox_escape_blocked */
it('전역 Function/eval 참조는 undefined 로 막힌다', () => {
expect(computed(app, "Function('return 1')()")).toBeUndefined();
expect(computed(app, "eval('1')")).toBeUndefined();
});
/** @effects sandbox_escape_blocked */
it('__proto__/prototype 접근은 undefined 로 막힌다', () => {
expect(computed(app, '({}).__proto__')).toBeUndefined();
expect(computed(app, '[].constructor.prototype')).toBeUndefined();
});
});
describe('scripts[].if 정상 평가', () => {
/** @effects same_expression_same_value_across_paths */
it('{{...}} 조건을 boolean 으로 평가한다', () => {
expect(condition(app, '{{_global.on}}', { _global: { on: true } })).toBe(true);
expect(condition(app, '{{_global.on}}', { _global: { on: false } })).toBe(false);
expect(condition(app, "{{status === 'active'}}", { status: 'active' })).toBe(true);
});
});
describe('scripts[].if 보안 회귀 — 샌드박스 탈출 차단', () => {
/** @effects sandbox_escape_blocked */
it("''.constructor.constructor 조건은 false 로 막힌다", () => {
expect(condition(app, "{{''.constructor.constructor('return true')()}}")).toBe(false);
});
/** @effects sandbox_escape_blocked */
it('전역 Function 참조 조건은 false 로 막힌다', () => {
expect(condition(app, "{{Function('return true')()}}")).toBe(false);
});
});
});
@@ -0,0 +1,256 @@
/**
* TemplateApp.isAllowedScriptSrc 테스트 (KVE-2026-1915 B-2 + 신뢰 출처 허용목록)
*
* 배포 번들에서는 minify 로 이 함수를 이름으로 호출할 수 없어 E2E 는 결과(네트워크에
* 허용목록 밖 스크립트가 없음)만 관찰한다. 결정 로직 자체는 여기서 잠근다.
*
* 효과 요약(마커 아님 — 평문): trusted_script_host_allowlist_wired,
* untrusted_external_script_blocked. 실제 마커는 그 효과를 단언하는 개별 테스트에만 둔다 —
* 파일 레벨에 몰아 적으면 테스트를 전부 지워도 커버리지가 green 으로 남는다.
*
* 레이아웃 `scripts[].src` 로더는 same-origin path 이거나, 확장이 manifest 로 선언해
* 코어가 `window.G7Config.trustedScriptHosts` 로 노출한 신뢰 호스트에 속한 외부 스크립트만
* 로드한다. 그 외 외부 origin(미선언 원격 코드)은 차단한다.
*
* 회귀 배경: 초기 B-2 는 모든 외부 origin 을 무조건 차단해 CKEditor5(cdn.ckeditor.com)·
* Daum 우편번호(t1.daumcdn.net) 등 번들 확장의 CDN 스크립트까지 막아 기능이 깨졌다.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { TemplateApp } from '../TemplateApp';
import type { TemplateAppConfig } from '../TemplateApp';
import { AuthManager } from '../auth/AuthManager';
const mockApiClient = {
post: vi.fn().mockResolvedValue({}),
get: vi.fn().mockResolvedValue({}),
removeToken: vi.fn(),
setToken: vi.fn(),
getToken: vi.fn().mockReturnValue(null),
setOnUnauthorized: vi.fn(),
};
vi.mock('../api/ApiClient', () => ({
getApiClient: () => mockApiClient,
}));
const { sharedActionDispatcher } = vi.hoisted(() => ({
sharedActionDispatcher: {
setNavigate: vi.fn(),
setGlobalState: vi.fn(),
setDefaultContext: vi.fn(),
setGlobalStateUpdater: vi.fn(),
registerHandler: vi.fn(),
customHandlers: new Map(),
},
}));
vi.mock('../template-engine', () => ({
initTemplateEngine: vi.fn().mockResolvedValue(undefined),
renderTemplate: vi.fn().mockResolvedValue(undefined),
destroyTemplate: vi.fn(),
getActionDispatcher: vi.fn().mockReturnValue(sharedActionDispatcher),
getState: vi.fn().mockReturnValue({
actionDispatcher: sharedActionDispatcher,
reactRoot: null,
currentLayoutJson: null,
}),
}));
vi.mock('../template-engine/TransitionManager', () => ({
transitionManager: {
setPending: vi.fn(),
getIsPending: vi.fn(() => false),
subscribe: vi.fn(() => vi.fn()),
clearSubscribers: vi.fn(),
},
}));
vi.mock('../routing/Router', () => ({
Router: vi.fn(function (this: any) {
this.loadRoutes = vi.fn().mockResolvedValue(undefined);
this.on = vi.fn();
this.navigateToCurrentPath = vi.fn();
this.getRoutes = vi.fn().mockReturnValue([]);
}),
}));
vi.mock('../template-engine/LayoutLoader', async () => {
const actual = await vi.importActual<any>('../template-engine/LayoutLoader');
return {
...actual,
LayoutLoader: vi.fn(function (this: any) {
this.loadLayout = vi.fn().mockResolvedValue({ components: [] });
}),
};
});
vi.mock('../template-engine/ComponentRegistry', () => {
const mockInstance = {
loadComponents: vi.fn().mockResolvedValue(undefined),
getComponent: vi.fn().mockReturnValue(() => null),
hasComponent: vi.fn().mockReturnValue(true),
getInstance: vi.fn(),
};
mockInstance.getInstance.mockReturnValue(mockInstance);
return {
ComponentRegistry: {
getInstance: vi.fn(() => mockInstance),
},
};
});
describe('TemplateApp.isAllowedScriptSrc (신뢰 출처 허용목록)', () => {
let app: TemplateApp;
const build = (trustedScriptHosts: string[] = []): TemplateApp => {
(window as any).G7Config = { trustedScriptHosts };
const config: TemplateAppConfig = {
templateId: 'sirsoft-admin_basic',
templateType: 'admin',
locale: 'ko',
debug: false,
};
return new TemplateApp(config);
};
const allowed = (a: TemplateApp, src: string): boolean =>
(a as any).isAllowedScriptSrc(src);
beforeEach(() => {
document.body.innerHTML = '<div id="app"></div>';
Object.defineProperty(window, 'location', {
value: {
href: '',
origin: 'https://g7.test',
protocol: 'https:',
pathname: '/',
search: '',
},
writable: true,
configurable: true,
});
(AuthManager as any).instance = undefined;
(window as any).G7Core = { devTools: { trackAuthEvent: vi.fn() } };
vi.clearAllMocks();
});
afterEach(() => {
delete (window as any).G7Core;
delete (window as any).G7Config;
});
/** @effects trusted_script_host_allowlist_wired */
it('same-origin 절대 경로는 항상 허용된다', () => {
app = build([]);
expect(allowed(app, '/api/modules/x/widget.js')).toBe(true);
});
/** @effects untrusted_external_script_blocked */
it('신뢰 목록이 비면 외부 origin 스크립트는 차단된다', () => {
app = build([]);
expect(allowed(app, 'https://cdn.ckeditor.com/ckeditor5/x.js')).toBe(false);
});
/** @effects trusted_script_host_allowlist_wired */
it('선언된 신뢰 호스트의 scheme URL 스크립트는 허용된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.umd.js')).toBe(true);
});
/** @effects trusted_script_host_allowlist_wired */
it('선언된 신뢰 호스트의 protocol-relative 스크립트도 허용된다', () => {
app = build(['t1.daumcdn.net']);
expect(allowed(app, '//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js')).toBe(true);
});
/** @effects untrusted_external_script_blocked */
it('신뢰 목록에 없는 외부 호스트는 선언 여부와 무관하게 차단된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, 'https://evil.com/x.js')).toBe(false);
expect(allowed(app, '//evil.com/x.js')).toBe(false);
});
/** @effects trusted_script_host_allowlist_wired */
it('호스트 대소문자는 정규화되어 매칭된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, 'https://CDN.CKEditor.COM/x.js')).toBe(true);
});
/** @effects untrusted_external_script_blocked */
it('javascript:·data: 등 비 http(s) scheme 은 신뢰 호스트여도 차단된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, 'javascript:alert(1)')).toBe(false);
expect(allowed(app, 'data:text/javascript,alert(1)')).toBe(false);
});
/** @effects untrusted_external_script_blocked */
it('빈 문자열·공백은 차단된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, '')).toBe(false);
expect(allowed(app, ' ')).toBe(false);
});
// ==========================================
// authority 우회 (KVE-2026-1915 후속)
// ==========================================
//
// 브라우저 URL 파서는 (a) 파싱 전에 ASCII tab·개행을 제거하고 (b) special scheme 에서
// 백슬래시를 슬래시와 동등하게 처리한다. 따라서 아래 형태들은 `//` 로 시작하지 않고
// scheme 도 없으며 `/` 로 시작하지만, 실제로는 외부 origin 으로 해석되어 원격 스크립트가
// 로드된다. 접두 문자열 검사만으로는 막을 수 없다.
//
// 실측(node `new URL(src, 'https://g7.test/')`): 6형태 전부 origin `https://evil.com`.
const BS = String.fromCharCode(92);
const TAB = String.fromCharCode(9);
const LF = String.fromCharCode(10);
const CR = String.fromCharCode(13);
it.each([
['슬래시-백슬래시-슬래시', '/' + BS + '/evil.com/x.js'],
['슬래시-백슬래시', '/' + BS + 'evil.com/x.js'],
['슬래시-이중백슬래시', '/' + BS + BS + 'evil.com/x.js'],
['슬래시-탭-슬래시', '/' + TAB + '/evil.com/x.js'],
['슬래시-LF-슬래시', '/' + LF + '/evil.com/x.js'],
['슬래시-CR-슬래시', '/' + CR + '/evil.com/x.js'],
])('authority 우회(%s)는 차단된다', (_name, src) => {
app = build([]);
expect(allowed(app, src)).toBe(false);
});
/** @effects trusted_script_host_allowlist_wired, untrusted_external_script_blocked */
it('authority 우회로 도달한 호스트는 신뢰 목록에 있어야만 허용된다', () => {
// 정규화 후 호스트가 추출되므로, 신뢰 선언된 호스트면 허용·아니면 차단 (브라우저 해석과 일치)
app = build(['cdn.ckeditor.com']);
expect(allowed(app, '/' + BS + '/evil.com/x.js')).toBe(false);
expect(allowed(app, '/' + BS + '/cdn.ckeditor.com/x.js')).toBe(true);
});
/** @effects trusted_script_host_allowlist_wired */
it('경로 중간의 백슬래시·탭은 authority 를 만들지 않으므로 허용된다', () => {
// 과차단 회귀 방지 — 브라우저도 same-origin 으로 해석한다(실측)
app = build([]);
expect(allowed(app, '/js/a' + BS + 'b.js')).toBe(true);
expect(allowed(app, '/js/c' + TAB + 'd.js')).toBe(true);
});
// 신뢰 호스트를 userinfo 로 위장하는 형태. 백슬래시가 슬래시로 접히면서
// `https://evil.com/@cdn.ckeditor.com/x.js` 가 되어 실제 출처는 evil.com 이다.
// 저장측(TrustedScriptHosts::hostOf)이 정규화 없이 parse_url 로 읽으면 이 형태의
// 호스트를 `cdn.ckeditor.com` 으로 보게 되므로, 세 계층이 같은 판정을 내는지 고정한다.
/** @effects untrusted_external_script_blocked */
it('신뢰 호스트를 userinfo 로 위장한 src 는 차단된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, 'https://evil.com' + BS + '@cdn.ckeditor.com/x.js')).toBe(false);
expect(allowed(app, '//evil.com' + BS + '@cdn.ckeditor.com/x.js')).toBe(false);
});
// 브라우저는 선행 슬래시 런을 authority 시작으로 접는다(`///host` ≡ `//host`).
// 정규화가 이를 접지 않으면 런타임만 host 를 뽑고 저장측·정적검사는 못 뽑는 갈림이 생긴다.
/** @effects untrusted_external_script_blocked */
it('선행 슬래시가 3개 이상이어도 authority 로 해석된다', () => {
app = build(['cdn.ckeditor.com']);
expect(allowed(app, '///cdn.ckeditor.com/x.js')).toBe(true);
expect(allowed(app, '///evil.com/x.js')).toBe(false);
});
});
@@ -5,6 +5,78 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.60.4] - 2026-08-14
### Security
#### legacy 접근자를 통한 프로토타입 도달 차단
- `Object` facade 에서 `getPrototypeOf`/`setPrototypeOf`/`defineProperty` 를 제거했지만, 같은 능력을 **모든 객체가 상속으로 제공하는** `__lookupGetter__`/`__lookupSetter__`/`__defineGetter__`/`__defineSetter__` 로 되찾을 수 있었다. 이 4종은 프로퍼티를 **키가 아니라 문자열 인자**로 지목하므로 키 정규화(`normalizeKey`)를 원리상 거치지 않는다. 네 이름을 금지 프로퍼티에 추가해 dot·computed·문자열 조립 형태를 한꺼번에 막았다.
- 임의 코드 실행(RCE)으로는 이어지지 않았다 — `Function`/`eval` 도달은 여전히 `constructor` 키를 요구하고 그 경로는 이미 차단되어 있었다. 막은 것은 **페이지 전역 프로토타입 오염과 빌트인 메서드 변조/삭제로 인한 전역 장애**다.
- `Object.assign` 이 source 의 `__proto__` 키로 대상의 프로토타입을 바꾸던 경로도 닫았다. 네이티브 `assign` 은 대입(`[[Set]]`) 이라 `JSON.parse('{"__proto__":…}')` 결과를 합칠 때 setter 가 깨어났다 — 이제 항상 own 데이터 프로퍼티로 정의하며, 금지 키는 복사하지 않고 거부한다.
- 저장측 검증과 정적 검사에도 같은 패턴을 넣어 세 계층을 맞췄다. 배포 레이아웃 전수에서 이 4개 이름 사용은 0건이라 정상 표현식이 막히는 회귀는 없다(`toLocaleString`·`Object.assign`·`Object.create` 정당 사용은 그대로 동작).
## [engine-v1.60.3] - 2026-08-14
### Security
#### 선행 슬래시 런도 authority 로 접어 판정 (engine-v1.60.2 후속)
- v1.60.2 의 정규화는 백슬래시를 슬래시로 바꾸기만 해서, `/\/host/x.js` 가 정규화 후 슬래시 3개(`///host/x.js`)가 됐다. 브라우저는 선행 슬래시가 몇 개든 authority 시작으로 접으므로(`///host` ≡ `//host`, `https:///host` ≡ `https://host`) 이 형태도 외부 호스트에서 로드된다. 정규화에 **선행 슬래시 런 접기**를 추가해 런타임·저장측·정적 검사 세 계층이 같은 호스트를 보도록 맞췄다.
- 경로 중간의 연속 슬래시(`/js//a.js`)는 브라우저도 경로로 두므로 건드리지 않는다(과차단 없음).
- 이 형태의 실질 영향은 저장측이었다 — 런타임은 `new URL` 로 호스트를 뽑아 이미 올바르게 판정하고 있었고, 저장측 신뢰 호스트 추출만 갈려 있었다(코어 `TrustedScriptHosts` 수정분 참조).
## [engine-v1.60.2] - 2026-08-14
### Security
#### `scripts[].src` same-origin 판정의 authority 우회 차단 (KVE-2026-1915 B-2 후속)
- 원격 스크립트 차단이 `//` 접두·scheme 존재·`/` 시작이라는 **문자열 접두 검사**로만 same-origin 을 판정했다. 그런데 브라우저 URL 파서는 (a) 파싱 전에 ASCII tab·개행을 제거하고 (b) http/https 에서 백슬래시를 슬래시와 동등하게 처리하므로, `/\/evil.com/x.js` · `/\evil.com/x.js` · `/{tab}/evil.com/x.js` 같은 형태가 검사를 통과한 뒤 실제로는 `https://evil.com/x.js` 로 해석되어 **선언되지 않은 외부 스크립트가 그대로 로드**됐다(실측: `new URL` 로 6형태 전부 외부 origin 해석).
- 판정 전에 브라우저와 동일하게 정규화(tab·LF·CR 제거 → 백슬래시를 슬래시로)한 뒤 접두 검사를 적용하도록 고쳤다. 경로 중간의 백슬래시·탭(`/js/a\b.js`)은 authority 를 만들지 않으므로 종전대로 same-origin 으로 통과한다(과차단 없음).
- 저장측(`SafeLayoutExpressions`·`NoExternalUrls`)과 정적 검사(`layout-scripts-src-same-origin`)도 동일 정규화를 공유한다 — 세 계층이 같은 판정 로직을 쓰고 있었으므로 한 형태로 셋이 함께 뚫려 있었다.
#### 화이트리스트 전역의 `Object.assign`/`freeze` 변조 차단
- `delete` 는 화이트리스트 전역(`Math`/`JSON`/`Date` 등)을 identity 로 차단하는데, facade 에 남긴 `assign`/`freeze` 는 대상을 검사하지 않아 `Object.assign(Math, { floor: … })` 로 **공유 전역을 영구 변조**할 수 있었다. 화이트리스트 전역은 실제 전역 참조를 노출하므로 그 변조는 페이지 전체(엔진·모듈·플러그인)에 지속된다. 두 메서드에도 `delete` 와 동일한 대상 검사를 적용했다. 일반 객체 대상 `assign`/`freeze` 는 그대로 동작한다.
## [engine-v1.60.1] - 2026-08-14
### Security
#### 화이트리스트 평가기의 비-문자열 computed 키 · Object 리플렉션 static 을 통한 샌드박스 탈출 차단 (KVE-2026-1915)
- `SafeExpressionEvaluator` 의 프로퍼티 접근 하드닝이 **문자열 키만** 검사해, 배열/객체 키가 `''[['constructor']][['constructor']]('code')()` 처럼 JS ToPropertyKey 강제변환으로 `constructor` 에 도달하던 탈출을 막지 못했다. 키를 접근 전에 **1회 정규화**(심볼 외 `String()` 강제변환)한 뒤 금지 프로퍼티(`constructor`/`__proto__`/`prototype`)를 차단하고 그 정규화된 원시 키로만 접근하도록 고쳤다 — 배열·중첩 배열·객체 `toString` 강제변환·문자열 조립 등 모든 우회 형태가 접근 시점에 거부되며 재변환(TOCTOU) 여지도 없다. `evalMember`/`evalCall`/`delete` 세 경로 모두 적용.
- 화이트리스트 전역 `Object` 를 네이티브 그대로 노출해 `Object.getOwnPropertyDescriptor(Object.getPrototypeOf(String), 'constructor').value` 로 Function 에 도달하거나 `Object.setPrototypeOf`/`defineProperty` 로 프로토타입을 오염시킬 수 있었다. 이 static 들은 프로퍼티 키가 아니라 **문자열 인자**로 프로퍼티를 지목하므로 키 정규화로는 잡히지 않는다. 리플렉션·프로토타입·디스크립터 계열 static 을 제거하고 순수 데이터 계열(`keys`/`values`/`entries`/`assign`/`fromEntries`/`create`/`freeze`/`isFrozen`)만 노출하는 facade 로 교체했다. `create` 는 프로토타입/디스크립터를 읽지도 쓰지도 않아(신규 객체 생성만) 탈출 벡터가 아니며, 레이아웃이 `Object.assign(Object.create(null), …)` 로 정당하게 사용한다.
- 저장측(`app/Rules/SafeLayoutExpressions.php`)·정적 검사(`layout-expression-dangerous-token`)도 동형으로 넓혔다: 금지 프로퍼티 이름의 따옴표 문자열을 위치 무관 차단(computed 키 `['constructor']`·중첩 배열 키 `[['constructor']]`·리플렉션 문자열 인자 `…, 'constructor')` 포함), Object 리플렉션 static 이름 차단. 문자열 조립 난독화(`['const' + 'ructor']`)는 정적 토큰 매칭이 불가능하므로 런타임 인터프리터가 최종 게이트다.
## [engine-v1.60.0] - 2026-08-14
### Fixed
#### 표현식 평가기가 statement 본문(IIFE)을 거부해 저장이 원문 문자열로 전송되던 회귀 (KVE-2026-1915 후속)
- engine-v1.59.0 에서 `new Function` → `SafeExpressionEvaluator`(AST 인터프리터)로 교체하며, 기존 30개 레이아웃이 쓰던 `(function() { const …; if (…) return {…}; })()` / `(() => { … })()` 형태의 **statement 본문 IIFE** 를 파싱 단계에서 거부하게 됐다. `DataBindingEngine.resolveBindings` 는 평가 실패 시 원본 문자열을 그대로 돌려주므로, 이 식을 body 로 쓰던 저장 액션은 미해석 `{{…}}` 문자열을 서버로 전송했고 서버는 아무것도 저장하지 못한 채 성공(200)을 반환했다. 발현: 이커머스 설정에서 문의 게시판을 지정해도 저장되지 않고, 게시판/관리자 설정 저장, 카테고리 부모 선택 옵션, 배송비 단위 표기 등 동일 형태를 쓰던 화면이 조용히 동작하지 않았다(예외·경고 없음).
- `SafeExpressionEvaluator` 에 함수/화살표 **블록 본문 해석**을 추가했다: 함수 표현식(`function (…) { … }`, 명명 함수 재귀 포함)·화살표 블록 본문·`const`/`let` 선언·`if`/`else`·`for…of`(+`break`/`continue`)·`return`·`try`/`catch`/`finally`·`delete`·기본 파라미터. 모두 인터프리터가 트리워킹으로 실행하며 코드 문자열 컴파일(`eval`/`new Function`)은 여전히 쓰지 않는다.
- 보안 경계는 그대로다 — KVE-2026-1915 의 탈출 벡터는 "function 키워드" 자체가 아니라 `''.constructor.constructor('code')()` 같은 **프로퍼티 체인을 통한 Function 생성자 접근**이었고, 그 차단(`constructor`/`__proto__`/`prototype` 접근, `Function`/`eval`/`Reflect` 등 위험 전역, 비화이트리스트 `new`)은 statement 본문 안에서도 동일하게 적용된다. 함수 표현식은 네이티브 컴파일이 아니라 해석기 클로저로만 실행되므로 새 탈출 경로가 생기지 않는다. 추가로 `delete` 는 화이트리스트 전역 객체(`Math`/`JSON`/`Array` 등)의 프로퍼티를 지우지 못하도록 identity 로 차단한다. 대입(`=`)·증감(`++`/`--`)·복합대입·sequence(`,`)·비트/시프트/거듭제곱 연산자는 계속 거부한다.
## [engine-v1.59.0] - 2026-08-13
### Security
#### 레이아웃 표현식 평가를 화이트리스트 AST 인터프리터로 교체 (KVE-2026-1915)
- 신규 `SafeExpressionEvaluator.ts` — 표현식 문자열을 토크나이저 → Pratt 파서 → AST 트리워킹 인터프리터로 해석한다. `eval` / `new Function` / `with(ctx)` 를 일절 쓰지 않으므로 `''.constructor.constructor('code')()` 형태의 샌드박스 탈출(CWE-184/CWE-94)이 원천 차단된다.
- 위험 지점 3곳을 이 평가기로 통일했다: `DataBindingEngine.evaluateExpression`(주 평가 경로, `TranslationEngine` 의 `$t:` 파라미터 평가 포함 200여 소비처), `TemplateApp.evaluateComputedExpression`(computed), `TemplateApp.evaluateScriptCondition`(scripts[].if). 종전 `evaluateComputedExpression`/`evaluateScriptCondition` 은 `with(ctx)` 로 필터조차 거치지 않아 더 위험했다.
- 차단: `constructor`/`__proto__`/`prototype` 프로퍼티 접근(dot·문자열 리터럴 computed·런타임 해석된 computed 키 모두), `Function`/`eval`/`globalThis`/`window`/`Reflect`/`Proxy` 등 위험 전역, 함수 생성(`function` 키워드), 할당·증감, 비트/시프트/거듭제곱 연산자.
- 호환 유지: 화살표 함수(인터프리터 클로저로 실행), 스프레드(배열/객체/호출인자), optional chaining, 템플릿 리터럴(`${}` 은 같은 인터프리터로 해석), 화이트리스트 생성자의 `new`(`new Date(...)`·`Array.from(new Set(...))` 등 — `Date`/`Set`/`Map`/`WeakSet`/`WeakMap`/`Array` 등만 허용, `new Function` 은 차단), 화이트리스트 전역(`Math`/`JSON`/`Date`/`Array`/`Object`/`Number`/`String`/`Boolean`/`parseInt`/`parseFloat`/`isNaN`/`isFinite`) 및 인스턴스 메서드 호출.
- 컨텍스트 값이 항상 전역보다 우선한다. 미존재 식별자는 `with(ctx)` 시맨틱대로 `undefined` 를 반환한다(예외 없음).
#### `scripts[].src` 원격 스크립트 차단 + 신뢰 출처 허용목록 (KVE-2026-1915 B-2)
- `TemplateApp.loadLayoutScripts` — 레이아웃 스크립트 `src` 는 same-origin path-only(`/` 시작)만 로드한다. `//`(protocol-relative)·scheme 포함 절대 URL(외부 origin)은 skip + 경고로 원격 코드 로드를 차단한다.
- 예외: 확장이 manifest(`trusted_script_hosts`)로 선언해 코어가 `window.G7Config.trustedScriptHosts` 로 노출한 신뢰 호스트의 외부 스크립트는 허용한다(`isAllowedScriptSrc`). CKEditor5(cdn.ckeditor.com)·Daum 우편번호(t1.daumcdn.net) 등 번들 확장의 CDN 스크립트가 정상 로드되도록 하되, 편집기 저장분에 임의 원격 스크립트를 넣는 경로는 여전히 차단한다. (신뢰 경계: 미선언 외부 origin 은 항상 skip)
## [engine-v1.58.4] - 2026-08-14
### Fixed
@@ -13,6 +13,7 @@ import { TranslationEngine } from './TranslationEngine';
import { hasPipes, splitPipes, executePipeChain } from './PipeRegistry';
import { classifyExpression, extractSingleBinding, isComplexExpression, LITERALS, scanBindings } from './BindingShape';
import { RAW_PREFIX, wrapRaw, wrapRawDeep } from './rawMarkers';
import { evaluateSafeExpression } from './SafeExpressionEvaluator';
import type { G7DevToolsInterface } from './G7CoreGlobals';
const logger = createLogger('DataBindingEngine');
@@ -20,20 +21,9 @@ const logger = createLogger('DataBindingEngine');
/**
* 함수 파라미터 이름으로 쓸 수 있는 식별자 패턴.
*
* 표현식 평가는 컨텍스트 키를 `new Function` 의 파라미터로 넘긴다. 파라미터가 될 수 없는
* 이름이 하나라도 섞이면 함수 생성이 통째로 실패하므로 미리 걸러낸다.
* 표현식 평가는 화이트리스트 AST 평가기(SafeExpressionEvaluator)가 담당한다 —
* 컨텍스트를 직접 스코프로 삼아 인터프리터로 해석하므로 `new Function` 이 필요 없다.
*/
const VALID_IDENTIFIER_PATTERN = /^[$A-Za-z_][$A-Za-z0-9_]*$/;
/** 파라미터 이름으로 쓸 수 없는 예약어 (엄격 모드 예약어 포함) */
const RESERVED_WORDS = new Set([
'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default',
'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for',
'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let',
'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static',
'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void',
'while', 'with', 'yield', 'arguments', 'eval',
]);
/**
* G7Core.devTools 인터페이스 가져오기
@@ -189,15 +179,6 @@ export class DataBindingEngine {
*/
private cache: Map<string, CacheEntry> = new Map();
/**
* 표현식 함수 캐시
*
* key: 전처리된 표현식, value: 컴파일된 Function
* - Function 생성자 비용이 높으므로 동일 표현식 재사용 시 캐시에서 조회
* - 표현식 자체만 캐싱하고, 컨텍스트 값은 실행 시 전달
*/
private expressionFnCache: Map<string, Function> = new Map();
/**
* 렌더 사이클 캐시
*
@@ -1137,11 +1118,10 @@ export class DataBindingEngine {
/**
* 캐시 초기화
*
* 바인딩 값 캐시와 표현식 함수 캐시를 모두 초기화합니다.
* 바인딩 값 캐시를 초기화합니다.
*/
public clearCache(): void {
this.cache.clear();
this.expressionFnCache.clear();
}
/**
@@ -1383,45 +1363,15 @@ export class DataBindingEngine {
return current ?? fallback;
};
// 확장된 컨텍스트의 키를 변수로 사용할 수 있도록 준비.
//
// 함수 파라미터가 될 수 없는 키(`sales_status[]`, `data-id`, 예약어 등)는 제외한다.
// 하나라도 섞이면 `new Function` 생성 자체가 SyntaxError 로 실패해 **그 컨텍스트에서
// 평가되는 모든 표현식**이 통째로 죽는다 — 식이 그 키를 쓰지 않아도 마찬가지다.
// 예외도 화면 오류도 없이 값만 사라지므로(catch → 폴백) 원인 파악이 어렵다.
//
// 제외해도 잃는 것은 없다 — 그런 키는 애초에 식 안에서 맨이름으로 참조할 수 없었고
// (`sales_status[]` 는 식별자가 아니다), 실제 작성은 `query['sales_status[]']` 처럼
// 상위 객체를 거치므로 그대로 동작한다.
// @since engine-v1.56.2
const contextKeys: string[] = [];
const contextValues: unknown[] = [];
for (const [key, value] of Object.entries(extendedContext)) {
if (!VALID_IDENTIFIER_PATTERN.test(key) || RESERVED_WORDS.has(key)) {
continue;
}
contextKeys.push(key);
contextValues.push(value);
}
// 캐시 키 생성: 전처리된 표현식 + 컨텍스트 키 조합
// 같은 표현식이라도 컨텍스트 키가 다르면 다른 함수가 필요
const cacheKey = `${processedExpr}|${contextKeys.join(',')}`;
// 캐시된 함수 조회 또는 새로 생성
let evaluator = this.expressionFnCache.get(cacheKey);
const fromCache = !!evaluator;
if (!evaluator) {
// Function 생성자를 사용하여 표현식 평가
// 예: expr = "!_global.sidebarOpen"
// contextKeys = ["_global", "user", ...]
// contextValues = [{sidebarOpen: false}, {...}, ...]
// eslint-disable-next-line no-new-func
evaluator = new Function(...contextKeys, `return (${processedExpr});`);
this.expressionFnCache.set(cacheKey, evaluator);
}
const result = evaluator(...contextValues);
// 표현식은 화이트리스트 AST 평가기로 안전하게 실행한다(KVE-2026-1915).
// `new Function(...)` / `with(ctx)` 기반 평가는 `''.constructor.constructor(...)`
// 형태의 샌드박스 탈출을 허용했으므로 폐기하고, evaluateSafeExpression 이 컨텍스트를
// 직접 스코프로 삼아 식을 인터프리터로 해석한다. 컨텍스트 키를 함수 파라미터로
// 만들지 않으므로 `sales_status[]` 같은 비-식별자 키가 섞여도 평가가 죽지 않는다
// (그런 키는 `query['sales_status[]']` 로 상위 객체를 거쳐 그대로 접근된다).
// @since engine-v1.59.0
const fromCache = false;
const result = evaluateSafeExpression(processedExpr, extendedContext);
// DevTools: 표현식 평가 추적
if (devTools?.isEnabled()) {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,76 @@
/**
* 조건 표현식 샌드박스 단위 테스트 (KVE-2026-1915)
*
* `layout-expression-sandbox.spec.ts`(Playwright) 가 배포 번들의 공개 API
* `G7Core.evaluateCondition` 로 잠그는 `window.__g7jsi` canary 축을, 그 API 가 실제로
* 호출하는 함수 `evaluateStringCondition` 을 통해 단위 레벨에서 고정한다. E2E 미실행
* 환경에서도 "위험 표현식은 코드를 실행하지 못한다(전역 canary 미설정)" 축이 검증된다.
*
* scripts[].if / if / classMap 등 레이아웃 조건은 전부 이 함수를 경유하므로, 이 canary 가
* 설정되면 렌더 경로 어디서든 샌드박스가 뚫린 것이다.
*
* 효과 요약(마커 아님 — 평문): sandbox_escape_blocked, dangerous_payload_does_not_set_global.
* 실제 마커는 그 효과를 단언하는 개별 테스트에만 둔다 — 파일 레벨에 몰아 적으면 테스트를
* 전부 지워도 커버리지가 green 으로 남는다.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { evaluateStringCondition } from '../helpers/ConditionEvaluator';
import { DataBindingEngine } from '../DataBindingEngine';
const CANARY = '__g7jsi';
describe('조건 표현식 샌드박스 — window.__g7jsi canary (KVE-2026-1915)', () => {
const engine = new DataBindingEngine();
afterEach(() => {
delete (globalThis as any)[CANARY];
delete (window as any)[CANARY];
});
it('정상 조건(삼항·nullish·비교)은 렌더 경로에서 정상 평가된다', () => {
const ctx = { user: { name: '홍길동' }, count: 2 } as any;
expect(evaluateStringCondition('{{user?.name ? true : false}}', ctx, engine)).toBe(true);
expect(
evaluateStringCondition('{{(user?.missing ?? "fallback") === "fallback"}}', ctx, engine)
).toBe(true);
expect(evaluateStringCondition('{{count > 1}}', ctx, engine)).toBe(true);
});
/** @effects sandbox_escape_blocked, dangerous_payload_does_not_set_global */
it('constructor 체인 익스플로잇은 코드를 실행하지 못한다(canary 미설정 + 거부)', () => {
delete (globalThis as any)[CANARY];
delete (window as any)[CANARY];
const payloads = [
"{{''.constructor.constructor('window.__g7jsi = 1')()}}",
"{{''['constructor']['constructor']('window.__g7jsi = 2')()}}",
'{{({}).__proto__}}',
"{{Function('window.__g7jsi = 3')()}}",
"{{eval('window.__g7jsi = 4')}}",
];
const results = payloads.map((p) => {
try {
return evaluateStringCondition(p, {} as any, engine);
} catch {
return false;
}
});
// 익스플로잇 코드가 실행되지 않았다 — 전역 canary 미설정
expect((globalThis as any)[CANARY]).toBeUndefined();
expect((window as any)[CANARY]).toBeUndefined();
// 위험 표현식은 truthy 로 평가되지 않는다(거부)
expect(results.every((r) => r === false)).toBe(true);
});
it('화살표 함수·템플릿 리터럴 정상 표현식은 통과한다(과차단 회귀 방지)', () => {
const ctx = { items: [{ v: 'a' }, { v: 'b' }, { v: 'a' }], $args: ['x'] } as any;
expect(
evaluateStringCondition("{{(items ?? []).filter(i => i.v === 'a').length === 2}}", ctx, engine)
).toBe(true);
expect(
evaluateStringCondition('{{`/mypage/${$args[0]}` === "/mypage/x"}}', ctx, engine)
).toBe(true);
});
});
@@ -0,0 +1,804 @@
import { describe, it, expect } from 'vitest';
import { evaluateSafeExpression } from '../SafeExpressionEvaluator';
/**
* SafeExpressionEvaluator 테스트.
*
* `new Function` / `with(ctx)` 를 대체하는 안전한 표현식 인터프리터 검증.
* 실제 레이아웃 표현식 호환성 + 샌드박스 탈출 차단(보안)을 모두 다룬다.
*
* 시나리오 축(case)은 배포 번들 E2E(layout-expression-sandbox.spec.ts)가 커버하고,
* 이 파일은 소스 레벨에서 같은 효과를 떠받친다.
*
* 효과 요약(마커 아님 — 평문): sandbox_escape_blocked,
* same_expression_same_value_across_paths. 실제 마커는 그 효과를 단언하는 개별
* 테스트에만 둔다 — 파일 레벨에 몰아 적으면 테스트를 전부 지워도 커버리지가 green 으로 남는다.
*/
const evalx = (expr: string, ctx: Record<string, unknown> = {}): unknown =>
evaluateSafeExpression(expr, ctx);
describe('SafeExpressionEvaluator', () => {
describe('literals', () => {
it('정수/실수', () => {
expect(evalx('42')).toBe(42);
expect(evalx('3.14')).toBe(3.14);
expect(evalx('.5')).toBe(0.5);
expect(evalx('1e3')).toBe(1000);
});
it('문자열 (따옴표/이스케이프)', () => {
expect(evalx("'hello'")).toBe('hello');
expect(evalx('"world"')).toBe('world');
expect(evalx("'a\\'b'")).toBe("a'b");
expect(evalx('"a\\"b"')).toBe('a"b');
expect(evalx("'a\\\\b'")).toBe('a\\b');
expect(evalx("'a\\nb'")).toBe('a\nb');
expect(evalx("'a\\tb'")).toBe('a\tb');
});
it('boolean/null/undefined', () => {
expect(evalx('true')).toBe(true);
expect(evalx('false')).toBe(false);
expect(evalx('null')).toBe(null);
expect(evalx('undefined')).toBe(undefined);
});
it('배열/객체 리터럴', () => {
expect(evalx('[1, 2, 3]')).toEqual([1, 2, 3]);
expect(evalx("{ a: 1, 'b-c': 2 }")).toEqual({ a: 1, 'b-c': 2 });
});
});
describe('member & optional chaining', () => {
it('점 접근', () => {
expect(evalx('a.b.c', { a: { b: { c: 5 } } })).toBe(5);
});
it('옵셔널 체이닝 단락', () => {
expect(evalx('a?.b', { a: null })).toBe(undefined);
expect(evalx('a?.b?.c', { a: undefined })).toBe(undefined);
expect(evalx("user?.name ?? 'Guest'", { user: null })).toBe('Guest');
expect(evalx("user?.name ?? 'Guest'", { user: { name: 'Kim' } })).toBe('Kim');
});
it('없는 식별자는 undefined (throw 하지 않음)', () => {
expect(evalx('missing')).toBe(undefined);
expect(evalx('missing?.x')).toBe(undefined);
expect(evalx("missing ?? 'fallback'")).toBe('fallback');
});
it('nullish 비-optional 접근은 undefined 반환', () => {
expect(evalx('a.b', { a: undefined })).toBe(undefined);
});
});
describe('computed access', () => {
it('문자열/변수 키', () => {
expect(evalx("obj['key']", { obj: { key: 9 } })).toBe(9);
expect(evalx('obj[k]', { obj: { key: 9 }, k: 'key' })).toBe(9);
expect(evalx("query['status[]']", { query: { 'status[]': ['a'] } })).toEqual(['a']);
});
it('옵셔널 computed', () => {
expect(evalx('a?.[0]', { a: null })).toBe(undefined);
expect(evalx('a?.[0]', { a: [7] })).toBe(7);
});
});
describe('calls & methods', () => {
it('컨텍스트 함수 호출', () => {
expect(evalx("$t('some.key')", { $t: (k: string) => k })).toBe('some.key');
});
it('$get 헬퍼', () => {
const $get = (obj: unknown, path: string[], def: unknown): unknown => {
let cur: unknown = obj;
for (const p of path) {
if (cur == null) return def;
cur = (cur as Record<string, unknown>)[p];
}
return cur ?? def;
};
expect(evalx("$get(product, ['prices', 'KRW'], 'n/a')", { product: { prices: { KRW: 1000 } }, $get })).toBe(
1000,
);
expect(evalx("$get(product, ['prices', 'USD'], 'n/a')", { product: { prices: { KRW: 1000 } }, $get })).toBe(
'n/a',
);
});
it('인스턴스 메서드 체인', () => {
expect(evalx('String(value).toLocaleString()', { value: 1234 })).toBe('1234');
});
it('옵셔널 호출', () => {
expect(evalx('obj?.method?.()', { obj: {} })).toBe(undefined);
expect(evalx('obj?.method?.()', { obj: { method: () => 3 } })).toBe(3);
});
it('Math.max 등 화이트리스트 전역', () => {
expect(evalx('Math.max(0, (products?.data?.length ?? 0) - 1)', { products: { data: [1, 2, 3] } })).toBe(2);
expect(evalx('Math.max(0, (products?.data?.length ?? 0) - 1)', {})).toBe(0);
});
});
describe('arrow-function array methods', () => {
it('filter', () => {
expect(evalx("['a', 'b', 'c'].filter(v => v !== 'b')")).toEqual(['a', 'c']);
});
it('map returning object', () => {
expect(
evalx('items.map(i => ({ id: i.id, label: i.name })).length', {
items: [
{ id: 1, name: 'x' },
{ id: 2, name: 'y' },
],
}),
).toBe(2);
});
it('findIndex (u, i, a) 3-params dedupe', () => {
const ctx = {
list: [{ uuid: 'a' }, { uuid: 'b' }, { uuid: 'a' }],
};
expect(evalx('list.filter((u, i, a) => a.findIndex(x => x.uuid === u.uuid) === i).length', ctx)).toBe(2);
});
});
describe('spread (array / object / call)', () => {
it('배열 스프레드', () => {
expect(evalx('[...a, ...b, 3]', { a: [1], b: [2] })).toEqual([1, 2, 3]);
});
it('객체 스프레드', () => {
expect(evalx('{ ...a, c: 3 }', { a: { a: 1, b: 2 } })).toEqual({ a: 1, b: 2, c: 3 });
});
it('call 스프레드', () => {
expect(evalx('Math.max(...nums)', { nums: [4, 9, 2] })).toBe(9);
});
});
describe('operators & precedence', () => {
it('산술 우선순위', () => {
expect(evalx('1 + 2 * 3')).toBe(7);
expect(evalx('(1 + 2) * 3')).toBe(9);
expect(evalx('10 % 3')).toBe(1);
expect(evalx('7 / 2')).toBe(3.5);
});
it('단항', () => {
expect(evalx('!true')).toBe(false);
expect(evalx('-5')).toBe(-5);
expect(evalx('+"3"')).toBe(3);
expect(evalx("typeof x", { x: 'str' })).toBe('string');
expect(evalx('typeof missing')).toBe('undefined');
});
it('비교/동등', () => {
expect(evalx('1 === 1')).toBe(true);
expect(evalx("1 === '1'")).toBe(false);
expect(evalx("1 == '1'")).toBe(true);
expect(evalx('2 !== 3')).toBe(true);
expect(evalx('2 < 3 && 3 <= 3')).toBe(true);
});
it('(count ?? 0) + 1', () => {
expect(evalx('(count ?? 0) + 1', {})).toBe(1);
expect(evalx('(count ?? 0) + 1', { count: 5 })).toBe(6);
});
});
describe('ternary / nullish / logical short-circuit', () => {
it('삼항 (중첩)', () => {
expect(evalx("a ? 'x' : b ? 'y' : 'z'", { a: false, b: true })).toBe('y');
expect(evalx("a ? 'x' : b ? 'y' : 'z'", { a: false, b: false })).toBe('z');
});
it('|| 은 첫 truthy 피연산자 반환 (boolean 아님)', () => {
expect(evalx("'' || 'fallback'")).toBe('fallback');
expect(evalx("'first' || 'second'")).toBe('first');
expect(evalx('0 || 42')).toBe(42);
});
it('&& 는 첫 falsy 또는 마지막 값', () => {
expect(evalx("'a' && 'b'")).toBe('b');
expect(evalx("0 && 'b'")).toBe(0);
});
it('?? 는 nullish 만 폴백', () => {
expect(evalx("0 ?? 'x'")).toBe(0);
expect(evalx("null ?? 'x'")).toBe('x');
expect(evalx("'' ?? 'x'")).toBe('');
});
it('&& 단락으로 오른쪽 미평가', () => {
let called = false;
const ctx = {
cond: false,
boom: () => {
called = true;
return 1;
},
};
expect(evalx('cond && boom()', ctx)).toBe(false);
expect(called).toBe(false);
});
});
describe('whitelisted globals', () => {
it('JSON / Number / Boolean / parse*', () => {
expect(evalx('JSON.stringify(a)', { a: { x: 1 } })).toBe('{"x":1}');
expect(evalx("Number('42')")).toBe(42);
expect(evalx("parseInt('10px', 10)")).toBe(10);
expect(evalx("parseFloat('3.5rem')")).toBe(3.5);
expect(evalx('isNaN(x)', { x: NaN })).toBe(true);
expect(evalx('isFinite(1)')).toBe(true);
expect(evalx('Boolean(0)')).toBe(false);
expect(evalx('Array.isArray(a)', { a: [] })).toBe(true);
});
});
describe('context shadowing', () => {
it('컨텍스트 값이 전역보다 우선', () => {
expect(evalx('String', { String: 'shadowed' })).toBe('shadowed');
expect(evalx('Math', { Math: 123 })).toBe(123);
});
});
describe('template literals', () => {
it('보간 없는 템플릿', () => {
expect(evalx('`no interpolation`')).toBe('no interpolation');
});
it('단일 보간', () => {
expect(evalx('`/mypage/${$args[0]}`', { $args: ['x'] })).toBe('/mypage/x');
});
it('표현식 보간', () => {
expect(evalx('`total: ${(count ?? 0) + 1}`', {})).toBe('total: 1');
expect(evalx('`total: ${(count ?? 0) + 1}`', { count: 9 })).toBe('total: 10');
});
it('다중 보간 + 리터럴 조각', () => {
expect(evalx('`${a}-${b}!`', { a: 'x', b: 'y' })).toBe('x-y!');
});
it('템플릿 내 이스케이프', () => {
expect(evalx('`a\\nb`')).toBe('a\nb');
expect(evalx('`price \\${x}`')).toBe('price ${x}');
});
});
describe('new operator (whitelisted constructors)', () => {
it('new Date(str).getTime() → number', () => {
expect(evalx("new Date('2020-01-01').getTime()")).toBe(new Date('2020-01-01').getTime());
expect(typeof evalx("new Date('2020-01-01').getTime()")).toBe('number');
});
it('new Date().toISOString().slice(0,10) → 10-char string', () => {
const r = evalx('new Date().toISOString().slice(0, 10)');
expect(typeof r).toBe('string');
expect((r as string).length).toBe(10);
});
it('Array.from(new Set([...])) dedupe', () => {
expect(evalx('Array.from(new Set([1, 1, 2]))')).toEqual([1, 2]);
});
it('new Map([...]).get(key)', () => {
expect(evalx("new Map([['a', 1]]).get('a')")).toBe(1);
});
it('new Date(query.expires_at).getTime()', () => {
const ctx = { query: { expires_at: '2021-06-15T00:00:00Z' } };
expect(evalx('new Date(query.expires_at).getTime()', ctx)).toBe(
new Date('2021-06-15T00:00:00Z').getTime(),
);
});
it('Array.from(new Set(x.flatMap(...)))', () => {
const ctx = { x: [{ tags: ['a', 'b'] }, { tags: ['b', 'c'] }] };
expect(evalx('Array.from(new Set((x ?? []).flatMap(p => p.tags)))', ctx)).toEqual(['a', 'b', 'c']);
});
});
describe('real-world compatibility', () => {
/** @effects same_expression_same_value_across_paths */
it('상태 필터 토글 (statusFilter)', () => {
const expr =
"((_global.statusFilter ?? query['status[]']) || []).includes('pending') ? ((_global.statusFilter ?? query['status[]']) || []).filter(v => v !== 'pending') : [...((_global.statusFilter ?? query['status[]']) || []), 'pending']";
// 현재 pending 없음 → 추가
expect(evalx(expr, { _global: { statusFilter: ['active'] }, query: {} })).toEqual(['active', 'pending']);
// 현재 pending 있음 → 제거
expect(evalx(expr, { _global: { statusFilter: ['pending', 'active'] }, query: {} })).toEqual(['active']);
// 둘 다 없음 → 추가
expect(evalx(expr, { _global: {}, query: {} })).toEqual(['pending']);
});
/** @effects same_expression_same_value_across_paths */
it('board_managers 병합 + dedupe', () => {
const expr =
'[...(_local.form?.board_managers ?? []), ...(_local.managerSearchResults ?? [])].filter(u => ($event.target.value ?? []).includes(u.uuid)).filter((u, i, a) => a.findIndex(x => x.uuid === u.uuid) === i)';
const ctx = {
_local: {
form: { board_managers: [{ uuid: 'a' }, { uuid: 'b' }] },
managerSearchResults: [{ uuid: 'b' }, { uuid: 'c' }],
},
$event: { target: { value: ['a', 'b'] } },
};
expect(evalx(expr, ctx)).toEqual([{ uuid: 'a' }, { uuid: 'b' }]);
});
/** @effects same_expression_same_value_across_paths */
it('comment blind 로그 판정', () => {
const expr =
"comment?.abilities?.can_manage && (comment?.action_logs ?? []).filter(log => log.action === 'blind').length > 0";
expect(
evalx(expr, {
comment: { abilities: { can_manage: true }, action_logs: [{ action: 'blind' }] },
}),
).toBe(true);
expect(
evalx(expr, {
comment: { abilities: { can_manage: true }, action_logs: [] },
}),
).toBe(false);
});
/** @effects same_expression_same_value_across_paths */
it('마지막 blind 로그 reason 추출', () => {
const expr = "(post?.data?.action_logs ?? []).filter(log => log.action === 'blind').slice(-1)[0]?.reason ?? '-'";
expect(
evalx(expr, {
post: { data: { action_logs: [{ action: 'blind', reason: 'spam' }] } },
}),
).toBe('spam');
expect(evalx(expr, { post: { data: { action_logs: [] } } })).toBe('-');
});
});
// engine-v1.60.0 — statement 본문(function/arrow 블록 IIFE) 회귀 복원.
// KVE-2026-1915 로 new Function → AST 인터프리터 교체 시, 기존 30개 레이아웃이 쓰던
// `(function(){ const …; if(…) return …; })()` 형태가 조용히 거부돼 저장이 미해석
// 원문 문자열로 전송되던 회귀(문의 게시판 지정 실패 등)를 고정한다.
describe('statement 본문 IIFE (engine-v1.60.0 회귀 복원)', () => {
it('const 선언 + return (arrow 블록)', () => {
expect(evalx('(() => { const x = 1; return x + 1; })()')).toBe(2);
});
it('const 선언 + return (function 식)', () => {
expect(evalx('(function() { const a = 2; const b = 3; return a * b; })()')).toBe(6);
});
it('if 분기 다중 return — 탭별 payload 조립 (이커머스 설정 저장 본문)', () => {
const expr =
"(function() { const tab = _global.activeEcommerceSettingsTab || query.tab || 'basic_info'; const form = _local.form ?? {}; if (tab === 'notification_definitions') { return { _tab: 'notifications', notifications: { channels: form.notifications?.channels || [] } }; } if (tab === 'mileage') { return { _tab: 'mileage', mileage: form.mileage ?? {} }; } return { _tab: tab, [tab]: form[tab] ?? {}, inquiry: form.inquiry ?? {} }; })()";
// 문의 게시판 지정: basic_info 탭에서 inquiry.board_slug 가 payload 에 실려야 한다
const result = evalx(expr, {
_global: {},
query: { tab: 'basic_info' },
_local: { form: { basic_info: { shop_name: 'S' }, inquiry: { board_slug: 'inquiry' } } },
}) as Record<string, unknown>;
expect(result._tab).toBe('basic_info');
expect((result.inquiry as Record<string, unknown>).board_slug).toBe('inquiry');
expect((result.basic_info as Record<string, unknown>).shop_name).toBe('S');
});
it('new Date() + 변형 메서드 (게시판 신고 기간 프리셋)', () => {
const expr = '(() => { const d = new Date(2026, 0, 10); d.setDate(d.getDate() - 2); return d.getDate(); })()';
expect(evalx(expr)).toBe(8);
});
it('for-of + continue + 재귀 arrow + 기본 파라미터 (카테고리 flatten)', () => {
const expr =
"(() => { const result = []; const flatten = (items, path = [], depth = 0) => { if (!items || !Array.isArray(items) || items.length === 0) return; for (const item of items) { if (!item || !item.id) continue; const currentPath = [...path, item.name]; result.push({ value: item.id, label: currentPath.join(' > ') }); if (item.children && Array.isArray(item.children) && item.children.length > 0 && depth < 2) { flatten(item.children, currentPath, depth + 1); } } }; flatten(categories); return result; })()";
const out = evalx(expr, {
categories: [
{ id: 1, name: 'A', children: [{ id: 2, name: 'A1', children: [] }] },
{ id: 3, name: 'B', children: [] },
{ id: null, name: 'skip' },
],
}) as Array<{ value: number; label: string }>;
expect(out).toEqual([
{ value: 1, label: 'A' },
{ value: 2, label: 'A > A1' },
{ value: 3, label: 'B' },
]);
});
it('delete 로 로컬 객체 사본 프로퍼티 제거 (edit 모드 slug 제외)', () => {
const expr = '(() => { const data = {...form}; if (mode === "edit") { delete data.slug; } return data; })()';
expect(evalx(expr, { form: { name: 'N', slug: 's' }, mode: 'edit' })).toEqual({ name: 'N' });
expect(evalx(expr, { form: { name: 'N', slug: 's' }, mode: 'create' })).toEqual({ name: 'N', slug: 's' });
});
it('function 콜백 + concat + map (게시판 카테고리 옵션)', () => {
const expr =
"[{value:'all', label:'전체'}].concat((categories ?? []).map(function(c){return{value:c,label:c};}))";
expect(evalx(expr, { categories: ['notice', 'qna'] })).toEqual([
{ value: 'all', label: '전체' },
{ value: 'notice', label: 'notice' },
{ value: 'qna', label: 'qna' },
]);
});
it('try/catch 블록 본문 (실제 throw 를 잡음)', () => {
// 이 평가기는 null 멤버 접근을 관대하게 undefined 로 돌려주므로(with 시맨틱),
// 실제로 throw 하는 것은 비함수 호출·JSON.parse 오류 등이다.
expect(evalx('(() => { try { return notFn(); } catch (e) { return "fallback"; } })()', { notFn: 123 })).toBe('fallback');
expect(evalx("(() => { try { return JSON.parse('{bad'); } catch (e) { return 'invalid'; } })()")).toBe('invalid');
expect(evalx('(() => { try { return safe; } catch (e) { return "x"; } })()', { safe: 42 })).toBe(42);
});
it('IIFE 반환 타입 보존 — 객체/배열/빈문자열/undefined (if 판정 계약)', () => {
expect(evalx('(function(){ return {}; })()')).toEqual({});
expect(evalx('(function(){ return []; })()')).toEqual([]);
expect(evalx('(function(){ return ""; })()')).toBe('');
expect(evalx('(function(){ return; })()')).toBe(undefined);
});
});
describe('SECURITY — sandbox escape blocked', () => {
/** @effects sandbox_escape_blocked */
it("''.constructor.constructor('return 1')()", () => {
expect(() => evalx("''.constructor.constructor('return 1')()")).toThrow();
});
/** @effects sandbox_escape_blocked */
it("''['constructor']['constructor']('return 1')()", () => {
expect(() => evalx("''['constructor']['constructor']('return 1')()")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('({}).__proto__', () => {
expect(() => evalx('({}).__proto__')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('[].constructor', () => {
expect(() => evalx('[].constructor')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('x.prototype', () => {
expect(() => evalx('x.prototype', { x: {} })).toThrow();
});
/** @effects sandbox_escape_blocked */
it('Function(...)', () => {
expect(() => evalx("Function('return 1')")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('window', () => {
expect(() => evalx('window')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('globalThis', () => {
expect(() => evalx('globalThis')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('eval', () => {
expect(() => evalx("eval('1')")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('computed constructor via variable — eval-time block', () => {
expect(() => evalx("''[c]", { c: 'constructor' })).toThrow();
});
/** @effects sandbox_escape_blocked */
it('computed __proto__ via variable — eval-time block', () => {
expect(() => evalx('o[k]', { o: {}, k: '__proto__' })).toThrow();
});
/** @effects sandbox_escape_blocked */
it('constructor access inside arrow callback still blocked', () => {
expect(() => evalx('[1].map(x => x.constructor)')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('constructor access inside template interpolation still blocked', () => {
expect(() => evalx("`${''.constructor.constructor('x')()}`")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('new on non-whitelisted constructor rejected', () => {
expect(() => evalx('new evil()', { evil: function () {} })).toThrow();
});
/** @effects sandbox_escape_blocked */
it('new Function still rejected', () => {
expect(() => evalx("new Function('return 1')")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('new x() with context function rejected (not whitelisted)', () => {
expect(() => evalx('new x()', { x: function () {} })).toThrow();
});
/** @effects sandbox_escape_blocked */
it("new ''.constructor() rejected", () => {
expect(() => evalx("new ''.constructor()")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('assignment rejected', () => {
expect(() => evalx('x = 1', { x: 0 })).toThrow();
});
/** @effects sandbox_escape_blocked */
it('increment rejected', () => {
expect(() => evalx('x++', { x: 0 })).toThrow();
});
// engine-v1.60.0: 함수 표현식/블록 본문은 허용된다(해석기 클로저로 실행).
// 탈출 벡터는 "function 키워드" 가 아니라 `.constructor`/`Function`/`eval` 접근이며,
// 그 차단은 statement 본문 안에서도 그대로 유지된다.
/** @effects sandbox_escape_blocked */
it('함수 표현식 본문에서도 constructor 탈출은 여전히 차단', () => {
expect(() => evalx('(function(){ return "".constructor; })()')).toThrow();
expect(() => evalx('(function(){ return [].constructor.constructor("return 1")(); })()')).toThrow();
expect(() => evalx('(() => { const c = "".constructor; return c; })()')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('함수 본문에서도 Function/eval 전역 참조는 차단', () => {
expect(() => evalx('(function(){ return Function("return 1"); })()')).toThrow();
expect(() => evalx('(() => { return eval("1"); })()')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('블록 본문 안의 대입식은 여전히 거부', () => {
expect(() => evalx('(function(){ x = 1; return x; })()', { x: 0 })).toThrow();
expect(() => evalx('(() => { let y = 0; y = 2; return y; })()')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('블록 본문 안에서도 비화이트리스트 new 는 차단', () => {
expect(() => evalx('(function(){ return new evil(); })()', { evil: function () {} })).toThrow();
});
/** @effects sandbox_escape_blocked */
it('delete 로 화이트리스트 전역 프로퍼티 삭제 차단', () => {
expect(() => evalx('(function(){ delete Math.floor; return 1; })()')).toThrow();
expect(() => evalx('(function(){ const o = {}; return delete o.constructor; })()')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('sequence operator rejected', () => {
expect(() => evalx('1, 2')).toThrow();
});
});
// KVE-2026-1915 재발 — 비-문자열 computed 키 + Object 리플렉션 static 을 통한
// 샌드박스 탈출. 기존 SECURITY 스위트는 문자열 키(''[c], c='constructor')만 검증해
// 아래 벡터들이 81건 green 상태에서도 그대로 실행됐다.
describe('SECURITY — non-string computed key escape blocked (KVE-2026-1915)', () => {
/** @effects sandbox_escape_blocked */
it("''[['constructor']] — 배열 키가 'constructor' 로 강제변환되어 접근되던 결함", () => {
expect(() => evalx("''[['constructor']]")).toThrow();
});
/** @effects sandbox_escape_blocked */
it("''[['constructor']][['constructor']]('return 1')() — 배열 키 RCE 전체 체인", () => {
expect(() => evalx("''[['constructor']][['constructor']]('return 1')()")).toThrow();
});
/** @effects sandbox_escape_blocked */
it("''[['const' + 'ructor']] — 배열 안 문자열 조립 우회", () => {
expect(() => evalx("''[['const' + 'ructor']]")).toThrow();
});
/** @effects sandbox_escape_blocked */
it("''[[['constructor']]] — 중첩 배열 키 우회", () => {
expect(() => evalx("''[[['constructor']]]")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('o[[k]] — 컨텍스트 값을 담은 배열 키 우회', () => {
expect(() => evalx('o[[k]]', { o: {}, k: '__proto__' })).toThrow();
});
/** @effects sandbox_escape_blocked */
it("''[{ toString: () => 'constructor' }] — 객체 toString 강제변환 우회 (TOCTOU 없음: 1회 정규화)", () => {
expect(() => evalx("''[{ toString: () => 'constructor' }]")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('delete o[[key]] — 배열 키 삭제 경로도 차단', () => {
expect(() => evalx('(function(){ const o = {}; return delete o[["constructor"]]; })()')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('정상 computed 접근은 유지 — 배열/숫자/문자열 키', () => {
expect(evalx("o['a']", { o: { a: 1 } })).toBe(1);
expect(evalx('arr[0]', { arr: [42] })).toBe(42);
expect(evalx("o[k]", { o: { name: 'x' }, k: 'name' })).toBe('x');
});
});
describe('SECURITY — Object reflection statics removed (KVE-2026-1915)', () => {
/** @effects sandbox_escape_blocked */
it('Object.getPrototypeOf 는 노출되지 않는다', () => {
expect(() => evalx('Object.getPrototypeOf(String)')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('Object.getOwnPropertyDescriptor(...).value 리플렉션 RCE 전체 체인', () => {
expect(() =>
evalx("Object.getOwnPropertyDescriptor(Object.getPrototypeOf(String), 'constructor').value('return 1')()"),
).toThrow();
});
/** @effects sandbox_escape_blocked */
it('Object.setPrototypeOf 는 노출되지 않는다 (프로토타입 오염 차단)', () => {
expect(() => evalx('Object.setPrototypeOf({}, {})')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('Object.defineProperty 는 노출되지 않는다', () => {
expect(() => evalx("Object.defineProperty({}, 'x', { value: 1 })")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('Object.getOwnPropertyDescriptors 는 노출되지 않는다', () => {
expect(() => evalx('Object.getOwnPropertyDescriptors(String)')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('안전한 Object 데이터 메서드는 유지 — keys/values/entries/assign/fromEntries', () => {
expect(evalx('Object.keys({ a: 1, b: 2 })')).toEqual(['a', 'b']);
expect(evalx('Object.values({ a: 1, b: 2 })')).toEqual([1, 2]);
expect(evalx('Object.entries({ a: 1 })')).toEqual([['a', 1]]);
expect(evalx('Object.assign({ a: 1 }, { b: 2 })')).toEqual({ a: 1, b: 2 });
expect(evalx("Object.fromEntries([['a', 1]])")).toEqual({ a: 1 });
});
// 회귀 방지: create 는 프로토타입/디스크립터를 읽지도 쓰지도 않으므로 유지된다.
// 실제 레이아웃(_tab_reviews.json)의 리뷰 옵션 필터 맵 생성 패턴을 고정한다.
/** @effects sandbox_escape_blocked */
it('Object.create(null) + assign 은 유지 — 실제 레이아웃 필터 맵 패턴', () => {
expect(evalx("Object.assign(Object.create(null), { a: '1' }, { b: '2' })")).toEqual({
a: '1',
b: '2',
});
expect(
evalx('Object.assign(Object.create(null), base, { [k]: v })', {
base: { x: 1 },
k: 'y',
v: 2,
}),
).toEqual({ x: 1, y: 2 });
});
});
// ==========================================
// 공유 전역 변조 차단 (delete 가드와 대칭)
// ==========================================
//
// WHITELIST_GLOBALS 는 Math/JSON/Date 등 **실제 전역 참조**를 노출한다. delete 는
// identity 검사로 이미 차단하지만, facade 에 남긴 assign/freeze 는 대상 객체를
// 검사하지 않으면 같은 공유 전역을 변조할 수 있다 — 페이지 전체(엔진·모듈·플러그인)에
// 지속되는 오염이므로 delete 와 동일 강도로 막아야 한다.
describe('공유 전역 변조 차단', () => {
/** @effects sandbox_escape_blocked */
it('Object.assign 으로 화이트리스트 전역을 변조할 수 없다', () => {
expect(() => evalx('Object.assign(Math, { floor: 1 })')).toThrow();
expect(() => evalx('Object.assign(JSON, { parse: 1 })')).toThrow();
expect(Math.floor(1.5)).toBe(1);
});
/** @effects sandbox_escape_blocked */
it('Object.freeze 로 화이트리스트 전역을 동결할 수 없다', () => {
expect(() => evalx('Object.freeze(Math)')).toThrow();
expect(Object.isFrozen(Math)).toBe(false);
});
/** @effects sandbox_escape_blocked */
it('화이트리스트 생성자도 동일하게 보호된다', () => {
expect(() => evalx('Object.assign(Date, { now: 1 })')).toThrow();
});
/** @effects sandbox_escape_blocked */
it('일반 객체에 대한 assign·freeze 는 정상 동작한다 (과차단 회귀 방지)', () => {
expect(evalx('Object.assign({ a: 1 }, { b: 2 })')).toEqual({ a: 1, b: 2 });
expect(evalx("Object.assign(Object.create(null), { a: '1' })")).toEqual({ a: '1' });
expect(evalx('Object.isFrozen(Object.freeze({ a: 1 }))')).toBe(true);
expect(evalx('Object.assign(target, { b: 2 })', { target: { a: 1 } })).toEqual({
a: 1,
b: 2,
});
});
});
describe('SECURITY — legacy 접근자를 통한 프로토타입 도달 차단 (KVE-2026-1915)', () => {
// Object.prototype 위의 legacy 접근자 4종은 프로퍼티를 **키가 아니라 문자열 인자**로
// 지목하므로 normalizeKey 의 키 검사를 원리상 거치지 않는다. 이는 Object facade 에서
// getPrototypeOf/setPrototypeOf/defineProperty 를 제거한 것과 같은 능력을 우회 복원한다.
// 배포 레이아웃 599개에서 이 4개 이름 사용은 0건이라 차단해도 회귀가 없다.
afterEach(() => {
// 오염이 실제로 일어났다면 다른 테스트로 번지지 않게 정리한다.
delete (Object.prototype as Record<string, unknown>).pwned;
delete (Array.prototype as Record<string, unknown>).pwned;
});
it.each([
['__lookupGetter__', "({}).__lookupGetter__('__proto__')"],
['__lookupSetter__', "({}).__lookupSetter__('__proto__')"],
['__defineGetter__', "({}).__defineGetter__('x', function () { return 1; })"],
['__defineSetter__', "({}).__defineSetter__('x', function (v) { return v; })"],
])('%s 접근이 거부된다', (_name, expr) => {
expect(() => evalx(expr)).toThrow();
});
/** @effects sandbox_escape_blocked */
it('문자열 조립으로도 우회할 수 없다 (정적 검사가 못 잡는 형태)', () => {
expect(() => evalx("({})['__lookup' + 'Getter__']('__pro' + 'to__')")).toThrow();
expect(() => evalx("({})[['__lookupGetter__']]('__proto__')")).toThrow();
});
/** @effects sandbox_escape_blocked */
it('프로토타입을 손에 넣어 전역을 오염시킬 수 없다', () => {
// .call 없이 method-position 으로도 thisArg 가 공급되므로 두 형태를 모두 고정한다.
expect(() =>
evalx("({}).__lookupGetter__('__pro' + 'to__').call({}).__defineGetter__('pwned', function () { return 1; })")
).toThrow();
expect(() =>
evalx("({ g: ({}).__lookupGetter__('__pro' + 'to__') }).g()")
).toThrow();
expect((Object.prototype as Record<string, unknown>).pwned).toBeUndefined();
expect(({} as Record<string, unknown>).pwned).toBeUndefined();
});
/** @effects sandbox_escape_blocked */
it('배열 프로토타입도 동일하게 보호된다', () => {
expect(() => evalx("[].__lookupGetter__('__pro' + 'to__').call([])")).toThrow();
expect((Array.prototype as Record<string, unknown>).pwned).toBeUndefined();
expect([].map).toBeTypeOf('function');
});
/** @effects sandbox_escape_blocked */
it('함수 객체의 프로토타입에도 도달할 수 없다', () => {
expect(() =>
evalx("Math.floor.__lookupGetter__('__pro' + 'to__').call(Math.floor)")
).toThrow();
expect(Math.floor(1.5)).toBe(1);
});
/** @effects sandbox_escape_blocked */
it('Object.assign 이 source 의 __proto__ 키로 프로토타입을 바꾸지 못한다', () => {
// JSON.parse 는 __proto__ 를 own enumerable 데이터 프로퍼티로 만든다.
// 네이티브 Object.assign 은 [[Set]] 으로 복사해 target 의 __proto__ setter 를 깨운다.
const state: Record<string, unknown> = { a: 1 };
// 금지 키는 조용히 건너뛰지 않고 거부한다 — 평가기의 다른 금지 키 처리(normalizeKey)와
// 같은 강도. 조용한 skip 은 공격 시도를 정상 렌더로 위장한다.
expect(() =>
evalx('Object.assign(state, JSON.parse(raw))', {
state,
raw: '{"__proto__":{"isAdmin":true}}',
})
).toThrow();
expect(Object.getPrototypeOf(state)).toBe(Object.prototype);
expect((state as { isAdmin?: boolean }).isAdmin).toBeUndefined();
});
/** @effects sandbox_escape_blocked */
it('정상 표현식은 그대로 통과한다 (과차단 회귀 방지)', () => {
// 배포 레이아웃이 실제로 쓰는 형태들 — toLocaleString 19곳, Object.assign 34곳, Object.create 1곳
expect(evalx('(1234.5).toLocaleString()')).toBeTypeOf('string');
expect(evalx("Object.assign(Object.create(null), { a: '1' })")).toEqual({ a: '1' });
expect(evalx('Object.assign({ a: 1 }, { b: 2 })')).toEqual({ a: 1, b: 2 });
expect(evalx('({ a: 1 }).hasOwnProperty("a")')).toBe(true);
});
});
});
@@ -86,14 +86,14 @@ exports[`BindingShape 라우팅 diff 하네스 > 단일 바인딩 판정: greedy
]
`;
exports[`BindingShape 라우팅 diff 하네스 > 단일 바인딩 판정: 구 정규식과 신 정본이 갈리는 총량 1`] = `469`;
exports[`BindingShape 라우팅 diff 하네스 > 단일 바인딩 판정: 구 정규식과 신 정본이 갈리는 총량 1`] = `471`;
exports[`BindingShape 라우팅 diff 하네스 > 판정이 갈리는 식의 분류별 건수 요약 1`] = `
{
"numericIndex": 39,
"numericIndex": 29,
"other": 2,
"quotedBracket": 22,
"total": 63,
"total": 53,
}
`;
@@ -151,136 +151,6 @@ exports[`BindingShape 라우팅 diff 하네스 > 표현식/경로 판정: 구
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.bio[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.country[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.homepage[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.language[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.mobile[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.name[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.nickname[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.phone[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.signature[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "_local.profileErrors.timezone[0]",
"files": [
"templates/_bundled/sirsoft-basic/layouts/partials/mypage/profile/_edit.json",
],
"old": {
"DataBindingEngine.isBaseExpression": false,
"DataBindingEngine.resolveBindings": false,
"DynamicRenderer/ConditionEvaluator": false,
"RenderHelpers": true,
},
},
{
"canonical": true,
"expr": "['requested','sent','verified','failed','expired','cancelled','policy_violation_logged']",
@@ -1605,8 +1605,8 @@ describe('트러블슈팅 회귀 테스트 - DataGrid cellChildren 파이프', (
* 사례: cellChildren 단일 바인딩의 파이프가 적용되지 않아 셀이 비어 보임
*
* 단일 바인딩 판정 후 `|` 가 복잡 표현식 문자로 분류되어 evaluateExpression 으로
* 라우팅되면 JS 비트 OR 로 평가된다. 인자 있는 파이프는 예외(값 소실),
* 인자 없는 파이프는 조용한 오답이 된다. 라우팅 판정 자체를 고정한다.
* 라우팅되면 안 된다. engine-v1.59.0 의 안전 평가기는 비트 연산자를 거부하므로
* raw 파이프가 흘러들면 예외가 된다(종전엔 조용한 비트 OR 오답이었다). 라우팅 판정 자체를 고정한다.
*
* @see docs/frontend/troubleshooting-components-datagrid.md "DataGrid cellChildren 파이프 이슈"
* @see resources/js/core/template-engine/__tests__/renderItemChildren-pipe.test.ts (렌더 결과 검증)
@@ -1624,11 +1624,15 @@ describe('트러블슈팅 회귀 테스트 - DataGrid cellChildren 파이프', (
expect(hasPipes("row.flag ? '$t:common.badge|count=1' : ''")).toBe(false);
});
it('파이프를 evaluateExpression 으로 보내면 비트 OR 오답이 된다 (수정 전 동작 고정)', () => {
it('파이프를 evaluateExpression 으로 보내면 거부된다 (라우팅 판정 고정)', () => {
const engine = new DataBindingEngine();
// 인자 없는 파이프: 문자열이 0 으로 붕괴
expect(engine.evaluateExpression('row.code | uppercase', { row: { code: 'abc' } })).toBe(0);
// 인자 있는 파이프: 함수 호출 실패로 예외
// engine-v1.59.0: 표현식은 화이트리스트 AST 평가기로 실행되며 비트 연산자(`|`)를
// 거부한다. 종전 `new Function` 기반에서는 인자 없는 파이프가 비트 OR 로 조용히
// 0 이 되고 인자 있는 파이프는 예외였다 — 이제 둘 다 명확히 예외로 거부된다.
// (파이프는 hasPipes 로 먼저 분리되어야 하며 evaluateExpression 에 raw 로 오면 안 됨)
expect(() =>
engine.evaluateExpression('row.code | uppercase', { row: { code: 'abc' } })
).toThrow();
expect(() =>
engine.evaluateExpression("row.created_at | datetime('YYYY-MM-DD')", {
row: { created_at: '2024-01-15T14:30:00' },
@@ -39,6 +39,7 @@ function baseState(overrides: Partial<LayoutEditorState> = {}): LayoutEditorStat
}
describe('layoutEditorReducer — SELECT_ROUTE 가 별도 편집 모드를 종료', () => {
/** @effects select_route_from_separate_edit_mode_restores_route_mode_and_renders_canvas */
it('extension 편집 모드 → SELECT_ROUTE → editMode=route 복원 + 라우트 선택', () => {
const start = baseState({
editMode: 'extension',
@@ -144,6 +144,7 @@ describe('ComponentPalette — 폴백 카테고리 (componentPalette 미제공)'
});
// 결함 8 — 실제 렌더 컴포넌트 태그 배지 (React 컴포넌트명 형식)
/** @effects palette_card_shows_react_component_tag_badge */
it('카드에 React 컴포넌트명 형식의 태그 배지 표시 (<Div>, <Button>)', () => {
render(
withTranslation(
@@ -36,6 +36,7 @@ describe('EditorToolbar — 나가기 버튼 (결함 4)', () => {
expect(exit.disabled).toBe(true);
});
/** @effects toolbar_exit_navigates_to_template_list_by_type */
it('onExit 제공 시 활성 + 클릭하면 onExit 호출', () => {
const onExit = vi.fn();
render(wrap(<EditorToolbar onExit={onExit} />));
@@ -53,6 +54,7 @@ describe('EditorToolbar — 코드편집 버튼 (결함 5)', () => {
expect(code.disabled).toBe(true);
});
/** @effects toolbar_edit_code_opens_text_layout_editor_in_new_window_with_route */
it('onEditCode 제공 시 활성 + 클릭하면 호출', () => {
const onEditCode = vi.fn();
render(wrap(<EditorToolbar onEditCode={onEditCode} />));
@@ -79,6 +81,7 @@ describe('EditorToolbar — 버튼 잔류 테두리 (추가 결함: hover/focus
expect(/(^|;)\s*background\s*:/.test(raw)).toBe(false);
});
/** @effects toolbar_buttons_hover_transition_when_enabled_not_when_disabled */
it('마우스 올렸다 치우면 hover 스타일이 원복되어 잔류 테두리 없음', () => {
render(wrap(<EditorToolbar onExit={vi.fn()} onEditCode={vi.fn()} />));
const exit = screen.getByTestId('g7le-toolbar-exit') as HTMLButtonElement;
@@ -92,6 +95,7 @@ describe('EditorToolbar — 버튼 잔류 테두리 (추가 결함: hover/focus
expect(exit.style.borderColor).toBe(baseBorder);
});
/** @effects toolbar_buttons_no_residual_focus_outline_after_click */
it('클릭(focus)된 뒤에도 브라우저 기본 검정 outline 이 노출되지 않음 (outline:none)', () => {
render(wrap(<EditorToolbar onExit={vi.fn()} onEditCode={vi.fn()} />));
const code = screen.getByTestId('g7le-toolbar-edit-code') as HTMLButtonElement;
@@ -106,6 +110,7 @@ describe('EditorToolbar — 버튼 잔류 테두리 (추가 결함: hover/focus
});
describe('EditorToolbar — 저장 스피너 (결함 6)', () => {
/** @effects toolbar_save_shows_spinner_while_pending_then_restores */
it('onSave 가 Promise 면 저장 중 스피너 노출 + disabled, 완료 후 복원', async () => {
let resolveSave: () => void = () => {};
const onSave = vi.fn(
@@ -570,6 +570,7 @@ describe('RouteTreePanel — 라우트↔모달/확장 연결 그룹', () => {
return route;
}
/** @effects connected_group_collapsed_by_default */
it('연결 그룹(__conngroup__) 은 토글 가능한 헤더로 렌더 (기본 접힘 → 자식 미표시)', () => {
const route = makeRouteWithConnModal('/admin/users');
renderTree([makeGroupNode('template', '템플릿', [route])]);
@@ -590,6 +591,7 @@ describe('RouteTreePanel — 라우트↔모달/확장 연결 그룹', () => {
expect(modalItems).toHaveLength(0);
});
/** @effects connected_group_toggles_on_header_click */
it('연결 그룹 헤더 클릭 → 펼침 → 자식 표시, 재클릭 → 접힘', () => {
const route = makeRouteWithConnModal('/admin/users');
renderTree([makeGroupNode('template', '템플릿', [route])]);
@@ -613,6 +615,7 @@ describe('RouteTreePanel — 라우트↔모달/확장 연결 그룹', () => {
).toHaveLength(0);
});
/** @effects modal_child_click_enters_modal_edit_keeping_host_route_highlight */
it('연결 모달 자식 클릭 → ENTER_MODAL_EDIT + 호스트 라우트 강조 유지', () => {
const route = makeRouteWithConnModal('/admin/users');
renderTreeWithProbe([makeGroupNode('template', '템플릿', [route])]);
@@ -646,7 +649,8 @@ describe('RouteTreePanel — 라우트↔모달/확장 연결 그룹', () => {
expect(selectedModal.getAttribute('style')).toContain('rgb(239, 246, 255)');
});
it('연결 확장 자식 클릭 → ENTER_EXTENSION_EDIT (editMode=extension)', () => {
/** @effects extension_child_click_enters_extension_edit_keeping_host_route_highlight, connected_count_stable_when_entering_extension_edit_mode */
it('연결 확장 자식 클릭 → ENTER_EXTENSION_EDIT + 호스트 라우트 강조·연결 건수 유지', () => {
const route = makeRouteNode('/admin/users', '회원 목록');
const ext = makeConnectedExtensionNode('2', '🧩 게시판 · admin_user_list');
ext.connectedHostRoutePath = '/admin/users';
@@ -674,6 +678,27 @@ describe('RouteTreePanel — 라우트↔모달/확장 연결 그룹', () => {
.find((el) => el.getAttribute('data-route-kind') === 'extension')!;
fireEvent.click(extItem);
expect(screen.getByTestId('edit-mode-probe').textContent).toBe('extension');
// 호스트 라우트(/admin/users) 강조가 유지되어야 한다 — 확장 편집에 들어가도
// "어느 화면의 확장을 고치는 중인지" 를 트리에서 잃지 않는다.
const hostRoute = screen
.getAllByTestId('g7le-route-tree-item')
.find((el) => el.getAttribute('data-route-path') === '/admin/users')!;
expect(hostRoute.getAttribute('style')).toContain('rgb(239, 246, 255)');
// 연결 그룹과 그 자식이 그대로 남아 있어야 한다. 편집 모드 진입이 트리를
// 재구성하면서 연결 목록이 비면 "클릭하니 5개가 0개가 되는" 회귀가 된다.
// (헤더 라벨은 $t: 키라 테스트 dictionary 에서 건수 파라미터가 해석되지 않으므로
// 라벨 문자열이 아니라 실제 렌더된 자식 노드 수로 판정한다.)
const connGroupAfter = screen
.getAllByTestId('g7le-route-tree-group')
.find((g) => g.getAttribute('data-route-path') === '__conngroup__/extensions//admin/users')!;
expect(connGroupAfter).toBeDefined();
expect(connGroupAfter.getAttribute('aria-expanded')).toBe('true');
const extItemsAfter = screen
.getAllByTestId('g7le-route-tree-item')
.filter((el) => el.getAttribute('data-route-kind') === 'extension');
expect(extItemsAfter).toHaveLength(1);
});
});
@@ -94,6 +94,7 @@ describe('RecipePickerControls', () => {
expect(onChange).toHaveBeenCalledWith('/board');
});
/** @effects condition_param_widget_dispatches_via_widget_registry */
it('datasource-picker 후보 select → onChange(id)', () => {
const onChange = vi.fn();
render(
@@ -152,6 +153,7 @@ describe('RecipePickerControls', () => {
describe('ActionRecipeEditor', () => {
const node: EditorNode = { name: 'Button', props: {} };
/** @effects spec_undeclared_event_hides_action_slot */
it('events 미선언 → 안내', () => {
render(<ActionRecipeEditor node={node} spec={SPEC} capability={{}} t={t} onPatchNode={vi.fn()} />);
expect(screen.getByTestId('g7le-action-no-events')).toBeInTheDocument();
@@ -212,6 +214,10 @@ describe('ActionRecipeEditor', () => {
expect(screen.getByTestId('g7le-widget-page-picker-input')).toBeInTheDocument();
});
/**
* @scenario action_recipe=openModal_lazy_id, followup_chain=none
* @effects action_recipe_does_not_expose_handler_jargon_to_user
*/
it('레시피 친화 명칭만 노출 — 핸들러 용어 없음(추가 목록 라벨)', () => {
render(<ActionRecipeEditor node={node} spec={SPEC} capability={{ events: ['onClick'] }} t={t} onPatchNode={vi.fn()} />);
fireEvent.click(screen.getByTestId('g7le-action-slot-onClick-add-picker-toggle'));
@@ -221,6 +227,10 @@ describe('ActionRecipeEditor', () => {
expect(goToPageItem.querySelector('span')?.textContent).not.toMatch(/navigate|apiCall|handler/);
});
/**
* @scenario action_recipe=callServerThen, followup_chain=none
* @effects nested_action_list_widget_assembles_recursive_actions
*/
it('callServerThen 추가 → 중첩 action-list(onSuccess) 슬롯 렌더', () => {
// 최상위 actions + type:'click'
const node2: EditorNode = { name: 'Button', actions: [{ type: 'click', handler: 'apiCall', target: 'x', onSuccess: [] }] };
@@ -231,6 +241,10 @@ describe('ActionRecipeEditor', () => {
expect(screen.getByTestId('g7le-action-slot-onClick-edit-onSuccess')).toBeInTheDocument();
});
/**
* @scenario action_recipe=custom_extension_recipe, followup_chain=success_and_error_both
* @effects action_recipe_reverse_matches_existing_action_to_recipe
*/
it('legacy props.actions 도 읽어 친화 편집 진입 (역호환) — 저장 시 최상위로 이관', () => {
const onPatch = vi.fn();
// 과거 S7 결함으로 props.actions 에 저장된 노드도 빌더가 읽어야 한다.
@@ -289,6 +303,10 @@ describe('ConditionBuilder', () => {
expect((patched as { props?: { if?: unknown } }).props?.if).toBeUndefined();
});
/**
* @scenario action_recipe=custom_extension_recipe, followup_chain=none
* @effects condition_builder_preserves_advanced_handwritten_expr
*/
it('고급식(직접 작성) → 보존 + 원문 표시', () => {
const node2: EditorNode = { name: 'Div', if: '{{ custom.weird && expr }}', props: {} };
render(<ConditionBuilder node={node2} spec={SPEC} t={t} onPatchNode={vi.fn()} />);
@@ -105,6 +105,10 @@ describe('useDevicePreview', () => {
expect(result.current.customWidth).toBe(1024);
});
/**
* @scenario preview_device=custom, custom_width_input=in_range
* @effects preview_custom_device_uses_clamped_input_width_as_override
*/
it('setCustomWidth 입력값이 custom 디바이스의 deviceWidth 로 반영', () => {
const { result } = renderHook(() => useDevicePreview(), { wrapper: wrap() });
@@ -117,7 +121,11 @@ describe('useDevicePreview', () => {
expect(result.current.customWidth).toBe(500);
});
it('setCustomWidth 는 320~1920px 범위로 클램프', () => {
/**
* @scenario preview_device=custom, custom_width_input=below_min_320
* @effects preview_custom_width_clamped_320_to_1920
*/
it('setCustomWidth 하한 미만(100) 은 320 으로 클램프', () => {
const { result } = renderHook(() => useDevicePreview(), { wrapper: wrap() });
act(() => {
@@ -125,13 +133,28 @@ describe('useDevicePreview', () => {
result.current.setCustomWidth(100); // 하한 미만
});
expect(result.current.customWidth).toBe(320);
expect(result.current.deviceWidth).toBe(320);
});
/**
* @scenario preview_device=custom, custom_width_input=above_max_1920
* @effects preview_custom_width_clamped_320_to_1920
*/
it('setCustomWidth 상한 초과(5000) 는 1920 으로 클램프', () => {
const { result } = renderHook(() => useDevicePreview(), { wrapper: wrap() });
act(() => {
result.current.setDevice('custom');
result.current.setCustomWidth(5000); // 상한 초과
});
expect(result.current.customWidth).toBe(1920);
expect(result.current.deviceWidth).toBe(1920);
});
/**
* @scenario preview_device=desktop, custom_width_input=in_range
* @effects preview_non_custom_ignores_custom_width
*/
it('custom 미선택(desktop) 상태에서는 customWidth 변경이 deviceWidth 에 영향 없음', () => {
const { result } = renderHook(() => useDevicePreview(), { wrapper: wrap() });
@@ -143,4 +166,36 @@ describe('useDevicePreview', () => {
expect(result.current.device).toBe('desktop');
expect(result.current.deviceWidth).toBe(1280);
});
/**
* @scenario preview_device=tablet, custom_width_input=in_range
* @effects preview_non_custom_ignores_custom_width
*/
it('tablet 선택 상태에서는 customWidth 변경이 deviceWidth 에 영향 없음', () => {
const { result } = renderHook(() => useDevicePreview(), { wrapper: wrap() });
act(() => {
result.current.setDevice('tablet');
result.current.setCustomWidth(500);
});
expect(result.current.device).toBe('tablet');
expect(result.current.deviceWidth).toBe(820);
});
/**
* @scenario preview_device=mobile, custom_width_input=in_range
* @effects preview_non_custom_ignores_custom_width
*/
it('mobile 선택 상태에서는 customWidth 변경이 deviceWidth 에 영향 없음', () => {
const { result } = renderHook(() => useDevicePreview(), { wrapper: wrap() });
act(() => {
result.current.setDevice('mobile');
result.current.setCustomWidth(500);
});
expect(result.current.device).toBe('mobile');
expect(result.current.deviceWidth).toBe(390);
});
});
@@ -402,6 +402,10 @@ describe('buildRouteTree — 라우트↔모달/확장 정적 연결', () => {
return group?.children?.find((c) => c.path === path);
}
/**
* @scenario connection_kind=modal, host_match=match, conn_count=many
* @effects connected_modals_attached_when_host_layout_equals_route_layout
*/
it('모달 host_layout 이 라우트 layout 과 일치하면 "이 화면의 모달" 자식 그룹 부착', () => {
const tree = buildRouteTree({
routes: [tplRoute('/admin/users', 'admin_user_list', { title: '회원 목록' })],
@@ -427,6 +431,10 @@ describe('buildRouteTree — 라우트↔모달/확장 정적 연결', () => {
expect(modalNode.connectedHostRoutePath).toBe('/admin/users');
});
/**
* @scenario connection_kind=overlay, host_match=match, conn_count=one
* @effects connected_overlay_attached_when_target_layout_equals_route_layout, connected_extensions_attached_statically_by_host_layouts_without_canvas_load
*/
it('overlay 확장 target_layout 이 라우트 layout 과 일치하면 "주입되는 확장" 자식 그룹 부착', () => {
const tree = buildRouteTree({
routes: [tplRoute('/admin/users', 'admin_user_list')],
@@ -448,6 +456,10 @@ describe('buildRouteTree — 라우트↔모달/확장 정적 연결', () => {
expect(extNode.connectedHostRoutePath).toBe('/admin/users');
});
/**
* @scenario connection_kind=extension_point, host_match=match, conn_count=one
* @effects connected_extension_point_attached_when_host_layout_in_host_layouts
*/
it('extension_point 타입도 hostLayouts 가 라우트 layout 과 일치하면 정적 부착 (클릭 불필요)', () => {
const tree = buildRouteTree({
// EP 의 hostLayouts=['shop_checkout'] 이 라우트 layout 과 일치 → 정적 부착
@@ -468,6 +480,10 @@ describe('buildRouteTree — 라우트↔모달/확장 정적 연결', () => {
expect(extNode.connectedHostRoutePath).toBe('/shop/checkout');
});
/**
* @scenario connection_kind=overlay, host_match=no_match, conn_count=zero
* @effects connected_group_omitted_when_zero_matches
*/
it('hostLayouts 에 없는 라우트에는 확장 미부착', () => {
const tree = buildRouteTree({
// header_ext 슬롯명을 layout 으로 가져도, hostLayouts 매칭이 아니면 부착 안 됨
@@ -483,6 +499,10 @@ describe('buildRouteTree — 라우트↔모달/확장 정적 연결', () => {
expect(extGroup).toBeUndefined();
});
/**
* @scenario connection_kind=modal, host_match=no_match, conn_count=zero
* @effects connected_group_omitted_when_zero_matches
*/
it('연결 모달/확장이 0건이면 연결 자식 그룹 미부착 (노이즈 방지)', () => {
const tree = buildRouteTree({
routes: [tplRoute('/admin/orphan', 'orphan_layout')],
@@ -497,6 +517,102 @@ describe('buildRouteTree — 라우트↔모달/확장 정적 연결', () => {
expect(connGroups).toHaveLength(0);
});
/**
* 같은 호스트에 overlay 가 여러 개 붙는 경우. 1건 경로만 검증하면 두 번째 확장이
* 조용히 누락돼도(첫 항목만 부착) 통과한다.
*
* @scenario connection_kind=overlay, host_match=match, conn_count=many
* @effects connected_overlay_attached_when_target_layout_equals_route_layout
*/
it('같은 라우트에 overlay 확장이 여러 개 매칭되면 모두 부착된다', () => {
const tree = buildRouteTree({
routes: [tplRoute('/admin/users', 'admin_user_list')],
modals: [],
baseLayouts: [],
extensionGroups: [
{
sourceIdentifier: 'sirsoft-board',
sourceType: 'module' as const,
sourceLabel: '게시판',
extensions: [
{ id: 10, extensionType: 'overlay' as const, targetName: 'admin_user_list', isActive: true, isModified: false, hostLayouts: ['admin_user_list'] },
{ id: 11, extensionType: 'overlay' as const, targetName: 'admin_user_list', isActive: true, isModified: false, hostLayouts: ['admin_user_list'] },
{ id: 12, extensionType: 'overlay' as const, targetName: 'other_layout', isActive: true, isModified: false, hostLayouts: ['other_layout'] },
],
},
],
moduleDisplayNames: { 'sirsoft-board': '게시판' },
pluginDisplayNames: NO_PLUGINS,
});
const route = findRouteNode(tree, '/admin/users')!;
const extGroup = route.children!.find((c) => c.path.startsWith('__conngroup__/extensions/'))!;
expect(extGroup).toBeDefined();
expect(extGroup.label).toContain('count=2'); // 매칭 2건만, 무관 확장 제외
expect(extGroup.children).toHaveLength(2);
expect(extGroup.children!.map((c) => c.extensionId).sort()).toEqual(['10', '11']);
});
/**
* @scenario connection_kind=extension_point, host_match=no_match, conn_count=zero
* @effects connected_group_omitted_when_zero_matches
*/
it('extension_point 의 hostLayouts 와 라우트 layout 이 불일치하면 미부착', () => {
const tree = buildRouteTree({
routes: [tplRoute('/admin/orders', 'admin_order_list')],
modals: [],
baseLayouts: [],
extensionGroups: [
{
sourceIdentifier: 'sirsoft-board',
sourceType: 'module' as const,
sourceLabel: '게시판',
extensions: [
{ id: 20, extensionType: 'extension_point' as const, targetName: 'header_ext', isActive: true, isModified: false, hostLayouts: ['shop_checkout'] },
],
},
],
moduleDisplayNames: { 'sirsoft-board': '게시판' },
pluginDisplayNames: NO_PLUGINS,
});
const route = findRouteNode(tree, '/admin/orders')!;
const extGroup = route.children?.find((c) => c.path.startsWith('__conngroup__/extensions/'));
expect(extGroup).toBeUndefined();
});
/**
* @scenario connection_kind=extension_point, host_match=match, conn_count=many
* @effects connected_extension_point_attached_when_host_layout_in_host_layouts
*/
it('같은 라우트에 extension_point 가 여러 개 매칭되면 모두 부착된다', () => {
const tree = buildRouteTree({
routes: [tplRoute('/shop/checkout', 'shop_checkout')],
modals: [],
baseLayouts: [],
extensionGroups: [
{
sourceIdentifier: 'sirsoft-board',
sourceType: 'module' as const,
sourceLabel: '게시판',
extensions: [
{ id: 30, extensionType: 'extension_point' as const, targetName: 'header_ext', isActive: true, isModified: false, hostLayouts: ['shop_checkout'] },
{ id: 31, extensionType: 'extension_point' as const, targetName: 'footer_ext', isActive: true, isModified: false, hostLayouts: ['shop_checkout', 'shop_cart'] },
],
},
],
moduleDisplayNames: { 'sirsoft-board': '게시판' },
pluginDisplayNames: NO_PLUGINS,
});
const route = findRouteNode(tree, '/shop/checkout')!;
const extGroup = route.children!.find((c) => c.path.startsWith('__conngroup__/extensions/'))!;
expect(extGroup).toBeDefined();
expect(extGroup.label).toContain('count=2');
expect(extGroup.children!.map((c) => c.extensionId).sort()).toEqual(['30', '31']);
});
/**
* @scenario connection_kind=modal, host_match=match, conn_count=one
* @effects connected_modals_attached_when_host_layout_equals_route_layout
*/
it('연결 그룹은 children 앞쪽 — 하위 라우트보다 먼저 배치', () => {
const tree = buildRouteTree({
routes: [
@@ -74,6 +74,7 @@ describe('합성 if 식 ↔ ConditionEvaluator 평가', () => {
expect(evalSynthesized(clauses, 'or', { _global: { currentUser: {} }, posts: { data: [] } })).toBe(false);
});
/** @effects condition_synthesized_expr_evaluates_via_condition_evaluator */
it('합성식은 정확히 단일 {{ }} 한 쌍 (중첩 보간 없음)', () => {
const expr = combineConditions(
[{ operator: 'isLoggedIn', params: {} }, { operator: 'fieldEquals', params: { field: 'a', value: 'b' } }],
@@ -74,16 +74,28 @@ describe('buildAction — 코어 핸들러 규칙 준수', () => {
const recipes = normalizeActionRecipes(RECIPES);
const byId = (id: string) => recipes.find((r) => r.id === id)!;
/**
* @scenario action_recipe=goToPage, followup_chain=none
* @effects action_recipe_build_emits_correct_handler_name_and_top_level_target, action_recipe_navigate_uses_navigate_not_nav
*/
it('goToPage → navigate (nav 아님) + path 치환', () => {
const a = buildAction(byId('goToPage'), { url: '/board' });
expect(a).toEqual({ handler: 'navigate', params: { path: '/board' } });
});
/**
* @scenario action_recipe=showMessage, followup_chain=none
* @effects action_recipe_toast_handler_not_showToast
*/
it('showMessage → toast (showToast 아님) + message/type', () => {
const a = buildAction(byId('showMessage'), { text: '저장되었습니다', tone: 'success' });
expect(a).toEqual({ handler: 'toast', params: { message: '저장되었습니다', type: 'success' } });
});
/**
* @scenario action_recipe=changeState, followup_chain=none
* @effects action_recipe_setState_target_top_level_not_in_params
*/
it('changeState → setState + target top-level (params 밖)', () => {
const a = buildAction(byId('changeState'), { key: 'activeTab', value: 'detail' });
expect(a.handler).toBe('setState');
@@ -91,11 +103,19 @@ describe('buildAction — 코어 핸들러 규칙 준수', () => {
expect(a.params).toEqual({ activeTab: 'detail' });
});
/**
* @scenario action_recipe=refreshData, followup_chain=none
* @effects action_recipe_refetchDataSource_uses_dataSourceId_key_not_id
*/
it('refreshData → refetchDataSource + dataSourceId (id 아님)', () => {
const a = buildAction(byId('refreshData'), { src: 'recent_posts' });
expect(a).toEqual({ handler: 'refetchDataSource', params: { dataSourceId: 'recent_posts' } });
});
/**
* @scenario action_recipe=callServerThen, followup_chain=success_and_error_both
* @effects action_recipe_top_level_onSuccess_onError_keys_not_in_params, action_recipe_apiCall_target_outside_params_to_avoid_resolvedTarget_undefined
*/
it('callServerThen → apiCall + target/onSuccess/onError 가 top-level', () => {
const onSuccess = [{ handler: 'toast', params: { message: 'ok' } }];
const a = buildAction(byId('callServerThen'), { endpoint: 'admin/users', onSuccess, onError: [] });
@@ -108,6 +128,7 @@ describe('buildAction — 코어 핸들러 규칙 준수', () => {
expect(a.params).toBeUndefined();
});
/** @effects nested_action_list_widget_assembles_recursive_actions */
it('중첩 action-list — onSuccess 안에 N개 액션 배열 조립', () => {
const onSuccess = [
{ handler: 'toast', params: { message: 'saved' } },
@@ -137,6 +158,7 @@ describe('assertHandlerRules — 금지 별칭 교정', () => {
warn.mockRestore();
});
/** @effects action_recipe_handler_name_follows_claude_md_critical_rules */
it('올바른 핸들러는 그대로', () => {
expect(assertHandlerRules({ handler: 'navigate' }).handler).toBe('navigate');
});
@@ -145,6 +167,7 @@ describe('assertHandlerRules — 금지 별칭 교정', () => {
describe('matchAction — 역해석', () => {
const recipes = normalizeActionRecipes(RECIPES);
/** @effects action_recipe_reverse_matches_existing_action_to_recipe */
it('navigate 액션 → goToPage 레시피 + url 복원', () => {
const m = matchAction({ handler: 'navigate', params: { path: '/board' } }, recipes);
expect(m?.recipeId).toBe('goToPage');
@@ -465,6 +488,7 @@ describe('resolveActionCard / summarizeAction / if (S10-1 보강)', () => {
expect(card.handler).toBe('customUnknown');
});
/** @effects action_recipe_does_not_expose_handler_jargon_to_user */
it('summarizeAction — 라벨 + 주요 입력값 (핸들러명 미노출)', () => {
const recipe = recipes.find((r) => r.id === 'goToPage')!;
const t = (k: string) => (k === '$t:editor.action.go_to_page.label' ? '페이지 이동' : k);
@@ -50,11 +50,13 @@ describe('buildClauseExpr — {paramKey} 치환', () => {
expect(buildClauseExpr({ operator: 'isLoggedIn', params: {} }, ops)).toBe('_global?.currentUser?.uuid');
});
/** @effects condition_recipe_array_length_uses_length_nullish_zero_fallback */
it('{src} 치환 — 옵셔널 체이닝 + 배열 길이 ?? 0 형태 보존', () => {
const e = buildClauseExpr({ operator: 'dsHasData', params: { src: 'posts' } }, ops);
expect(e).toBe('(posts?.data?.length ?? 0) > 0');
});
/** @effects condition_recipe_substitutes_params_into_expr_template */
it('{field}/{value} 치환', () => {
const e = buildClauseExpr({ operator: 'fieldEquals', params: { field: 'status', value: 'open' } }, ops);
expect(e).toBe("status === 'open'");
@@ -71,6 +73,7 @@ describe('combineConditions — 단일 {{ }} 합성 (코어 if 규칙)', () => {
expect(r).toBe('{{ _global?.currentUser?.uuid }}');
});
/** @effects condition_recipe_wraps_entire_combined_expression_in_single_braces */
it('AND 결합 — 각 절 괄호 + && + 전체 한 쌍 {{ }}', () => {
const r = combineConditions(
[{ operator: 'isLoggedIn', params: {} }, { operator: 'dsHasData', params: { src: 'posts' } }],
@@ -89,6 +92,7 @@ describe('combineConditions — 단일 {{ }} 합성 (코어 if 규칙)', () => {
expect(r).toBe('{{ (_global?.currentUser?.uuid) || (!_global?.currentUser?.uuid) }}');
});
/** @effects condition_builder_does_not_emit_nested_interpolation_braces */
it('중첩 보간 {{ {{x}} }} 를 만들지 않는다', () => {
const r = combineConditions(
[{ operator: 'fieldEquals', params: { field: 'a', value: 'b' } }, { operator: 'isLoggedIn', params: {} }],
@@ -104,6 +108,7 @@ describe('combineConditions — 단일 {{ }} 합성 (코어 if 규칙)', () => {
expect(combineConditions([], 'and', ops)).toBe('');
});
/** @effects condition_recipe_uses_optional_chaining_for_null_safety */
it('fieldHasError — 옵셔널 체이닝 인덱스 접근 보존', () => {
const r = combineConditions([{ operator: 'fieldHasError', params: { field: 'email' } }], 'and', ops);
expect(r).toBe("{{ !!_local?.errors?.['email'] }}");
@@ -111,6 +116,7 @@ describe('combineConditions — 단일 {{ }} 합성 (코어 if 규칙)', () => {
});
describe('matchSinglePreset — 역해석', () => {
/** @effects condition_builder_reverse_matches_single_preset */
it('파라미터 없는 단일 프리셋 식 → operator 복원', () => {
expect(matchSinglePreset('{{ _global?.currentUser?.uuid }}', ops)).toBe('isLoggedIn');
expect(matchSinglePreset('{{_global?.currentUser?.uuid}}', ops)).toBe('isLoggedIn');
@@ -163,6 +169,7 @@ describe('parseConditionExpr — 라운드트립 역해석 (modal remount 무상
expect(r).toEqual({ clauses, combinator: 'or' });
});
/** @effects condition_builder_preserves_advanced_handwritten_expr */
it('손작성 임의 식 → null (고급 취급)', () => {
expect(parseConditionExpr('{{ custom.weird && thing }}', ops)).toBeNull();
expect(parseConditionExpr('', ops)).toBeNull();
@@ -2,8 +2,8 @@
* editorClipboardAndShortcuts.test.tsx — 클립보드 버퍼 + 단축키 디스패처 + 단축키 맵 모달
*
*
* @scenario shortcut_clipboard + shortcut_dispatch + shortcut_help_modal
* @effects clipboard_session_roundtrip_strips_internal_meta, clipboard_read_returns_fresh_copy, shortcut_dispatch_guards_input_and_modal, shortcut_escape_branches_deselect_vs_exit_by_selection, shortcut_requires_selection_guard, shortcut_help_modal_lists_all_groups_from_ssot, paste_across_layouts_via_session_storage
* 축 요약(마커 아님 — 평문): shortcut_clipboard, shortcut_dispatch, shortcut_help_modal.
* 효과 요약(마커 아님 — 평문): clipboard_session_roundtrip_strips_internal_meta, clipboard_read_returns_fresh_copy, shortcut_dispatch_guards_input_and_modal, shortcut_escape_branches_deselect_vs_exit_by_selection, shortcut_requires_selection_guard, shortcut_help_modal_lists_all_groups_from_ssot, paste_across_layouts_via_session_storage.
* @since engine-v1.50.0
*/
@@ -21,6 +21,7 @@ afterEach(() => { cleanup(); clearClipboard(); });
beforeEach(() => clearClipboard());
describe('editorClipboard — sessionStorage round-trip', () => {
/** @effects clipboard_session_roundtrip_strips_internal_meta */
it('write→read 복원 + 내부 메타(__source) 제거', () => {
const node: EditorNode = { type: 'basic', name: 'Div', __source: { kind: 'extension' } as never, children: [{ type: 'basic', name: 'Span', text: 'x', __source: {} as never }] };
expect(writeClipboard(node)).toBe(true);
@@ -32,6 +33,7 @@ describe('editorClipboard — sessionStorage round-trip', () => {
expect((out.children as EditorNode[])[0].text).toBe('x');
});
/** @effects clipboard_read_returns_fresh_copy */
it('read 는 매번 새 복제본(연속 붙여넣기 안전)', () => {
writeClipboard({ type: 'basic', name: 'Div' });
const a = readClipboard();
@@ -45,6 +47,7 @@ describe('editorClipboard — sessionStorage round-trip', () => {
expect(hasClipboard()).toBe(false);
});
/** @effects paste_across_layouts_via_session_storage */
it('다른 레이아웃 시뮬레이션 — write 후 (네비게이션 가정) read 가능', () => {
writeClipboard({ type: 'basic', name: 'Button', text: '버튼' });
// sessionStorage 는 네비게이션/리렌더에 무관하게 유지 → read 성공.
@@ -70,6 +73,7 @@ describe('useEditorShortcuts — 디스패치/가드', () => {
expect(copy).toHaveBeenCalledTimes(1);
});
/** @effects shortcut_dispatch_guards_input_and_modal */
it('입력칸 포커스 시 가로채지 않음', () => {
const copy = vi.fn();
setup({ copy }, true);
@@ -80,6 +84,7 @@ describe('useEditorShortcuts — 디스패치/가드', () => {
input.remove();
});
/** @effects shortcut_dispatch_guards_input_and_modal */
it('모달 열림 시 가로채지 않음', () => {
const copy = vi.fn();
setup({ copy }, true);
@@ -91,6 +96,7 @@ describe('useEditorShortcuts — 디스패치/가드', () => {
backdrop.remove();
});
/** @effects shortcut_requires_selection_guard */
it('requiresSelection: 선택 없으면 copy 무시', () => {
const copy = vi.fn();
setup({ copy }, false);
@@ -98,6 +104,7 @@ describe('useEditorShortcuts — 디스패치/가드', () => {
expect(copy).not.toHaveBeenCalled();
});
/** @effects shortcut_escape_branches_deselect_vs_exit_by_selection */
it('Escape: 선택 있으면 deselect, 없으면 exit', () => {
const deselect = vi.fn();
const { unmount } = setup({ deselect }, true);
@@ -119,6 +126,7 @@ describe('useEditorShortcuts — 디스패치/가드', () => {
});
describe('ShortcutHelpModal — SSoT 기반 렌더', () => {
/** @effects shortcut_help_modal_lists_all_groups_from_ssot */
it('모든 그룹 + 대표 액션 행 렌더(키맵 SSoT)', () => {
render(<ShortcutHelpModal t={t} onClose={vi.fn()} isMac={false} />);
expect(screen.getByTestId('g7le-shortcut-group-clipboard')).toBeTruthy();
@@ -53,6 +53,7 @@ describe('isRenderedAsFlex — computed style 기반(className 토큰 아님)',
});
describe('isNodeFlexEnabled — 노드 파생(enable 컨트롤 역해석)', () => {
/** @effects flex_auto_detection_works_across_tailwind_bootstrap_native_css */
it('className 에 flex 토큰 있으면 true', () => {
expect(isNodeFlexEnabled({ props: { className: 'w-full flex gap-2' } }, ENABLE_CONTROL)).toBe(true);
});
@@ -93,9 +94,11 @@ describe('isNodeFlexEnabled — 노드 파생(enable 컨트롤 역해석)', () =
});
describe('resolveFlexContainerMode', () => {
/** @effects flex_container_classToken_emits_per_spec_apply_type */
it('container → 항상 컨테이너 컨트롤(해제 버튼 없음)', () => {
expect(resolveFlexContainerMode('container', null)).toEqual({ showContainer: true, showEnableButton: false, showDisableButton: false });
});
/** @effects flex_item_align_self_emits_correct_recipe, flex_item_order_property_set */
it('item → 컨테이너 컨트롤 비노출', () => {
expect(resolveFlexContainerMode('item', null)).toEqual({ showContainer: false, showEnableButton: false, showDisableButton: false });
});
@@ -108,6 +111,7 @@ describe('resolveFlexContainerMode', () => {
showDisableButton: true,
});
});
/** @effects flex_make_box_button_when_not_rendered_as_flex */
it('auto + 노드 파생 비flex(enable 컨트롤 있음) → "정렬 박스로 만들기" 버튼만', () => {
// el 이 flex 로 보여도(패치 직후 stale 가능) 노드 파생이 우선이므로 enable 버튼.
vi.spyOn(window, 'getComputedStyle').mockReturnValue({ display: 'flex' } as CSSStyleDeclaration);
@@ -117,6 +121,7 @@ describe('resolveFlexContainerMode', () => {
showDisableButton: false,
});
});
/** @effects flex_auto_detection_uses_computed_style_not_classname */
it('auto + enable 컨트롤 없음 → computed style 폴백(flex)', () => {
vi.spyOn(window, 'getComputedStyle').mockReturnValue({ display: 'flex' } as CSSStyleDeclaration);
expect(resolveFlexContainerMode('auto', document.createElement('div'), false, false)).toEqual({
@@ -30,11 +30,13 @@ function overlaps(
}
describe('resolveAffordancePlacement', () => {
/** @effects overlay_affordances_inside_when_box_ge_44 */
it('임계값(44px) 이상의 큰 박스는 inside 배치', () => {
expect(resolveAffordancePlacement(box(200, 100))).toBe('inside');
expect(resolveAffordancePlacement(box(44, 44))).toBe('inside');
});
/** @effects overlay_affordances_outside_when_box_lt_44_no_overlap */
it('width 가 임계값 미만이면 outside 배치 (겹침 회피)', () => {
expect(resolveAffordancePlacement(box(20, 100))).toBe('outside');
});
@@ -92,6 +94,7 @@ describe('resolveInsertionCrossOffsets', () => {
expect(-push - half + INSERTION_AFFORDANCE_BUTTON).toBe(-gap); // 버튼 하단 = -gap
});
/** @effects insertion_affordances_cross_layout_when_box_lt_44_no_overlap_no_clip */
it('네 버튼은 서로 겹치지 않는다 (작은 6×20 박스)', () => {
const c = resolveInsertionCrossOffsets(box(6, 20));
const dirs = ['above', 'below', 'left', 'right'] as const;
+1
View File
@@ -49,6 +49,7 @@
bundleUrls: @json($bundleUrls ?? null),
activeModules: @json($activeModulesMeta ?? []),
activePlugins: @json($activePluginsMeta ?? []),
trustedScriptHosts: @json($trustedScriptHosts ?? []),
appConfig: @json($appConfig ?? []),
// 레이아웃 편집기 lazy 번들 URL — `/admin/layout-editor/*` 진입 시에만 런타임
// <script> 주입으로 로드된다(초기 접속 payload 에 미포함). filemtime 캐시버스팅,
+1
View File
@@ -49,6 +49,7 @@
bundleUrls: @json($bundleUrls ?? null),
activeModules: @json($activeModulesMeta ?? []),
activePlugins: @json($activePluginsMeta ?? []),
trustedScriptHosts: @json($trustedScriptHosts ?? []),
appConfig: @json($appConfig ?? []),
// 레이아웃 편집기 lazy 번들 URL — `/admin/layout-editor/*` 진입 시에만 런타임
// <script> 주입으로 로드된다(초기 접속 payload 에 미포함). filemtime 캐시버스팅,