fix(core,extensions): 동적 스크립트 주입 경로 전부에 출처 게이트 적용
레이아웃 scripts[] 에만 있던 원격 스크립트 차단 게이트가 다른 주입 경로에는 없어, 저장측(SafeLayoutExpressions·NoExternalUrls)이 외부 URL 저장을 422 로 막아도 런타임 디스패치 한 번으로 임의 원격 코드가 로드됐다. 저장 검증이 통째로 무의미해지는 상태였고 오류도 경고도 남지 않았다. 판정식을 support/scriptSrcPolicy.ts 로 분리해 런타임 SSoT 를 하나로 두고, loadScript 액션 · 확장 핸들러 재로드 · 편집기 프리뷰 · 편집기 자산 매니페스트 · G7Core.asset.loadScript · PG 플러그인 SDK 주입이 모두 그것을 경유하게 했다. 사본을 두지 않은 이유는 차집합이 그대로 우회로가 되기 때문이다. - 게이트는 캐시 검사보다 앞에 둔다 (뒤에 두면 이미 로드된 미신뢰 스크립트가 캐시 히트로 통과한다) - NoExternalUrls 순회를 9키로 확대 — 번들 레이아웃 601개 사전 스캔으로 정당한 외부 URL 0건을 확인한 뒤 넓혔다 (저장 회귀 없음) - callExternal 은 생성자를 참조 동일성으로 거부하고(별칭 전역 포함), 프로토타입 경로 세그먼트를 읽기·매핑 키 양쪽에서 차단한다 - PG SDK 는 서비스 SDK 라 자체 호스팅이 불가능하므로 manifest 선언 + 주입 직전 호스트 확인이 게이트다. tosspayments SDK URL 은 확장자가 없어 정적 검사에 걸리지 않아 그 런타임 확인이 유일한 게이트다 - 함께 드러난 결함: 동시 loadScript 가 로드 전에 완료 처리되던 문제, 확장 재로드에서 script 기존재가 CSS 까지 건너뛰던 문제, loadCSS 의 in-flight 미공유
This commit is contained in:
1 parent
621cd28376
commit
1e89335258
82 files changed
+2706
-240
No files matched your search
@@ -39,6 +39,12 @@ import {
|
||||
import { notifyAssetFailure, clearAssetFailure } from './assets/AssetFailureNotice';
|
||||
import { suffixed, extStaticUrl, convertToCurrentMode } from './support/assetUrl';
|
||||
import { fetchStaticFirst } from './support/fetchStaticFirst';
|
||||
import {
|
||||
normalizeScriptSrcForOriginCheck as normalizeScriptSrcForOriginCheckImpl,
|
||||
extractScriptHost as extractScriptHostImpl,
|
||||
getTrustedScriptHosts as getTrustedScriptHostsImpl,
|
||||
isAllowedScriptSrc as isAllowedScriptSrcImpl,
|
||||
} from './support/scriptSrcPolicy';
|
||||
import { resetLocalInitTracking } from './template-engine/localInitSlot';
|
||||
/**
|
||||
* DevTools 추적 - G7DevToolsCore.getInstance() 직접 호출 대신 G7Core.devTools를 사용합니다.
|
||||
@@ -2167,35 +2173,15 @@ export class TemplateApp {
|
||||
* (cdn.ckeditor.com), Daum 우편번호(t1.daumcdn.net).
|
||||
* 차단: 그 외 `//`(protocol-relative)·scheme 포함 외부 origin(미선언 원격 코드 로드).
|
||||
*
|
||||
* 판정식 자체는 `support/scriptSrcPolicy` 가 SSoT 다 — 같은 판정을 쓰는 주입 경로가
|
||||
* 레이아웃 `scripts[]` 말고도 여럿(loadScript 액션·확장 핸들러 재로드·편집기 프리뷰·
|
||||
* `G7Core.asset.loadScript`)이라, 사본이 생기면 그 차집합이 우회로가 된다.
|
||||
*
|
||||
* @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);
|
||||
return isAllowedScriptSrcImpl(src);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2211,22 +2197,15 @@ export class TemplateApp {
|
||||
* 않으므로 그대로 same-origin 으로 통과합니다(과차단 없음).
|
||||
*
|
||||
* 저장측 `SafeLayoutExpressions::normalizeForOriginCheck` · 정적 검사
|
||||
* `layout-scripts-src-same-origin` 과 3층 동형이어야 합니다.
|
||||
* `layout-scripts-src-same-origin` 과 3층 동형이어야 합니다. 구현은
|
||||
* `support/scriptSrcPolicy` 가 SSoT 이며 이 메서드는 위임입니다.
|
||||
*
|
||||
* @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//');
|
||||
return normalizeScriptSrcForOriginCheckImpl(src);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2239,20 +2218,7 @@ export class TemplateApp {
|
||||
* @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;
|
||||
}
|
||||
return extractScriptHostImpl(src);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2261,11 +2227,7 @@ export class TemplateApp {
|
||||
* @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())
|
||||
: [];
|
||||
return getTrustedScriptHostsImpl();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1653,6 +1653,46 @@ describe('G7CoreGlobals - 자산 API', () => {
|
||||
expect(typeof G7Core.asset.loadStylesheet).toBe('function');
|
||||
});
|
||||
|
||||
describe('loadScript 출처 게이트', () => {
|
||||
/**
|
||||
* @effects untrusted_external_script_blocked
|
||||
*/
|
||||
it('미신뢰 외부 URL 은 reject 된다', async () => {
|
||||
await expect(G7Core.asset.loadScript('https://cdn.evil.com/x.js')).rejects.toThrow(
|
||||
/Blocked untrusted script src/
|
||||
);
|
||||
});
|
||||
|
||||
it('authority 우회 형태도 reject 된다', async () => {
|
||||
await expect(G7Core.asset.loadScript('/\\/evil.com/x.js')).rejects.toThrow(
|
||||
/Blocked untrusted script src/
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* @effects trusted_script_host_allowlist_wired
|
||||
*/
|
||||
it('same-origin 경로와 선언된 신뢰 호스트는 게이트를 통과한다', () => {
|
||||
(window as any).G7Config.trustedScriptHosts = ['t1.daumcdn.net'];
|
||||
|
||||
// 실제 네트워크를 타지 않도록 로드는 즉시 실패시키고, 게이트 통과 여부만 본다
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
queueMicrotask(() => node.onerror?.(new Event('error')));
|
||||
return node;
|
||||
}) as any);
|
||||
|
||||
expect(G7Core.asset.isAllowedScriptSrc('/api/plugins/assets/x/dist/a.js')).toBe(true);
|
||||
expect(G7Core.asset.isAllowedScriptSrc('//t1.daumcdn.net/postcode.v2.js')).toBe(true);
|
||||
expect(G7Core.asset.isAllowedScriptSrc('https://cdn.evil.com/x.js')).toBe(false);
|
||||
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('판정 함수를 공개 seam 으로 노출한다 (로더를 못 쓰는 주입용)', () => {
|
||||
expect(typeof G7Core.asset.isAllowedScriptSrc).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* @scenario asset_class=vendored, outcome=failed
|
||||
* @effects failed_asset_shows_retry_notice
|
||||
|
||||
@@ -397,6 +397,15 @@ export class ModuleAssetLoader {
|
||||
/**
|
||||
* CSS 파일을 동적으로 로드합니다.
|
||||
*
|
||||
* `loadJS`·`loadBundleJs` 와 같이 in-flight Promise 를 공유한다 — CSS 경로만 이
|
||||
* 계층이 없어서, 같은 확장의 CSS 를 동시에 요청하면 `<link>` 가 중복 생성되고
|
||||
* 재시도 로더가 기존 element 를 제거하면서 서로의 시도를 지웠다.
|
||||
*
|
||||
* 키는 `module-css-{id}` 로 둔다 — `loadJS` 가 raw identifier 를 키로 쓰므로,
|
||||
* 같은 키공간을 쓰면 JS 로드가 CSS 로드로 오인되어 조용히 건너뛰어진다.
|
||||
*
|
||||
* 실패해도 throw 하지 않는 기존 계약을 유지한다(`surfaceCssFailure`).
|
||||
*
|
||||
* @param identifier 모듈 식별자
|
||||
* @param url CSS 파일 URL
|
||||
*/
|
||||
@@ -409,18 +418,31 @@ export class ModuleAssetLoader {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await loadStylesheetWithRetry(url, { id: elementId }, { label: `CSS: ${identifier}` });
|
||||
|
||||
logger.log(`CSS loaded: ${identifier}`);
|
||||
|
||||
const link = document.getElementById(elementId);
|
||||
if (link) {
|
||||
this.registerLoadedAsset(identifier, { type: 'css', element: link });
|
||||
}
|
||||
} catch (error) {
|
||||
this.surfaceCssFailure(identifier, identifier, url, error);
|
||||
// 이미 로딩 중인 경우 대기 (JS 키공간과 겹치지 않는 elementId 를 키로 쓴다)
|
||||
const existingPromise = this.loadingPromises.get(elementId);
|
||||
if (existingPromise) {
|
||||
logger.log(`CSS already loading: ${identifier}`);
|
||||
return existingPromise;
|
||||
}
|
||||
|
||||
const loadPromise = loadStylesheetWithRetry(url, { id: elementId }, { label: `CSS: ${identifier}` })
|
||||
.then(() => {
|
||||
logger.log(`CSS loaded: ${identifier}`);
|
||||
|
||||
const link = document.getElementById(elementId);
|
||||
if (link) {
|
||||
this.registerLoadedAsset(identifier, { type: 'css', element: link });
|
||||
}
|
||||
this.loadingPromises.delete(elementId);
|
||||
})
|
||||
.catch((error) => {
|
||||
this.loadingPromises.delete(elementId);
|
||||
this.surfaceCssFailure(identifier, identifier, url, error);
|
||||
});
|
||||
|
||||
this.loadingPromises.set(elementId, loadPromise);
|
||||
|
||||
return loadPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -479,4 +479,63 @@ describe('ModuleAssetLoader', () => {
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadCSS in-flight Promise 공유', () => {
|
||||
/**
|
||||
* appendChild 를 가로채 생성된 element 를 모으고 즉시 load 를 발화시킨다.
|
||||
*
|
||||
* @return 생성된 element 목록
|
||||
*/
|
||||
function stubStylesheetLoading(): HTMLElement[] {
|
||||
const created: HTMLElement[] = [];
|
||||
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName === 'LINK' || node.tagName === 'SCRIPT') {
|
||||
created.push(node);
|
||||
document.body.appendChild(node);
|
||||
queueMicrotask(() => node.onload?.(new Event('load')));
|
||||
}
|
||||
return node;
|
||||
}) as any);
|
||||
|
||||
return created;
|
||||
}
|
||||
|
||||
it('같은 확장 CSS 동시 2회 → link 1개만 생성된다', async () => {
|
||||
const created = stubStylesheetLoading();
|
||||
|
||||
await Promise.all([
|
||||
(loader as any).loadCSS('vendor-ext', '/api/modules/x.css'),
|
||||
(loader as any).loadCSS('vendor-ext', '/api/modules/x.css'),
|
||||
]);
|
||||
|
||||
expect(created.filter(el => el.tagName === 'LINK')).toHaveLength(1);
|
||||
expect(document.getElementById('module-css-vendor-ext')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('CSS 로드 실패는 여전히 throw 하지 않는다 (no-throw 계약 유지)', async () => {
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName === 'LINK') {
|
||||
document.body.appendChild(node);
|
||||
queueMicrotask(() => node.onerror?.(new Event('error')));
|
||||
}
|
||||
return node;
|
||||
}) as any);
|
||||
|
||||
await expect(
|
||||
(loader as any).loadCSS('vendor-fail', '/api/modules/x.css')
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('CSS in-flight 키는 JS 키공간과 겹치지 않는다', async () => {
|
||||
stubStylesheetLoading();
|
||||
|
||||
const pending = (loader as any).loadCSS('vendor-ext', '/api/modules/x.css');
|
||||
|
||||
expect((loader as any).loadingPromises.has('module-css-vendor-ext')).toBe(true);
|
||||
expect((loader as any).loadingPromises.has('vendor-ext')).toBe(false);
|
||||
|
||||
await pending;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* 동적 스크립트 주입 출처 정책 (support/scriptSrcPolicy) 단위 테스트.
|
||||
*
|
||||
* `docs/frontend/security.md` "same-origin 판정은 브라우저 URL 파서와 같아야 한다" 의
|
||||
* 우회 표 전 케이스를 고정한다. 이 판정은 레이아웃 `scripts[]` 뿐 아니라 loadScript
|
||||
* 액션·확장 핸들러 재로드·편집기 프리뷰·`G7Core.asset.loadScript` 가 공유하므로,
|
||||
* 여기서 뚫리면 그 모든 주입 경로가 같이 뚫린다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import {
|
||||
normalizeScriptSrcForOriginCheck,
|
||||
extractScriptHost,
|
||||
getTrustedScriptHosts,
|
||||
isAllowedScriptSrc,
|
||||
} from '../scriptSrcPolicy';
|
||||
|
||||
describe('scriptSrcPolicy', () => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: {
|
||||
href: 'https://g7.test/',
|
||||
origin: 'https://g7.test',
|
||||
protocol: 'https:',
|
||||
pathname: '/',
|
||||
search: '',
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).G7Config;
|
||||
});
|
||||
|
||||
describe('normalizeScriptSrcForOriginCheck', () => {
|
||||
it('tab/LF/CR 를 제거한다', () => {
|
||||
expect(normalizeScriptSrcForOriginCheck('/\t/evil.com/x.js')).toBe('//evil.com/x.js');
|
||||
expect(normalizeScriptSrcForOriginCheck('/\n/evil.com/x.js')).toBe('//evil.com/x.js');
|
||||
expect(normalizeScriptSrcForOriginCheck('/\r/evil.com/x.js')).toBe('//evil.com/x.js');
|
||||
});
|
||||
|
||||
it('백슬래시를 슬래시로 바꾼다', () => {
|
||||
expect(normalizeScriptSrcForOriginCheck('/\\/evil.com/x.js')).toBe('//evil.com/x.js');
|
||||
expect(normalizeScriptSrcForOriginCheck('/\\evil.com/x.js')).toBe('//evil.com/x.js');
|
||||
});
|
||||
|
||||
it('선행 슬래시 런을 접는다 (scheme 유무 모두)', () => {
|
||||
expect(normalizeScriptSrcForOriginCheck('///evil.com/x.js')).toBe('//evil.com/x.js');
|
||||
expect(normalizeScriptSrcForOriginCheck('https:///evil.com/x.js')).toBe(
|
||||
'https://evil.com/x.js'
|
||||
);
|
||||
});
|
||||
|
||||
it('경로 중간의 연속 슬래시는 건드리지 않는다 (과차단 방지)', () => {
|
||||
expect(normalizeScriptSrcForOriginCheck('/js//a.js')).toBe('/js//a.js');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractScriptHost', () => {
|
||||
it('protocol-relative 와 절대 URL 의 호스트를 소문자로 돌려준다', () => {
|
||||
expect(extractScriptHost('//CDN.Example.com/x.js')).toBe('cdn.example.com');
|
||||
expect(extractScriptHost('https://CDN.Example.com/x.js')).toBe('cdn.example.com');
|
||||
});
|
||||
|
||||
it('http/https 가 아닌 scheme 은 null', () => {
|
||||
expect(extractScriptHost('javascript:alert(1)')).toBeNull();
|
||||
expect(extractScriptHost('data:text/javascript,alert(1)')).toBeNull();
|
||||
});
|
||||
|
||||
it('same-origin 경로는 문서 origin 의 호스트로 해석된다', () => {
|
||||
expect(extractScriptHost('/api/widget.js')).toBe('g7.test');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTrustedScriptHosts', () => {
|
||||
it('G7Config 미설정 시 빈 배열', () => {
|
||||
expect(getTrustedScriptHosts()).toEqual([]);
|
||||
});
|
||||
|
||||
it('배열이 아니면 빈 배열', () => {
|
||||
(window as any).G7Config = { trustedScriptHosts: 'cdn.example.com' };
|
||||
expect(getTrustedScriptHosts()).toEqual([]);
|
||||
});
|
||||
|
||||
it('소문자로 정규화해 돌려준다', () => {
|
||||
(window as any).G7Config = { trustedScriptHosts: ['CDN.Example.com'] };
|
||||
expect(getTrustedScriptHosts()).toEqual(['cdn.example.com']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isAllowedScriptSrc — security.md 우회 표', () => {
|
||||
/** @effects trusted_script_host_allowlist_wired */
|
||||
it('same-origin 절대 경로는 허용', () => {
|
||||
expect(isAllowedScriptSrc('/api/widget.js', [])).toBe(true);
|
||||
});
|
||||
|
||||
/** @effects untrusted_external_script_blocked */
|
||||
it('protocol-relative 외부 origin 은 차단', () => {
|
||||
expect(isAllowedScriptSrc('//evil.com/x.js', [])).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['/\\/evil.com/x.js'],
|
||||
['/\\evil.com/x.js'],
|
||||
['/\t/evil.com/x.js'],
|
||||
['///evil.com/x.js'],
|
||||
])('authority 우회 형태 %s 는 차단 (@effects untrusted_external_script_blocked)', src => {
|
||||
expect(isAllowedScriptSrc(src, [])).toBe(false);
|
||||
});
|
||||
|
||||
it('신뢰 호스트를 우회 형태로 쓴 것은 허용 (과차단 방지)', () => {
|
||||
expect(isAllowedScriptSrc('/\\/cdn.trusted.com/x.js', ['cdn.trusted.com'])).toBe(true);
|
||||
});
|
||||
|
||||
it('경로 중간 백슬래시는 same-origin 으로 통과 (과차단 방지)', () => {
|
||||
expect(isAllowedScriptSrc('/js/a\\b.js', [])).toBe(true);
|
||||
});
|
||||
|
||||
it('userinfo 자리에 신뢰 호스트를 끼운 주소는 실제 호스트로 판정한다', () => {
|
||||
expect(
|
||||
isAllowedScriptSrc('https://evil.com\\@cdn.trusted.com/x.js', ['cdn.trusted.com'])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
/** @effects trusted_script_host_allowlist_wired */
|
||||
it('신뢰 호스트는 허용 (protocol-relative / https 양쪽)', () => {
|
||||
expect(isAllowedScriptSrc('//cdn.trusted.com/x.js', ['cdn.trusted.com'])).toBe(true);
|
||||
expect(isAllowedScriptSrc('https://cdn.trusted.com/x.js', ['cdn.trusted.com'])).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('신뢰 호스트 비교는 대소문자를 무시한다', () => {
|
||||
expect(isAllowedScriptSrc('https://CDN.Trusted.com/x.js', ['cdn.trusted.com'])).toBe(
|
||||
true
|
||||
);
|
||||
expect(isAllowedScriptSrc('https://cdn.trusted.com/x.js', ['CDN.Trusted.com'])).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('javascript:/data: scheme 은 차단', () => {
|
||||
expect(isAllowedScriptSrc('javascript:alert(1)', [])).toBe(false);
|
||||
expect(isAllowedScriptSrc('data:text/javascript,alert(1)', [])).toBe(false);
|
||||
});
|
||||
|
||||
it('빈 값·비문자열은 차단', () => {
|
||||
expect(isAllowedScriptSrc('', [])).toBe(false);
|
||||
expect(isAllowedScriptSrc(' ', [])).toBe(false);
|
||||
expect(isAllowedScriptSrc(undefined as any, [])).toBe(false);
|
||||
});
|
||||
|
||||
it('상대 경로(`/` 미시작)는 차단', () => {
|
||||
expect(isAllowedScriptSrc('js/widget.js', [])).toBe(false);
|
||||
});
|
||||
|
||||
it('인자 생략 시 window.G7Config.trustedScriptHosts 를 읽는다', () => {
|
||||
(window as any).G7Config = { trustedScriptHosts: ['cdn.trusted.com'] };
|
||||
expect(isAllowedScriptSrc('https://cdn.trusted.com/x.js')).toBe(true);
|
||||
expect(isAllowedScriptSrc('https://evil.com/x.js')).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* 동적 스크립트 주입 출처 정책 (프론트측 SSoT).
|
||||
*
|
||||
* 브라우저에 새 `<script>` 를 만들어 붙이는 모든 경로는 이 모듈의 판정을 경유한다.
|
||||
* 레이아웃 `scripts[]`(TemplateApp) 뿐 아니라 `loadScript` 액션 · 확장 핸들러 재로드 ·
|
||||
* 편집기 프리뷰 · `G7Core.asset.loadScript` 공개 seam 이 같은 판정을 쓴다.
|
||||
*
|
||||
* ## 허용 규칙
|
||||
*
|
||||
* 1. `/` 로 시작하는 same-origin 절대 경로.
|
||||
* 2. 확장이 manifest(`trusted_script_hosts`)로 선언한 신뢰 호스트에 속한 외부 스크립트
|
||||
* — 코어가 집계해 `window.G7Config.trustedScriptHosts` 로 노출한다.
|
||||
*
|
||||
* 그 외(`//` protocol-relative · scheme 포함 외부 origin)는 미선언 원격 코드 로드 경로다.
|
||||
*
|
||||
* ## 3층 동형
|
||||
*
|
||||
* 저장측 `App\Rules\SafeLayoutExpressions::normalizeForOriginCheck` · 정적 검사
|
||||
* `layout-scripts-src-same-origin` 과 **같은 정규화**를 공유해야 한다. 한 층만 바뀌면
|
||||
* 그 차집합이 그대로 우회로가 된다 (KVE-2026-1915 B-2).
|
||||
*
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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 으로 통과합니다(과차단 없음).
|
||||
*
|
||||
* @param src 원본 src 문자열
|
||||
* @returns 정규화된 src
|
||||
*/
|
||||
export function 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`)는 브라우저도 경로로 두므로 건드리지 않는다.
|
||||
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 문자열 (정규화된 값을 넘길 것)
|
||||
* @param baseOrigin 상대 경로 해석 기준 origin (기본: 현재 문서 origin)
|
||||
* @returns 소문자 호스트명 (판정 불가 시 null)
|
||||
*/
|
||||
export function extractScriptHost(src: string, baseOrigin?: string): string | null {
|
||||
try {
|
||||
// protocol/origin 이 비어 있을 수 있다 (테스트 하네스가 location 을 교체한 경우 등).
|
||||
// 그때 빈 문자열을 그대로 이어 붙이면 `//host` 가 파싱 불가가 되어 호스트 추출이
|
||||
// null 로 떨어지고, protocol-relative 로 적은 **신뢰 호스트가 조용히 차단**된다.
|
||||
const protocol =
|
||||
(typeof window !== 'undefined' && window.location?.protocol) || 'https:';
|
||||
const base =
|
||||
baseOrigin ||
|
||||
(typeof window !== 'undefined' ? window.location?.origin : undefined) ||
|
||||
'https://localhost';
|
||||
|
||||
const normalized = src.startsWith('//') ? `${protocol}${src}` : src;
|
||||
const url = new URL(normalized, base);
|
||||
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return url.hostname.toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어가 집계해 노출한 신뢰 외부 스크립트 호스트 목록을 반환합니다.
|
||||
*
|
||||
* @returns 소문자 호스트명 배열 (window.G7Config.trustedScriptHosts)
|
||||
*/
|
||||
export function getTrustedScriptHosts(): string[] {
|
||||
const hosts =
|
||||
typeof window !== 'undefined'
|
||||
? (window as any).G7Config?.trustedScriptHosts
|
||||
: undefined;
|
||||
|
||||
return Array.isArray(hosts)
|
||||
? hosts.map((host: unknown) => String(host).toLowerCase())
|
||||
: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 스크립트 src 가 주입 허용 대상인지 판정합니다.
|
||||
*
|
||||
* @param src 스크립트 src 문자열
|
||||
* @param trustedHosts 신뢰 호스트 목록 (생략 시 `getTrustedScriptHosts()`)
|
||||
* @returns 주입 허용이면 true
|
||||
*/
|
||||
export function isAllowedScriptSrc(src: string, trustedHosts?: readonly string[]): boolean {
|
||||
if (typeof src !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const trimmed = src.trim();
|
||||
|
||||
if (trimmed === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 접두 검사 전에 브라우저 URL 파서와 동일하게 정규화한다
|
||||
const normalized = 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 = extractScriptHost(normalized);
|
||||
const hosts = trustedHosts ?? getTrustedScriptHosts();
|
||||
|
||||
return host !== null && hosts.map(h => String(h).toLowerCase()).includes(host);
|
||||
}
|
||||
@@ -32,7 +32,8 @@ import { addMissingLeafKeys } from './helpers/StateMerge';
|
||||
import { triggerModalParentUpdate } from './ParentContextProvider';
|
||||
import type { GlobalHeaderRule } from './LayoutLoader';
|
||||
import { IdentityGuardInterceptor } from '../identity/IdentityGuardInterceptor';
|
||||
import { isAbortError, isNetworkFailure } from './networkResilience';
|
||||
import { isAbortError, isNetworkFailure, loadScriptWithRetry, loadStylesheetWithRetry } from './networkResilience';
|
||||
import { isAllowedScriptSrc, getTrustedScriptHosts } from '../support/scriptSrcPolicy';
|
||||
|
||||
const logger = createLogger('ActionDispatcher');
|
||||
|
||||
@@ -1410,43 +1411,36 @@ export class ActionDispatcher {
|
||||
const scriptUrl = moduleData.assets.js;
|
||||
const scriptId = `module-${identifier}`;
|
||||
|
||||
// 이미 로드된 스크립트인지 확인
|
||||
// 출처 게이트 — 정상 확장 자산 URL 은 전부 `/api/...` same-origin 이다.
|
||||
this.assertAllowedExtensionAssetUrl(scriptUrl, `module script (${identifier})`, action);
|
||||
|
||||
// 이미 로드된 스크립트면 JS 만 건너뛴다 (CSS 는 아래 형제 블록이 계속 처리).
|
||||
if (document.getElementById(scriptId)) {
|
||||
logger.warn(`reloadModuleHandlers: Script ${scriptId} already loaded`);
|
||||
return;
|
||||
} else {
|
||||
await loadScriptWithRetry(
|
||||
scriptUrl,
|
||||
{ id: scriptId },
|
||||
{ label: `module-script:${identifier}` }
|
||||
);
|
||||
logger.log(`reloadModuleHandlers: Script loaded successfully for ${identifier}`);
|
||||
}
|
||||
}
|
||||
|
||||
// <script> 태그 동적 생성
|
||||
const script = document.createElement('script');
|
||||
script.id = scriptId;
|
||||
script.src = scriptUrl;
|
||||
script.async = true;
|
||||
// CSS 파일이 있으면 동적 로드 (JS 유무·기존재와 무관한 형제 작업)
|
||||
if (moduleData.assets.css) {
|
||||
const cssUrl = moduleData.assets.css;
|
||||
const linkId = `module-css-${identifier}`;
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
script.onload = () => {
|
||||
logger.log(`reloadModuleHandlers: Script loaded successfully for ${identifier}`);
|
||||
resolve();
|
||||
};
|
||||
script.onerror = () => {
|
||||
logger.error(`reloadModuleHandlers: Failed to load script for ${identifier}`);
|
||||
reject(new Error(`Failed to load module script: ${scriptUrl}`));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
this.assertAllowedExtensionAssetUrl(cssUrl, `module stylesheet (${identifier})`, action);
|
||||
|
||||
// CSS 파일이 있으면 동적 로드
|
||||
if (moduleData.assets.css) {
|
||||
const cssUrl = moduleData.assets.css;
|
||||
const linkId = `module-css-${identifier}`;
|
||||
|
||||
if (!document.getElementById(linkId)) {
|
||||
const link = document.createElement('link');
|
||||
link.id = linkId;
|
||||
link.rel = 'stylesheet';
|
||||
link.href = cssUrl;
|
||||
document.head.appendChild(link);
|
||||
logger.log(`reloadModuleHandlers: CSS loaded for ${identifier}`);
|
||||
}
|
||||
if (!document.getElementById(linkId)) {
|
||||
await loadStylesheetWithRetry(
|
||||
cssUrl,
|
||||
{ id: linkId },
|
||||
{ label: `module-css:${identifier}` }
|
||||
);
|
||||
logger.log(`reloadModuleHandlers: CSS loaded for ${identifier}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1530,43 +1524,36 @@ export class ActionDispatcher {
|
||||
const scriptUrl = pluginData.assets.js;
|
||||
const scriptId = `plugin-${identifier}`;
|
||||
|
||||
// 이미 로드된 스크립트인지 확인
|
||||
// 출처 게이트 — 정상 확장 자산 URL 은 전부 `/api/...` same-origin 이다.
|
||||
this.assertAllowedExtensionAssetUrl(scriptUrl, `plugin script (${identifier})`, action);
|
||||
|
||||
// 이미 로드된 스크립트면 JS 만 건너뛴다 (CSS 는 아래 형제 블록이 계속 처리).
|
||||
if (document.getElementById(scriptId)) {
|
||||
logger.warn(`reloadPluginHandlers: Script ${scriptId} already loaded`);
|
||||
return;
|
||||
} else {
|
||||
await loadScriptWithRetry(
|
||||
scriptUrl,
|
||||
{ id: scriptId },
|
||||
{ label: `plugin-script:${identifier}` }
|
||||
);
|
||||
logger.log(`reloadPluginHandlers: Script loaded successfully for ${identifier}`);
|
||||
}
|
||||
}
|
||||
|
||||
// <script> 태그 동적 생성
|
||||
const script = document.createElement('script');
|
||||
script.id = scriptId;
|
||||
script.src = scriptUrl;
|
||||
script.async = true;
|
||||
// CSS 파일이 있으면 동적 로드 (JS 유무·기존재와 무관한 형제 작업)
|
||||
if (pluginData.assets.css) {
|
||||
const cssUrl = pluginData.assets.css;
|
||||
const linkId = `plugin-css-${identifier}`;
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
script.onload = () => {
|
||||
logger.log(`reloadPluginHandlers: Script loaded successfully for ${identifier}`);
|
||||
resolve();
|
||||
};
|
||||
script.onerror = () => {
|
||||
logger.error(`reloadPluginHandlers: Failed to load script for ${identifier}`);
|
||||
reject(new Error(`Failed to load plugin script: ${scriptUrl}`));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
this.assertAllowedExtensionAssetUrl(cssUrl, `plugin stylesheet (${identifier})`, action);
|
||||
|
||||
// CSS 파일이 있으면 동적 로드
|
||||
if (pluginData.assets.css) {
|
||||
const cssUrl = pluginData.assets.css;
|
||||
const linkId = `plugin-css-${identifier}`;
|
||||
|
||||
if (!document.getElementById(linkId)) {
|
||||
const link = document.createElement('link');
|
||||
link.id = linkId;
|
||||
link.rel = 'stylesheet';
|
||||
link.href = cssUrl;
|
||||
document.head.appendChild(link);
|
||||
logger.log(`reloadPluginHandlers: CSS loaded for ${identifier}`);
|
||||
}
|
||||
if (!document.getElementById(linkId)) {
|
||||
await loadStylesheetWithRetry(
|
||||
cssUrl,
|
||||
{ id: linkId },
|
||||
{ label: `plugin-css:${identifier}` }
|
||||
);
|
||||
logger.log(`reloadPluginHandlers: CSS loaded for ${identifier}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5790,17 +5777,63 @@ export class ActionDispatcher {
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 자산 URL(js/css)이 주입 허용 대상인지 검사하고, 아니면 차단합니다.
|
||||
*
|
||||
* 확장 활성화 응답이 지시하는 URL 을 그대로 `<script>`/`<link>` 로 붙이는 경로는
|
||||
* 레이아웃 `scripts[]` 와 같은 출처 정책을 받아야 한다. 정상 확장 자산 URL 은 전부
|
||||
* `/api/...` same-origin 이므로 과차단은 발생하지 않는다.
|
||||
*
|
||||
* @param url 자산 URL
|
||||
* @param what 오류 메시지에 실을 대상 설명
|
||||
* @param action 액션 정의 (ActionError 컨텍스트)
|
||||
* @throws ActionError 미신뢰 출처인 경우
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
private assertAllowedExtensionAssetUrl(url: string, what: string, action: ActionDefinition): void {
|
||||
if (isAllowedScriptSrc(url, getTrustedScriptHosts())) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.error(`Blocked untrusted ${what} asset url: ${url}`);
|
||||
throw new ActionError(
|
||||
`Blocked untrusted ${what} url (same-origin path or declared trusted host required): ${url}`,
|
||||
action
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 로드된 외부 스크립트 ID를 추적하기 위한 Set
|
||||
*/
|
||||
private static loadedScripts: Set<string> = new Set();
|
||||
|
||||
/**
|
||||
* 로드 진행 중인 스크립트의 공유 Promise (키 = scriptId).
|
||||
*
|
||||
* 같은 스크립트를 동시에 요청한 호출자들이 하나의 `<script>` 태그를 공유하고,
|
||||
* **1회차 onload 이후에** 함께 완료되도록 한다. 종전에는 in-flight 를 추적하지 않아
|
||||
* 2번째 호출이 "DOM 에 태그가 있다" 는 이유로 로드 완료 전에 즉시 resolve 했고,
|
||||
* 그 호출자의 onLoad 는 SDK 전역이 아직 없는 시점에 실행됐다 (예외 없이 무반응).
|
||||
*
|
||||
* 공유 Promise 는 "로드 완료" 만 담는다 — onLoad 는 호출자별로 await 후 각자 실행한다.
|
||||
*
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
private static loadingScripts: Map<string, Promise<void>> = new Map();
|
||||
|
||||
/**
|
||||
* 외부 스크립트를 동적으로 로드합니다.
|
||||
*
|
||||
* 이미 로드된 스크립트는 재로드하지 않고 캐시된 상태를 사용합니다.
|
||||
* 스크립트 로드 완료 시 onLoad 액션을 실행합니다.
|
||||
*
|
||||
* `src` 는 레이아웃 `scripts[]` 와 **같은 출처 정책**을 받는다 — same-origin 절대 경로이거나
|
||||
* 확장이 manifest 로 선언한 신뢰 호스트여야 하며, 그 밖의 원격 URL 은 로드 전에 차단된다
|
||||
* (`support/scriptSrcPolicy`). 이 경로만 게이트가 없으면 저장측 검증을 우회한 임의 원격
|
||||
* 코드가 그대로 실행된다.
|
||||
*
|
||||
* 같은 스크립트를 동시에 요청하면 하나의 태그를 공유하고 모두 1회차 로드 완료 후 resolve 한다.
|
||||
*
|
||||
* @param params 스크립트 로드 파라미터
|
||||
* - src: 스크립트 URL (필수)
|
||||
* - id: 스크립트 요소 ID (선택, 중복 로드 방지에 사용)
|
||||
@@ -5832,6 +5865,18 @@ export class ActionDispatcher {
|
||||
throw new ActionError('loadScript handler requires "src" parameter', action);
|
||||
}
|
||||
|
||||
// 출처 게이트 — 캐시 검사보다 앞이다. 뒤에 두면 이미 로드된 미신뢰 스크립트가
|
||||
// 캐시 히트로 통과한다.
|
||||
if (!isAllowedScriptSrc(src, getTrustedScriptHosts())) {
|
||||
logger.warn(
|
||||
`loadScript: blocked untrusted script src (same-origin path or declared trusted host required): ${src}`
|
||||
);
|
||||
throw new ActionError(
|
||||
`Blocked untrusted script src (same-origin path or declared trusted host required): ${src}`,
|
||||
action
|
||||
);
|
||||
}
|
||||
|
||||
const scriptId = id || `script_${src.replace(/[^a-zA-Z0-9]/g, '_')}`;
|
||||
|
||||
// 이미 로드된 스크립트인지 확인
|
||||
@@ -5846,7 +5891,22 @@ export class ActionDispatcher {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 같은 스크립트가 로드 중이면 그 Promise 를 공유한다 (태그 1개, 완료는 함께).
|
||||
const inFlight = ActionDispatcher.loadingScripts.get(scriptId);
|
||||
if (inFlight) {
|
||||
logger.log(`loadScript: joining in-flight load: ${scriptId}`);
|
||||
await inFlight;
|
||||
|
||||
if (action.onLoad) {
|
||||
await this.executeAction(action.onLoad, context);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// DOM에 이미 스크립트가 존재하는지 확인
|
||||
// (dispatcher 가 만들지 않은 외래 태그 — 로드 상태를 식별할 수 없으므로 완료로 간주한다.
|
||||
// dispatcher 자신의 경합은 위 in-flight Map 이 이미 제거했다.)
|
||||
const existingScript = document.getElementById(scriptId);
|
||||
if (existingScript) {
|
||||
logger.log(`loadScript: script element already exists: ${scriptId}`);
|
||||
@@ -5862,36 +5922,56 @@ export class ActionDispatcher {
|
||||
|
||||
logger.log(`loadScript: loading script: ${src}`);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.id = scriptId;
|
||||
script.src = src;
|
||||
script.async = async;
|
||||
script.defer = defer;
|
||||
const script = document.createElement('script');
|
||||
script.id = scriptId;
|
||||
script.src = src;
|
||||
script.async = async;
|
||||
script.defer = defer;
|
||||
|
||||
script.onload = async () => {
|
||||
// 동의 관리(gdpr) preblocker 가 src setter 에서 동기적으로 차단을 기록한다.
|
||||
// 차단된 스크립트는 append 해도 영영 로드되지 않으므로, 태그를 붙이지 않고
|
||||
// 미완료 상태(resolve(false))로 돌려준다 — 오류가 아니라 "동의 전" 이라는 상태다.
|
||||
// 캐시·in-flight 에 기록하지 않으므로 동의 후 재디스패치하면 정상 로드된다.
|
||||
if (script.hasAttribute('data-gdpr-blocked-src')) {
|
||||
logger.warn(`loadScript: script blocked by consent manager (not loaded): ${src}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const loadPromise = new Promise<void>((resolve, reject) => {
|
||||
script.onload = () => {
|
||||
logger.log(`loadScript: script loaded successfully: ${scriptId}`);
|
||||
ActionDispatcher.loadedScripts.add(scriptId);
|
||||
|
||||
// onLoad 액션 실행
|
||||
if (action.onLoad) {
|
||||
try {
|
||||
await this.executeAction(action.onLoad, context);
|
||||
} catch (error) {
|
||||
logger.error('loadScript: onLoad action failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
resolve(true);
|
||||
ActionDispatcher.loadingScripts.delete(scriptId);
|
||||
resolve();
|
||||
};
|
||||
|
||||
script.onerror = (error) => {
|
||||
logger.error(`loadScript: failed to load script: ${src}`, error);
|
||||
ActionDispatcher.loadingScripts.delete(scriptId);
|
||||
reject(new ActionError(`Failed to load script: ${src}`, action));
|
||||
};
|
||||
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
|
||||
// 공유 Promise 의 rejection 이 구독자 없는 시점에 unhandled 로 새지 않게 한다
|
||||
// (아래 await 와 join 경로가 각자 처리한다).
|
||||
loadPromise.catch(() => {});
|
||||
|
||||
ActionDispatcher.loadingScripts.set(scriptId, loadPromise);
|
||||
|
||||
await loadPromise;
|
||||
|
||||
// onLoad 액션 실행
|
||||
if (action.onLoad) {
|
||||
try {
|
||||
await this.executeAction(action.onLoad, context);
|
||||
} catch (error) {
|
||||
logger.error('loadScript: onLoad action failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5974,6 +6054,10 @@ export class ActionDispatcher {
|
||||
);
|
||||
}
|
||||
|
||||
// 심층 방어: 스크립트 로드 게이트를 통과한 전역만 호출된다는 전제 위에서,
|
||||
// 임의 코드 실행으로 직결되는 생성자는 참조 동일성으로 거부한다.
|
||||
this.assertCallableExternalConstructor(Constructor, constructorPath, action);
|
||||
|
||||
logger.log(`callExternal: calling constructor ${constructorPath}`);
|
||||
|
||||
// 콜백 함수 생성 (callbackEvent가 지정된 경우)
|
||||
@@ -5999,8 +6083,15 @@ export class ActionDispatcher {
|
||||
const processMapping = (mapping: Record<string, any>): Record<string, any> => {
|
||||
const result: Record<string, any> = {};
|
||||
for (const [fieldName, dataPath] of Object.entries(mapping)) {
|
||||
// 프로토타입 오염 차단: 이 결과는 deepMergeWithState → setState 로 흘러가므로
|
||||
// 매핑 키 하나가 앱 전역의 모든 객체를 오염시킬 수 있다.
|
||||
if (ActionDispatcher.isPrototypePathSegment(fieldName)) {
|
||||
logger.warn(`callExternal: skipped prototype-polluting mapping key: ${fieldName}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof dataPath === 'string') {
|
||||
// 리프 노드: 실제 데이터 매핑
|
||||
// 리프 노드: 실제 데이터 매핑 (경로 세그먼트도 같은 판정을 받는다)
|
||||
result[fieldName] = this.getNestedProperty(data, dataPath);
|
||||
} else if (typeof dataPath === 'object' && dataPath !== null) {
|
||||
// 중첩 객체: 재귀 처리
|
||||
@@ -6125,6 +6216,10 @@ export class ActionDispatcher {
|
||||
);
|
||||
}
|
||||
|
||||
// 심층 방어: 스크립트 로드 게이트를 통과한 전역만 호출된다는 전제 위에서,
|
||||
// 임의 코드 실행으로 직결되는 생성자는 참조 동일성으로 거부한다.
|
||||
this.assertCallableExternalConstructor(Constructor, constructorPath, action);
|
||||
|
||||
logger.log(`callExternalEmbed: creating layer for ${constructorPath}`);
|
||||
|
||||
// 레이어 요소들 생성
|
||||
@@ -6152,8 +6247,15 @@ export class ActionDispatcher {
|
||||
const processMapping = (mapping: Record<string, any>): Record<string, any> => {
|
||||
const result: Record<string, any> = {};
|
||||
for (const [fieldName, dataPath] of Object.entries(mapping)) {
|
||||
// 프로토타입 오염 차단: 이 결과는 deepMergeWithState → setState 로 흘러가므로
|
||||
// 매핑 키 하나가 앱 전역의 모든 객체를 오염시킬 수 있다.
|
||||
if (ActionDispatcher.isPrototypePathSegment(fieldName)) {
|
||||
logger.warn(`callExternal: skipped prototype-polluting mapping key: ${fieldName}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof dataPath === 'string') {
|
||||
// 리프 노드: 실제 데이터 매핑
|
||||
// 리프 노드: 실제 데이터 매핑 (경로 세그먼트도 같은 판정을 받는다)
|
||||
result[fieldName] = this.getNestedProperty(data, dataPath);
|
||||
} else if (typeof dataPath === 'object' && dataPath !== null) {
|
||||
// 중첩 객체: 재귀 처리
|
||||
@@ -6326,19 +6428,91 @@ export class ActionDispatcher {
|
||||
return { overlay, layer, closeLayer };
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로토타입 체인에 도달하는 경로 세그먼트 (읽기·쓰기 양쪽에서 거부한다).
|
||||
*
|
||||
* 이 세그먼트를 타면 객체의 데이터가 아니라 **모든 객체가 공유하는 프로토타입**에
|
||||
* 닿는다. 읽기 쪽에서는 `Object.constructor` 같은 경로가 임의 함수 생성자로 이어지고,
|
||||
* 쓰기 쪽에서는 `__proto__` 매핑 한 줄이 앱 전역의 객체를 오염시킨다.
|
||||
*
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
private static readonly PROTOTYPE_PATH_SEGMENTS: readonly string[] = [
|
||||
'__proto__',
|
||||
'prototype',
|
||||
'constructor',
|
||||
];
|
||||
|
||||
/**
|
||||
* 경로 세그먼트가 프로토타입 체인에 닿는지 판정합니다.
|
||||
*
|
||||
* @param segment 경로 세그먼트
|
||||
* @returns 프로토타입 체인 세그먼트면 true
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
private static isPrototypePathSegment(segment: string): boolean {
|
||||
return ActionDispatcher.PROTOTYPE_PATH_SEGMENTS.includes(segment);
|
||||
}
|
||||
|
||||
/**
|
||||
* 중첩된 객체 속성을 경로로 접근합니다.
|
||||
*
|
||||
* 프로토타입 체인 세그먼트(`__proto__`/`prototype`/`constructor`)가 포함된 경로는
|
||||
* `undefined` 를 돌려준다 — 던지지 않는 이유는 이 함수가 상태 경로 해석에도 쓰이는
|
||||
* 공용 함수이기 때문이다. callExternal 에서는 이 undefined 가 기존의
|
||||
* "Constructor not found" ActionError 로 수렴한다.
|
||||
*
|
||||
* @param obj 대상 객체 (예: window)
|
||||
* @param path 점으로 구분된 경로 (예: "daum.Postcode")
|
||||
* @returns 해당 경로의 값 또는 undefined
|
||||
*/
|
||||
private getNestedProperty(obj: Record<string, any>, path: string): any {
|
||||
return path.split('.').reduce((current: any, key: string) => {
|
||||
if (ActionDispatcher.isPrototypePathSegment(key)) {
|
||||
return undefined;
|
||||
}
|
||||
return current && current[key] !== undefined ? current[key] : undefined;
|
||||
}, obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* callExternal 이 해석한 생성자가 임의 코드 실행 seam 인지 검사합니다.
|
||||
*
|
||||
* 이름이 아니라 **참조 동일성**으로 판정한다 — `window.myAlias = Function` 처럼 별칭을
|
||||
* 만들어 두면 이름 비교는 그대로 통과하기 때문이다. 스크립트 로드 게이트를 통과한
|
||||
* 전역만 호출된다는 전제 위의 심층 방어다.
|
||||
*
|
||||
* @param Constructor 해석된 생성자
|
||||
* @param constructorPath 오류 메시지에 실을 경로
|
||||
* @param action 액션 정의 (ActionError 컨텍스트)
|
||||
* @throws ActionError 임의 코드 실행 seam 인 경우
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
private assertCallableExternalConstructor(
|
||||
Constructor: unknown,
|
||||
constructorPath: string,
|
||||
action: ActionDefinition
|
||||
): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const denied: unknown[] = [
|
||||
(window as any).Function,
|
||||
(window as any).eval,
|
||||
(window as any).setTimeout,
|
||||
(window as any).setInterval,
|
||||
];
|
||||
|
||||
if (denied.some(fn => fn !== undefined && fn === Constructor)) {
|
||||
logger.error(`callExternal: blocked arbitrary code execution seam: ${constructorPath}`);
|
||||
throw new ActionError(
|
||||
`Blocked constructor (arbitrary code execution): ${constructorPath}`,
|
||||
action
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 로컬스토리지에 데이터를 저장합니다.
|
||||
*
|
||||
|
||||
@@ -5,6 +5,38 @@
|
||||
>
|
||||
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
|
||||
|
||||
## [engine-v1.64.0] - 2026-09-02
|
||||
|
||||
### Security
|
||||
|
||||
#### 동적 스크립트 주입 경로 전부에 출처 게이트 적용 (KVE-2026-1915 B-2 후속)
|
||||
|
||||
- 레이아웃 `scripts[]` 에만 있던 원격 스크립트 차단 게이트를 **브라우저에 새 `<script>` 를 붙이는 모든 경로**로 넓혔다. 종전에는 `loadScript` 액션 · `reloadModuleHandlers`/`reloadPluginHandlers` 의 확장 자산 · 편집기 프리뷰 캔버스 · `G7Core.asset.loadScript` 가 게이트 밖이라, 저장측(SafeLayoutExpressions·NoExternalUrls)이 외부 URL 저장을 422 로 막아도 런타임 디스패치 한 번으로 임의 원격 코드가 로드됐다(실브라우저 실측: 미신뢰 CDN 스크립트 로드 성공, 전역 생성 확인).
|
||||
- 판정식을 `resources/js/core/support/scriptSrcPolicy.ts` 로 분리해 런타임 SSoT 를 하나로 두었다. `TemplateApp` 의 private 4개(`isAllowedScriptSrc` · `normalizeScriptSrcForOriginCheck` · `extractScriptHost` · `getTrustedScriptHosts`)는 그 모듈로 위임하는 thin delegate 로 남긴다(테스트 seam 보존). `ActionDispatcher → TemplateApp` import 는 순환의존이라 불가능하므로 공유 모듈이 유일한 해법이다.
|
||||
- 게이트 실패 시 동작은 경로 성격에 맞춘다: 액션(`loadScript` · 확장 자산 재로드)은 `ActionError` 로 실패해 `onError`/`errorHandling` 오류 채널로 전달되고, 레이아웃 `scripts[]` 와 편집기 프리뷰는 종전대로 skip + 경고다.
|
||||
- `G7Core.asset.isAllowedScriptSrc(url)` 를 공개 seam 으로 노출한다. 코어 로더를 쓸 수 없는 주입(iframe `document.write` 등)이 같은 판정을 재사용하는 통로다. `G7Core.asset.loadScript` 는 미신뢰 URL 을 reject 한다 — 공개 API 계약 변경이다.
|
||||
- `callExternal`/`callExternalEmbed` 에 심층 방어를 더했다. 해석된 생성자가 `Function`·`eval`·`setTimeout`·`setInterval` 이면 **참조 동일성**으로 거부하고(별칭 전역도 차단), 경로 세그먼트가 `__proto__`/`prototype`/`constructor` 면 `getNestedProperty` 가 `undefined` 를 돌려준다. `callbackSetState` 매핑 키도 같은 판정을 받아, 매핑 한 줄이 `deepMergeWithState` → `setState` 를 타고 앱 전역 객체를 오염시키던 쓰기 경로를 닫았다.
|
||||
|
||||
### Fixed
|
||||
|
||||
#### 같은 스크립트를 동시에 요청하면 로드 전에 완료 처리되던 문제
|
||||
|
||||
- `loadScript` 액션이 in-flight 를 추적하지 않아, 2번째 호출이 "DOM 에 태그가 있다" 는 이유로 **1번째 로드가 끝나기 전에** 즉시 완료됐다(실측 0ms resolve). 그 호출자의 `onLoad` 는 SDK 전역이 아직 없는 시점에 실행되어 아무 일도 일어나지 않았고, 예외도 콘솔 에러도 남지 않았다.
|
||||
- 이제 `scriptId` 별 공유 Promise 를 두어 태그는 하나만 만들고, 동시 호출자 모두 그 태그의 `onload` 이후에 완료된다. 공유 Promise 는 "로드 완료" 만 담고 `onLoad` 는 호출자별로 각자 실행한다. dispatcher 가 만들지 않은 외래 태그는 로드 상태를 식별할 수 없으므로 종전대로 완료로 간주한다.
|
||||
|
||||
#### 확장 핸들러 재로드에서 script 가 이미 있으면 CSS 까지 건너뛰던 문제
|
||||
|
||||
- `reloadModuleHandlers`/`reloadPluginHandlers` 의 `assets.js` 기존재 early `return` 이 뒤따르는 CSS 로드까지 통째로 건너뛰었다. CSS 블록이 `if (assets.js)` 안에 중첩돼 있어 **CSS 만 있는 확장**은 아예 스타일이 붙지 않았다. 이제 JS 만 건너뛰고 CSS 는 형제 블록에서 독립적으로 처리한다.
|
||||
- 두 핸들러의 원시 `<script>`/`<link>` 생성을 `loadScriptWithRetry`/`loadStylesheetWithRetry` 로 교체했다. 실패한 element 를 남기지 않으므로 잔존 태그가 다음 시도를 조기 완료시키지 않는다.
|
||||
|
||||
#### 확장 CSS 를 동시에 요청하면 `<link>` 가 중복 생성되던 문제
|
||||
|
||||
- `ModuleAssetLoader.loadCSS` 만 in-flight Promise 공유(`loadingPromises`)가 없어 같은 확장의 CSS 동시 요청이 `<link>` 를 중복 생성했고, 재시도 로더가 기존 element 를 제거하면서 서로의 시도를 지웠다. 키는 `module-css-{id}` 로 둬 `loadJS` 의 raw identifier 키공간과 겹치지 않게 한다. 실패 시 throw 하지 않는 기존 계약은 유지한다.
|
||||
|
||||
### Changed
|
||||
|
||||
- 동의 관리(gdpr) preblocker 가 차단한 스크립트는 `loadScript` 액션에서 **오류가 아니라 미완료 상태**로 끝난다(`false` 반환). 태그를 붙이지 않고 캐시·in-flight 에도 기록하지 않으므로, 동의 후 다시 디스패치하면 정상 로드된다. `onLoad` 는 실행되지 않는다.
|
||||
|
||||
## [engine-v1.63.5] - 2026-09-02
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -64,6 +64,7 @@ import {
|
||||
pluginAsset,
|
||||
convertToCurrentMode,
|
||||
} from '../support/assetUrl';
|
||||
import { isAllowedScriptSrc, getTrustedScriptHosts } from '../support/scriptSrcPolicy';
|
||||
import {
|
||||
notifyAssetFailure,
|
||||
drainExternalAssetFailures,
|
||||
@@ -919,12 +920,37 @@ function initAssetUrlAPI(G7Core: any): void {
|
||||
* 확장이 자기 자산을 런타임에 직접 로드할 때 쓴다. 확장 번들이 코어 모듈을
|
||||
* import 할 수 없어 각자 `document.createElement('script')` 를 쓰면, 코어가
|
||||
* 갖춘 재시도·실패 표면화 계층이 그 경로에만 없게 된다.
|
||||
*
|
||||
* `url` 은 레이아웃 `scripts[]` 와 **같은 출처 정책**을 받는다 — same-origin 절대
|
||||
* 경로이거나 확장이 manifest(`trusted_script_hosts`)로 선언한 신뢰 호스트여야 한다.
|
||||
* 이 seam 만 게이트가 없으면 저장측 검증을 우회한 원격 코드 로드 통로가 된다.
|
||||
*
|
||||
* @since engine-v1.64.0 출처 게이트 추가 (미신뢰 URL 은 reject)
|
||||
*/
|
||||
loadScript: (
|
||||
url: string,
|
||||
attrs?: Record<string, string>,
|
||||
options?: Record<string, unknown>
|
||||
): Promise<void> => loadScriptWithRetry(url, attrs, options as any),
|
||||
): Promise<void> => {
|
||||
if (!isAllowedScriptSrc(url, getTrustedScriptHosts())) {
|
||||
return Promise.reject(
|
||||
new Error(
|
||||
`Blocked untrusted script src (same-origin path or declared trusted host required): ${url}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return loadScriptWithRetry(url, attrs, options as any);
|
||||
},
|
||||
/**
|
||||
* 스크립트 URL 이 주입 허용 대상인지 판정합니다.
|
||||
*
|
||||
* 로더를 쓸 수 없는 주입(iframe `document.write` 등)이 같은 판정을 재사용하는 통로다.
|
||||
*
|
||||
* @since engine-v1.64.0
|
||||
*/
|
||||
isAllowedScriptSrc: (url: string): boolean =>
|
||||
isAllowedScriptSrc(url, getTrustedScriptHosts()),
|
||||
/** 재시도 계층을 갖춘 스타일시트 로더 */
|
||||
loadStylesheet: (
|
||||
url: string,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* `reloadModuleHandlers` / `reloadPluginHandlers` 자산 로드 계약 테스트.
|
||||
*
|
||||
* 두 핸들러는 확장 활성화 응답이 지시하는 URL 을 그대로 `<script>`/`<link>` 로 붙인다.
|
||||
* 그래서 레이아웃 `scripts[]` 와 같은 출처 정책을 받아야 하고(미신뢰 URL 차단),
|
||||
* script 가 이미 있다는 이유로 **CSS 로드까지 건너뛰면 안 된다**(종전 결함).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { ActionDispatcher, ActionDefinition } from '../ActionDispatcher';
|
||||
|
||||
vi.mock('../../auth/AuthManager', () => ({
|
||||
AuthManager: {
|
||||
getInstance: vi.fn(() => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../api/ApiClient', () => ({
|
||||
getApiClient: vi.fn(() => ({ getToken: vi.fn() })),
|
||||
}));
|
||||
|
||||
describe('확장 자산 재로드 핸들러 (reloadModuleHandlers / reloadPluginHandlers)', () => {
|
||||
let dispatcher: ActionDispatcher;
|
||||
let created: HTMLElement[];
|
||||
let originalCreateElement: typeof document.createElement;
|
||||
|
||||
const lastResult = (r: any) => r;
|
||||
|
||||
beforeEach(() => {
|
||||
dispatcher = new ActionDispatcher({ navigate: vi.fn() });
|
||||
created = [];
|
||||
originalCreateElement = document.createElement.bind(document);
|
||||
document.head.innerHTML = '';
|
||||
|
||||
(window as any).G7Config = { trustedScriptHosts: [], moduleAssets: {}, pluginAssets: {} };
|
||||
|
||||
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
|
||||
const el = originalCreateElement(tagName);
|
||||
if (tagName === 'script' || tagName === 'link') {
|
||||
created.push(el as HTMLElement);
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation((node: Node) => {
|
||||
setTimeout(() => {
|
||||
const el = node as HTMLElement & { onload?: ((e: Event) => void) | null };
|
||||
el.onload?.(new Event('load'));
|
||||
}, 0);
|
||||
// 실제 DOM 에도 넣어야 getElementById 로 기존재 판정이 가능하다
|
||||
return HTMLHeadElement.prototype.appendChild.call(document.head, node) as Node;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
document.head.innerHTML = '';
|
||||
delete (window as any).G7Config;
|
||||
});
|
||||
|
||||
const run = (handler: string, params: Record<string, any>) =>
|
||||
dispatcher.executeAction(
|
||||
{ type: 'click', handler, params } as ActionDefinition,
|
||||
{} as any
|
||||
);
|
||||
|
||||
describe.each([
|
||||
['reloadModuleHandlers', 'moduleInfo', 'module', 'moduleAssets'],
|
||||
['reloadPluginHandlers', 'pluginInfo', 'plugin', 'pluginAssets'],
|
||||
])('%s', (handlerName, infoKey, prefix, assetsKey) => {
|
||||
const identifier = 'vendor-ext';
|
||||
|
||||
const add = (assets: Record<string, string>) =>
|
||||
run(handlerName, { [infoKey]: { identifier, assets }, action: 'add' });
|
||||
|
||||
it('same-origin js/css 는 정상 로드된다', async () => {
|
||||
const result = lastResult(await add({ js: '/api/x/bundle.js', css: '/api/x/bundle.css' }));
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(document.getElementById(`${prefix}-${identifier}`)).not.toBeNull();
|
||||
expect(document.getElementById(`${prefix}-css-${identifier}`)).not.toBeNull();
|
||||
expect((window as any).G7Config[assetsKey][identifier]).toBeDefined();
|
||||
});
|
||||
|
||||
it('미신뢰 외부 js 는 차단된다 (태그 미생성)', async () => {
|
||||
const result = lastResult(await add({ js: 'https://cdn.evil.com/x.js' }));
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked untrusted/);
|
||||
expect(created.filter(el => el.tagName === 'SCRIPT')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('미신뢰 외부 css 는 차단된다 (태그 미생성)', async () => {
|
||||
const result = lastResult(
|
||||
await add({ js: '/api/x/bundle.js', css: 'https://cdn.evil.com/x.css' })
|
||||
);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked untrusted/);
|
||||
expect(created.filter(el => el.tagName === 'LINK')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('script 가 이미 있어도 CSS 로드는 진행된다', async () => {
|
||||
const existing = originalCreateElement('script');
|
||||
existing.id = `${prefix}-${identifier}`;
|
||||
HTMLHeadElement.prototype.appendChild.call(document.head, existing);
|
||||
|
||||
const result = lastResult(await add({ js: '/api/x/bundle.js', css: '/api/x/bundle.css' }));
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(document.getElementById(`${prefix}-css-${identifier}`)).not.toBeNull();
|
||||
// 새 script 태그는 만들지 않는다
|
||||
expect(created.filter(el => el.tagName === 'SCRIPT')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('css 만 있는 확장도 로드된다 (js 없음)', async () => {
|
||||
const result = lastResult(await add({ css: '/api/x/bundle.css' }));
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(document.getElementById(`${prefix}-css-${identifier}`)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('신뢰 호스트로 선언된 외부 자산은 통과한다', async () => {
|
||||
(window as any).G7Config.trustedScriptHosts = ['cdn.trusted.com'];
|
||||
|
||||
const result = lastResult(await add({ js: 'https://cdn.trusted.com/x.js' }));
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(document.getElementById(`${prefix}-${identifier}`)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4503,10 +4503,13 @@ describe('ActionDispatcher', () => {
|
||||
|
||||
// Clear loaded scripts cache
|
||||
(ActionDispatcher as any).loadedScripts = new Set();
|
||||
(ActionDispatcher as any).loadingScripts = new Map();
|
||||
(window as any).G7Config = { trustedScriptHosts: [] };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
delete (window as any).G7Config;
|
||||
});
|
||||
|
||||
it('should load external script and execute onLoad action', async () => {
|
||||
@@ -4521,7 +4524,7 @@ describe('ActionDispatcher', () => {
|
||||
type: 'click',
|
||||
handler: 'loadScript',
|
||||
params: {
|
||||
src: '//example.com/script.js',
|
||||
src: '/js/vendor/script.js',
|
||||
id: 'test_script',
|
||||
},
|
||||
onLoad: onLoadAction,
|
||||
@@ -4537,7 +4540,7 @@ describe('ActionDispatcher', () => {
|
||||
|
||||
// Script should be created with correct attributes
|
||||
expect(appendedScripts.length).toBe(1);
|
||||
expect(appendedScripts[0].src).toContain('example.com/script.js');
|
||||
expect(appendedScripts[0].src).toContain('/js/vendor/script.js');
|
||||
expect(appendedScripts[0].id).toBe('test_script');
|
||||
|
||||
// onLoad setState should be called
|
||||
@@ -4556,7 +4559,7 @@ describe('ActionDispatcher', () => {
|
||||
type: 'click',
|
||||
handler: 'loadScript',
|
||||
params: {
|
||||
src: '//example.com/already.js',
|
||||
src: '/js/vendor/already.js',
|
||||
id: 'already_loaded',
|
||||
},
|
||||
onLoad: {
|
||||
@@ -4598,6 +4601,161 @@ describe('ActionDispatcher', () => {
|
||||
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('출처 게이트 (KVE-2026-1915 B-2 후속)', () => {
|
||||
const dispatch = (params: Record<string, any>) =>
|
||||
dispatcher.executeAction(
|
||||
{ type: 'click', handler: 'loadScript', params } as ActionDefinition,
|
||||
{} as any
|
||||
);
|
||||
|
||||
it('미신뢰 외부 src 는 실패로 끝나고 script 태그가 만들어지지 않는다', async () => {
|
||||
const result = await dispatch({ src: 'https://cdn.evil.com/lodash.js', id: 'evil' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked untrusted script src/);
|
||||
expect(appendedScripts.length).toBe(0);
|
||||
expect((ActionDispatcher as any).loadedScripts.has('evil')).toBe(false);
|
||||
});
|
||||
|
||||
it('authority 우회 형태(`/\\/evil.com/x.js`)도 차단된다', async () => {
|
||||
const result = await dispatch({ src: '/\\/evil.com/x.js', id: 'bypass' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked untrusted script src/);
|
||||
expect(appendedScripts.length).toBe(0);
|
||||
});
|
||||
|
||||
it('미신뢰 src 는 onError 액션을 발화시킨다', async () => {
|
||||
const mockSetState = vi.fn();
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'loadScript',
|
||||
params: { src: 'https://cdn.evil.com/x.js', id: 'evil2' },
|
||||
onError: { type: 'click', handler: 'setState', params: { blocked: true } },
|
||||
} as ActionDefinition;
|
||||
|
||||
const handler = dispatcher.createHandler(action, {}, { setState: mockSetState });
|
||||
const mockEvent = {
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
target: null,
|
||||
} as unknown as Event;
|
||||
|
||||
await handler(mockEvent);
|
||||
|
||||
expect(mockSetState).toHaveBeenCalledWith(expect.objectContaining({ blocked: true }));
|
||||
expect(appendedScripts.length).toBe(0);
|
||||
});
|
||||
|
||||
it('G7Config.trustedScriptHosts 에 선언된 호스트는 통과한다', async () => {
|
||||
(window as any).G7Config = { trustedScriptHosts: ['t1.daumcdn.net'] };
|
||||
|
||||
const result = await dispatch({ src: '//t1.daumcdn.net/postcode.v2.js', id: 'daum' });
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data).toBe(true);
|
||||
expect(appendedScripts.length).toBe(1);
|
||||
});
|
||||
|
||||
it('미신뢰 src 는 캐시에 이미 있어도 차단된다 (게이트가 캐시보다 앞)', async () => {
|
||||
(ActionDispatcher as any).loadedScripts.add('cached_evil');
|
||||
|
||||
const result = await dispatch({ src: 'https://cdn.evil.com/x.js', id: 'cached_evil' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked untrusted script src/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('동시 로드 Promise 공유', () => {
|
||||
it('같은 id 동시 2건 → script 1개, 두 호출자 모두 onload 이후 완료', async () => {
|
||||
const order: string[] = [];
|
||||
const onLoadA = vi.fn(() => order.push('A'));
|
||||
const onLoadB = vi.fn(() => order.push('B'));
|
||||
|
||||
// appendChild mock 이 10ms 뒤 onload 를 부른다 (beforeEach)
|
||||
const p1 = dispatcher
|
||||
.executeAction(
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'loadScript',
|
||||
params: { src: '/js/shared.js', id: 'shared' },
|
||||
onLoad: { type: 'click', handler: 'customA' },
|
||||
} as ActionDefinition,
|
||||
{} as any
|
||||
);
|
||||
const p2 = dispatcher
|
||||
.executeAction(
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'loadScript',
|
||||
params: { src: '/js/shared.js', id: 'shared' },
|
||||
onLoad: { type: 'click', handler: 'customB' },
|
||||
} as ActionDefinition,
|
||||
{} as any
|
||||
);
|
||||
|
||||
dispatcher.registerHandler('customA', async () => onLoadA());
|
||||
dispatcher.registerHandler('customB', async () => onLoadB());
|
||||
|
||||
await Promise.all([p1, p2]);
|
||||
|
||||
// 태그는 1개만 만들어진다
|
||||
expect(appendedScripts.length).toBe(1);
|
||||
// 두 호출자 모두 자기 onLoad 를 실행한다
|
||||
expect(onLoadA).toHaveBeenCalledTimes(1);
|
||||
expect(onLoadB).toHaveBeenCalledTimes(1);
|
||||
expect(order).toHaveLength(2);
|
||||
// 완료 후 in-flight 는 정리된다
|
||||
expect((ActionDispatcher as any).loadingScripts.size).toBe(0);
|
||||
expect((ActionDispatcher as any).loadedScripts.has('shared')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('동의 관리(gdpr) 차단 경계', () => {
|
||||
it('data-gdpr-blocked-src 가 붙으면 append 없이 resolve(false)', async () => {
|
||||
const mockSetState = vi.fn();
|
||||
|
||||
// src setter 를 가로채 차단 속성을 기록하는 preblocker 를 모사
|
||||
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
|
||||
const el = originalCreateElement(tagName);
|
||||
if (tagName === 'script') {
|
||||
const script = el as HTMLScriptElement;
|
||||
Object.defineProperty(script, 'src', {
|
||||
set(value: string) {
|
||||
script.setAttribute('data-gdpr-blocked-src', value);
|
||||
},
|
||||
get() {
|
||||
return '';
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
appendedScripts.push(script);
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'loadScript',
|
||||
params: { src: '/js/analytics.js', id: 'gdpr_blocked' },
|
||||
onLoad: { type: 'click', handler: 'setState', params: { loaded: true } },
|
||||
} as ActionDefinition;
|
||||
|
||||
const result = await dispatcher.executeAction(action, {
|
||||
setState: mockSetState,
|
||||
} as any);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data).toBe(false);
|
||||
expect(document.head.appendChild).not.toHaveBeenCalled();
|
||||
expect(mockSetState).not.toHaveBeenCalled();
|
||||
// 동의 후 재디스패치가 정상 로드되도록 캐시에 기록하지 않는다
|
||||
expect((ActionDispatcher as any).loadedScripts.has('gdpr_blocked')).toBe(false);
|
||||
expect((ActionDispatcher as any).loadingScripts.has('gdpr_blocked')).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('callExternal handler', () => {
|
||||
@@ -4635,6 +4793,131 @@ describe('ActionDispatcher', () => {
|
||||
delete (window as any).G7Core;
|
||||
});
|
||||
|
||||
describe('임의 코드 실행 seam 차단 (심층 방어)', () => {
|
||||
const dispatch = (handler: string, params: Record<string, any>, context: any = {}) =>
|
||||
dispatcher.executeAction(
|
||||
{ type: 'click', handler, params } as ActionDefinition,
|
||||
context
|
||||
);
|
||||
|
||||
it.each(['Function', 'eval', 'setTimeout', 'setInterval'])(
|
||||
'%s 는 참조 동일성으로 거부된다',
|
||||
async name => {
|
||||
const result = await dispatch('callExternal', { constructor: name, args: {} });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked constructor/);
|
||||
}
|
||||
);
|
||||
|
||||
it('별칭 전역도 참조 동일성으로 거부된다', async () => {
|
||||
(window as any).__alias = (window as any).Function;
|
||||
|
||||
try {
|
||||
const result = await dispatch('callExternal', { constructor: '__alias', args: {} });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked constructor/);
|
||||
} finally {
|
||||
delete (window as any).__alias;
|
||||
}
|
||||
});
|
||||
|
||||
it('callExternalEmbed 도 같은 판정을 받는다', async () => {
|
||||
const result = await dispatch('callExternalEmbed', {
|
||||
constructor: 'Function',
|
||||
args: {},
|
||||
embedTarget: 'body',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Blocked constructor/);
|
||||
});
|
||||
|
||||
it('프로토타입 체인 경로는 해석되지 않는다 (Object.constructor)', async () => {
|
||||
const result = await dispatch('callExternal', {
|
||||
constructor: 'Object.constructor',
|
||||
args: {},
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect((result.error as Error)?.message).toMatch(/Constructor not found/);
|
||||
});
|
||||
|
||||
it('정상 생성자는 그대로 호출된다 (과차단 없음)', async () => {
|
||||
const result = await dispatch('callExternal', {
|
||||
constructor: 'testLib.TestClass',
|
||||
args: {},
|
||||
method: 'open',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('callbackSetState 프로토타입 오염 차단', () => {
|
||||
afterEach(() => {
|
||||
delete (Object.prototype as any).polluted;
|
||||
});
|
||||
|
||||
const runMapping = async (callbackSetState: any) => {
|
||||
const mockSetState = vi.fn();
|
||||
|
||||
const action: ActionDefinition = {
|
||||
type: 'click',
|
||||
handler: 'callExternal',
|
||||
params: {
|
||||
constructor: 'testLib.TestClass',
|
||||
args: { oncomplete: true },
|
||||
callbackSetState,
|
||||
},
|
||||
} as ActionDefinition;
|
||||
|
||||
await dispatcher.executeAction(action, { setState: mockSetState, state: {} } as any);
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
|
||||
return mockSetState;
|
||||
};
|
||||
|
||||
it('프로토타입 체인 매핑 키는 상태에 도달하지 않는다', async () => {
|
||||
// 레이아웃 JSON 은 JSON.parse 를 거치므로 `__proto__` 도 own property 가 된다
|
||||
const mockSetState = await runMapping(
|
||||
JSON.parse(
|
||||
'{"__proto__": {"polluted": "result"}, "constructor": "result", "prototype": "result", "safe": "result"}'
|
||||
)
|
||||
);
|
||||
|
||||
expect(mockSetState).toHaveBeenCalled();
|
||||
const payload = mockSetState.mock.calls[0][0] as Record<string, any>;
|
||||
|
||||
expect(Object.prototype.hasOwnProperty.call(payload, 'constructor')).toBe(false);
|
||||
expect(Object.prototype.hasOwnProperty.call(payload, 'prototype')).toBe(false);
|
||||
expect(Object.prototype.hasOwnProperty.call(payload, '__proto__')).toBe(false);
|
||||
// 정상 키는 그대로 매핑된다 (과차단 없음)
|
||||
expect(payload.safe).toBe('success');
|
||||
expect((Object.prototype as any).polluted).toBeUndefined();
|
||||
});
|
||||
|
||||
it('중첩 매핑의 프로토타입 체인 키도 건너뛴다', async () => {
|
||||
const mockSetState = await runMapping(
|
||||
JSON.parse('{"form": {"constructor": "result", "safe": "result"}}')
|
||||
);
|
||||
|
||||
const payload = mockSetState.mock.calls[0][0] as Record<string, any>;
|
||||
|
||||
expect(Object.prototype.hasOwnProperty.call(payload.form, 'constructor')).toBe(false);
|
||||
expect(payload.form.safe).toBe('success');
|
||||
});
|
||||
|
||||
it('데이터 경로가 프로토타입 체인을 타면 undefined 로 해석된다', async () => {
|
||||
const mockSetState = await runMapping({ leaked: 'constructor.name' });
|
||||
|
||||
const payload = mockSetState.mock.calls[0][0] as Record<string, any>;
|
||||
|
||||
expect(payload.leaked).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('should call external constructor and method', async () => {
|
||||
const mockSetState = vi.fn();
|
||||
|
||||
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* PreviewCanvas — 편집 캔버스 스크립트 주입 출처 게이트 회귀 테스트.
|
||||
*
|
||||
* 프리뷰는 런타임 렌더의 미리보기다. 런타임(TemplateApp)이 거부하는 `scripts[].src` 를
|
||||
* 캔버스가 관리자 document.head 에 그대로 주입하면, **편집 중에만** 임의 원격 코드가
|
||||
* 관리자 세션에서 실행된다. 저장은 422 로 막히므로 저장 전 미리보기 단계가 유일한
|
||||
* 실행 창이고, 오류도 로그도 남지 않는다.
|
||||
*
|
||||
* 판정·결과는 런타임과 같아야 한다 — same-origin 경로/선언된 신뢰 호스트만 주입,
|
||||
* 그 밖은 skip + 경고.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import React from 'react';
|
||||
import { render, waitFor, cleanup } from '@testing-library/react';
|
||||
import { LayoutEditorProvider } from '../../LayoutEditorContext';
|
||||
import { LayoutDocumentProvider } from '../../LayoutDocumentContext';
|
||||
import { PreviewCanvas } from '../../components/PreviewCanvas';
|
||||
import { TranslationProvider } from '../../../TranslationContext';
|
||||
import { TranslationEngine } from '../../../TranslationEngine';
|
||||
import { ComponentRegistry } from '../../../ComponentRegistry';
|
||||
|
||||
describe('PreviewCanvas — scripts[] 출처 게이트', () => {
|
||||
let originalG7Core: any;
|
||||
let layoutScripts: Array<{ src: string; id?: string }> = [];
|
||||
let warnSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
const injectedScriptSrcs = (): string[] =>
|
||||
Array.from(window.document.querySelectorAll('script[data-g7le-canvas-script]')).map(
|
||||
el => el.getAttribute('data-g7le-canvas-script') ?? ''
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.resetInstance();
|
||||
originalG7Core = (window as any).G7Core;
|
||||
(window as any).G7Core = { t: vi.fn((key: string) => key) };
|
||||
(window as any).G7Config = { trustedScriptHosts: [] };
|
||||
|
||||
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
// 주입된 태그가 영원히 pending 되지 않도록 즉시 load 를 발화시킨다
|
||||
vi.spyOn(window.document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName === 'SCRIPT') {
|
||||
window.document.body.appendChild(node);
|
||||
queueMicrotask(() => node.dispatchEvent(new Event('load')));
|
||||
return node;
|
||||
}
|
||||
return HTMLHeadElement.prototype.appendChild.call(window.document.head, node);
|
||||
}) as any);
|
||||
|
||||
(global as any).fetch = vi.fn(async (url: string) => {
|
||||
if (url.includes('/editor-assets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: {
|
||||
identifier: 'sirsoft-basic',
|
||||
js: [],
|
||||
css: [],
|
||||
manifest_present: true,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/components.json')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
version: '1.0.0',
|
||||
templateId: 'sirsoft-basic',
|
||||
components: { basic: [], composite: [], layout: [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/lang/')) {
|
||||
return { ok: true, json: async () => ({}) };
|
||||
}
|
||||
if (url.includes('/api/layouts/')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({ data: { components: [], scripts: layoutScripts } }),
|
||||
};
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
});
|
||||
|
||||
(window as any).SirsoftBasic = {};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
window.document
|
||||
.querySelectorAll('script[data-g7le-canvas-script]')
|
||||
.forEach(el => el.remove());
|
||||
(window as any).G7Core = originalG7Core;
|
||||
delete (window as any).G7Config;
|
||||
delete (window as any).SirsoftBasic;
|
||||
ComponentRegistry.resetInstance();
|
||||
layoutScripts = [];
|
||||
});
|
||||
|
||||
/**
|
||||
* 문서 컨텍스트를 직접 주입해 캔버스를 렌더한다.
|
||||
*
|
||||
* 라우트 선택 → routes fetch → 문서 fetch 전체를 태우지 않고도, 캔버스가 실제로
|
||||
* `document.raw.scripts` 를 읽어 주입하는 그 경로를 그대로 지난다
|
||||
* (LayoutDocumentProvider 가 단일 진입점이다).
|
||||
*/
|
||||
const renderCanvas = () => {
|
||||
const engine = new TranslationEngine();
|
||||
const docValue = {
|
||||
document: {
|
||||
layoutName: 'main',
|
||||
raw: { components: [], scripts: layoutScripts },
|
||||
lockVersion: 0,
|
||||
},
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as any;
|
||||
|
||||
return render(
|
||||
React.createElement(
|
||||
TranslationProvider,
|
||||
{
|
||||
translationEngine: engine,
|
||||
translationContext: { templateId: 'sirsoft-admin_basic', locale: 'ko' },
|
||||
},
|
||||
React.createElement(
|
||||
LayoutEditorProvider,
|
||||
{ templateIdentifier: 'sirsoft-basic', initialLocale: 'ko' },
|
||||
React.createElement(
|
||||
LayoutDocumentProvider,
|
||||
{ value: docValue },
|
||||
React.createElement(PreviewCanvas)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
it('미신뢰 외부 src 는 주입하지 않고 경고만 남긴다', async () => {
|
||||
layoutScripts = [{ src: 'https://cdn.evil.com/x.js', id: 'evil' }];
|
||||
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Blocked untrusted script src')
|
||||
);
|
||||
});
|
||||
|
||||
expect(injectedScriptSrcs()).not.toContain('https://cdn.evil.com/x.js');
|
||||
});
|
||||
|
||||
it('authority 우회 형태도 주입하지 않는다', async () => {
|
||||
layoutScripts = [{ src: '/\\/evil.com/x.js', id: 'bypass' }];
|
||||
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Blocked untrusted script src')
|
||||
);
|
||||
});
|
||||
|
||||
expect(injectedScriptSrcs()).not.toContain('/\\/evil.com/x.js');
|
||||
});
|
||||
|
||||
it('same-origin 경로는 그대로 주입된다 (과차단 없음)', async () => {
|
||||
layoutScripts = [{ src: '/api/templates/assets/sirsoft-basic/x.js', id: 'ok' }];
|
||||
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(injectedScriptSrcs()).toContain('/api/templates/assets/sirsoft-basic/x.js');
|
||||
});
|
||||
});
|
||||
|
||||
it('선언된 신뢰 호스트는 주입된다', async () => {
|
||||
(window as any).G7Config = { trustedScriptHosts: ['cdn.ckeditor.com'] };
|
||||
layoutScripts = [{ src: 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.js', id: 'ck' }];
|
||||
|
||||
renderCanvas();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(injectedScriptSrcs()).toContain(
|
||||
'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.js'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+87
@@ -243,4 +243,91 @@ describe('useEditorTemplateAssets', () => {
|
||||
const langCall = fetchSpy.mock.calls.find((c) => /\/lang\/en\.json/.test(String(c[0])));
|
||||
expect(langCall).toBeDefined();
|
||||
});
|
||||
|
||||
/**
|
||||
* 편집 자산 매니페스트가 지시하는 `js` 는 서버 응답이지만, 붙는 자리는 **관리자 document** 다.
|
||||
* 확장 자산 재로드·프리뷰 캔버스와 같은 출처 게이트를 받아야 한다 — 이 경로만 게이트가
|
||||
* 없으면 편집기 진입만으로 임의 원격 코드가 관리자 세션에서 실행된다.
|
||||
*/
|
||||
describe('스크립트 주입 출처 게이트', () => {
|
||||
/**
|
||||
* 매니페스트가 주어진 js 목록을 돌려주도록 fetch 를 세운다.
|
||||
*
|
||||
* @param js 매니페스트 js 배열
|
||||
* @return void
|
||||
*/
|
||||
function mockManifest(js: string[]): void {
|
||||
fetchSpy.mockImplementation(async (url: string) => {
|
||||
if (url.includes('/editor-assets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: { identifier: 'sirsoft-basic', js, css: [], manifest_present: true },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/config.json')) return { ok: true, json: async () => ({ cache_version: 1 }) };
|
||||
if (url.includes('/components.json')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
version: '1.0.0',
|
||||
templateId: 'sirsoft-basic',
|
||||
components: { basic: [], composite: [], layout: [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes('/lang/')) return { ok: true, json: async () => ({}) };
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
(window as any).G7Config = { trustedScriptHosts: [] };
|
||||
// 주입된 태그가 영원히 pending 되지 않도록 즉시 load 를 발화시킨다
|
||||
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
|
||||
if (node.tagName === 'SCRIPT' || node.tagName === 'LINK') {
|
||||
document.body.appendChild(node);
|
||||
queueMicrotask(() => node.dispatchEvent(new Event('load')));
|
||||
return node;
|
||||
}
|
||||
return HTMLHeadElement.prototype.appendChild.call(document.head, node);
|
||||
}) as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
delete (window as any).G7Config;
|
||||
document.querySelectorAll('[data-g7le-asset]').forEach((n) => n.remove());
|
||||
});
|
||||
|
||||
it('미신뢰 외부 src 는 주입하지 않고 오류로 끝난다', async () => {
|
||||
mockManifest(['https://cdn.evil.com/x.js']);
|
||||
|
||||
const { result } = renderHook(() => useEditorTemplateAssets('sirsoft-basic', 'en'));
|
||||
|
||||
await waitFor(() => expect(result.current.error).not.toBeNull(), { timeout: 3000 });
|
||||
expect(
|
||||
document.querySelectorAll('script[data-g7le-asset="https://cdn.evil.com/x.js"]').length,
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it('same-origin src 는 주입된다 (과차단 없음)', async () => {
|
||||
mockManifest(['/api/templates/assets/sirsoft-basic/js/components.iife.js']);
|
||||
|
||||
renderHook(() => useEditorTemplateAssets('sirsoft-basic', 'en'));
|
||||
|
||||
// 게이트를 통과해 실제로 태그가 붙는지만 본다 — 그 뒤 부트스트랩(전역 확보 등)은
|
||||
// 이 축의 관심사가 아니다.
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(
|
||||
document.querySelectorAll(
|
||||
'script[data-g7le-asset="/api/templates/assets/sirsoft-basic/js/components.iife.js"]',
|
||||
).length,
|
||||
).toBe(1),
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
} from '../state/pageStateSimulator';
|
||||
import { trackPageState } from '../devtools/editorTrackers';
|
||||
import type { EditorStateItemSpec } from '../spec/specTypes';
|
||||
import { isAllowedScriptSrc, getTrustedScriptHosts } from '../../../support/scriptSrcPolicy';
|
||||
|
||||
export interface PreviewCanvasProps {
|
||||
/** components.json 매니페스트 — Chrome 에서 fetch 해 주입 */
|
||||
@@ -614,6 +615,15 @@ export function PreviewCanvas(props: PreviewCanvasProps = {}): React.ReactElemen
|
||||
const loaders: Promise<void>[] = [];
|
||||
for (const entry of scripts) {
|
||||
if (!entry?.src || typeof entry.src !== 'string') continue;
|
||||
// 프리뷰는 런타임 렌더의 미리보기다 — 런타임(TemplateApp)이 거부할 src 를
|
||||
// 관리자 document.head 에 주입하면 편집 중에만 임의 원격 코드가 실행된다.
|
||||
// 같은 판정·같은 결과(skip + 경고).
|
||||
if (!isAllowedScriptSrc(entry.src, getTrustedScriptHosts())) {
|
||||
console.warn(
|
||||
`[PreviewCanvas] Blocked untrusted script src (same-origin path or declared trusted host required): ${entry.src}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const sel = entry.id
|
||||
? `script#${CSS.escape(entry.id)}, script[data-g7le-canvas-script="${entry.src}"]`
|
||||
: `script[data-g7le-canvas-script="${entry.src}"], script[src="${entry.src}"]`;
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
} from '../types/editorErrors';
|
||||
import { reseedPendingIntoEngine } from './pendingCustomTranslations';
|
||||
import { suffixed } from '../../../support/assetUrl';
|
||||
import { isAllowedScriptSrc, getTrustedScriptHosts } from '../../../support/scriptSrcPolicy';
|
||||
|
||||
export interface EditorTemplateAssetsState {
|
||||
componentRegistry: ComponentRegistry | null;
|
||||
@@ -121,6 +122,17 @@ function injectScript(src: string): Promise<void> {
|
||||
reject(new Error('document undefined'));
|
||||
return;
|
||||
}
|
||||
// 출처 게이트 — 이 src 는 서버 응답(editor-assets manifest)이 지시하는 값이고,
|
||||
// 붙는 자리는 관리자 document 다. 확장 자산 재로드(reloadModuleHandlers)·프리뷰 캔버스와
|
||||
// 같은 판정을 받는다. 정상 템플릿 자산 URL 은 전부 `/api/...` same-origin 이다.
|
||||
if (!isAllowedScriptSrc(src, getTrustedScriptHosts())) {
|
||||
reject(
|
||||
new Error(
|
||||
`Blocked untrusted script src (same-origin path or declared trusted host required): ${src}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const existing = document.querySelector(`script[data-g7le-asset="${src}"]`);
|
||||
if (existing) {
|
||||
// 이미 로드된 상태로 간주 (실패한 경우라도 재시도는 페이지 새로고침으로)
|
||||
|
||||
Reference in new issue
Block a user