fix(core,basic): 검색 봇 화면 렌더러 패리티 결손 일괄 수정

일반 화면(React)과 봇 화면(PHP)은 같은 레이아웃을 각각 렌더하는데 봇
화면 쪽 지원 범위가 뒤처져, 확장이 교체한 본문이 통째로 빈 채 나갔다
(공개 이슈 ). 같은 결손 계열을 전수 조사해 함께 닫는다.

- 확장 주입 props 를 렌더 진입 시점에 해석해 자손 전체에 상속
 → 게시글·답글 원글·댓글·페이지·상품 설명 5개 지점 복구
- 사용자 작성 HTML 정화기 신설 — isHtml 판정에 따라 이스케이프/정화.
 미정화 상태에서 봇 경로로 저장형 스크립트가 실제 실행됐다
- 노드 키 패리티: conditions / type:iterator / responsive 매칭 규칙 /
 children 문자열 / text 우선순위 / $t:defer / 레이아웃 초기 상태
- 표현식: 단일 바인딩 판정 교체, ||·&& 를 값 반환(JS 시맨틱)으로,
 비교식이 raw 경로에서 null 이 되던 문제
- 데이터소스: 엔드포인트 표현식 전면 해석 + 레이아웃 8곳 선언 보강
- 봇 페이지 캐시 1회 전량 무효화 업그레이드 스텝

지원 범위 SSoT 표를 문서에 고정하고, 한쪽만 고치는 것을 막는 검사 룰과
레이아웃 전수 순회 테스트로 잠갔다.
This commit is contained in:
HeuJung committed 2026-07-27 10:03:06 +09:00
1 parent b505ac7ba7
commit 0dfb45951b
34 files changed
+5244 -172

No files matched your search

+575 -60
View File
@@ -4,6 +4,25 @@ namespace App\Seo;
class ComponentHtmlMapper
{
/**
* SEO 렌더링 기준 뷰포트 폭 (px)
*
* 검색 봇은 데스크톱으로 간주하므로 responsive 오버라이드 매칭에 이 값을 사용합니다.
*/
private const DESKTOP_VIEWPORT_WIDTH = 1024;
/**
* responsive 브레이크포인트 프리셋 → [min, max] 폭 범위 (px)
*
* React ResponsiveManager.ts 의 BREAKPOINT_PRESETS 와 동일한 값입니다.
*/
private const BREAKPOINT_PRESETS = [
'mobile' => [0, 767],
'tablet' => [768, 1023],
'desktop' => [1024, PHP_INT_MAX],
'portable' => [0, 1023],
];
/**
* 템플릿 제공 컴포넌트 매핑 (seo-config.json의 component_map)
*/
@@ -61,6 +80,21 @@ class ComponentHtmlMapper
*/
private array $fieldsContext = [];
/**
* 사용자 작성 HTML 정화기 (raw 렌더 모드에서 지연 생성)
*/
private ?HtmlSanitizer $htmlSanitizer = null;
/**
* `value` prop 을 텍스트로 승격하지 않는 태그 목록
*
* 폼 컨트롤의 `value` 는 현재 선택값(속성)이지 화면에 보이는 글자가 아닙니다.
* React 는 `<select>` 안에 `<option>` 라벨을 그리므로, 봇 화면에서만 `value` 가
* 글자로 노출되면(예: `<select>created_at_desc</select>`) 두 화면이 어긋나고
* 색인에도 내부 식별자가 섞입니다.
*/
private const VALUE_NOT_TEXT_TAGS = ['select', 'option', 'input', 'textarea', 'progress', 'meter'];
/**
* 템플릿 제공 컴포넌트 매핑을 설정합니다.
*
@@ -157,6 +191,15 @@ class ComponentHtmlMapper
$html = '';
foreach ($components as $component) {
// children 배열 내 문자열 = 텍스트 노드
// React DynamicRenderer 는 이 문자열을 그대로 반환한다(표현식·번역 미해석).
// SEO 가 여기서 표현식을 해석하면 반대 방향의 패리티 격차가 생기므로,
// 이스케이프만 하고 리터럴로 출력한다.
if (is_string($component)) {
$html .= e($component);
continue;
}
if (! is_array($component)) {
continue;
}
@@ -176,27 +219,24 @@ class ComponentHtmlMapper
*/
private function renderComponent(array $component, array $context, ExpressionEvaluator $evaluator): string
{
// SEO는 데스크톱 뷰로 렌더링 (검색 봇 = 데스크톱)
// responsive.desktop 오버라이드를 기본 속성에 병합
if (isset($component['responsive']['desktop'])) {
$desktop = $component['responsive']['desktop'];
if (isset($desktop['props'])) {
$component['props'] = array_merge($component['props'] ?? [], $desktop['props']);
}
if (isset($desktop['if'])) {
$component['if'] = $desktop['if'];
}
if (isset($desktop['text'])) {
$component['text'] = $desktop['text'];
}
}
// Extension Point 주입 컴포넌트의 props를 평가 컨텍스트에 주입
// LayoutExtensionService가 호스트 props를 주입 컴포넌트 최상위 extensionPointProps로
// 부착하므로, 여기서 해석해 컨텍스트에 넣어야 {{extensionPointProps.xxx}}가 평가된다.
// $context는 값 전달이므로 이 노드의 서브트리에만 상속되고 형제로 새지 않는다
// (React DynamicRenderer의 extendedDataContext 전파와 동형).
// if/iteration 평가에도 이미 반영되어야 하므로 가장 먼저 처리한다.
$this->injectExtensionPointContext($component, $context, $evaluator);
// 조건부 렌더링 (if)
if (isset($component['if'])) {
$condition = $evaluator->evaluate($component['if'], $context);
if ($condition === '' || $condition === 'false' || $condition === '0') {
return '';
}
// type: "iterator" → iteration 속성으로 변환 (React DynamicRenderer와 동일 매핑)
$component = $this->normalizeIteratorNode($component);
// SEO는 데스크톱 뷰로 렌더링 (검색 봇 = 데스크톱)
// 데스크톱 폭에 매칭되는 responsive 오버라이드를 기본 속성에 병합
$component = $this->applyResponsiveOverrides($component);
// 조건부 렌더링 (if / condition / conditions)
if (! $this->shouldRender($component, $context, $evaluator)) {
return '';
}
// 반복 렌더링 (iteration)
@@ -260,9 +300,375 @@ class ComponentHtmlMapper
return $html;
}
/**
* Extension Point 주입 컴포넌트의 props를 평가 컨텍스트에 주입합니다.
*
* LayoutExtensionService는 extension_point 호스트의 props를 주입 컴포넌트 최상위
* `extensionPointProps` 키로 부착합니다. 주입 컴포넌트는 `{{extensionPointProps.content}}`
* 형태로 그 값을 참조하므로, 렌더링 전에 표현식을 해석해 컨텍스트에 넣어야 합니다.
*
* 해석된 값은 이 노드와 그 자손 전체에 상속됩니다 (React DynamicRenderer가
* extendedDataContext를 자식에게 전달하는 동작과 동일).
*
* `extensionPointCallbacks`는 의도적으로 주입하지 않습니다 — SEO 파이프라인에는
* 액션 디스패처가 없고, 액션 배열을 컨텍스트에 넣으면 HTML에 JSON 파편이
* 노출될 수 있습니다.
*
* @param array $component 컴포넌트 정의 (해석 후 extensionPointProps 키 제거)
* @param array $context 데이터 컨텍스트 (해석된 값이 주입됨)
* @param ExpressionEvaluator $evaluator 표현식 평가기
*/
private function injectExtensionPointContext(array &$component, array &$context, ExpressionEvaluator $evaluator): void
{
if (! isset($component['extensionPointProps']) || ! is_array($component['extensionPointProps'])) {
return;
}
$context['extensionPointProps'] = $this->resolveAllProps(
$component['extensionPointProps'],
$context,
$evaluator
);
// iteration 재진입 시 항목별로 재해석되지 않도록 제거
// (React는 바깥 컨텍스트 기준 1회 해석 후 상속)
unset($component['extensionPointProps']);
}
/**
* `type: "iterator"` 노드를 `iteration` 속성 형태로 정규화합니다.
*
* React DynamicRenderer가 `{ type: "iterator", data, itemName, indexName }` 를
* `iteration: { source, item_var, index_var }` 로 변환하는 것과 동일합니다.
*
* @param array $component 컴포넌트 정의
* @return array 정규화된 컴포넌트 정의
*/
private function normalizeIteratorNode(array $component): array
{
if (($component['type'] ?? null) !== 'iterator' || ! isset($component['data'])) {
return $component;
}
$component['iteration'] = [
'source' => $component['data'],
'item_var' => $component['itemName'] ?? 'item',
'index_var' => $component['indexName'] ?? null,
];
unset($component['data'], $component['itemName'], $component['indexName']);
return $component;
}
/**
* 데스크톱 폭에 해당하는 responsive 오버라이드를 병합합니다.
*
* SEO는 검색 봇을 데스크톱 뷰포트로 간주하므로 `desktop` 프리셋과 데스크톱 폭
* (1024px 이상)을 포함하는 숫자 범위 키만 적용합니다. mobile/tablet/portable 은
* 데스크톱에서 매칭되지 않으므로 무시합니다.
*
* 오버라이드 항목은 React와 동일하게 props/if/text/children/iteration 입니다.
*
* @param array $component 컴포넌트 정의
* @return array 오버라이드가 병합된 컴포넌트 정의
*/
private function applyResponsiveOverrides(array $component): array
{
if (empty($component['responsive']) || ! is_array($component['responsive'])) {
return $component;
}
$breakpoint = $this->matchingBreakpointKey($component['responsive']);
if ($breakpoint === null) {
return $component;
}
$override = $component['responsive'][$breakpoint];
if (isset($override['props'])) {
$component['props'] = array_merge($component['props'] ?? [], $override['props']);
}
foreach (['if', 'text', 'children', 'iteration'] as $key) {
if (isset($override[$key])) {
$component[$key] = $override[$key];
}
}
return $component;
}
/**
* 데스크톱 폭에 매칭되는 responsive 키를 하나만 고릅니다.
*
* React `ResponsiveManager::getMatchingKey()` 와 동일한 우선순위를 따릅니다:
* ① 커스텀 범위가 프리셋보다 우선 ② 좁은 범위가 넓은 범위보다 우선.
* 매칭되는 키를 전부 순차 병합하면 JSON 키 선언 순서에 따라 결과가 달라진다.
*
* @param array $responsive responsive 오버라이드 맵
* @return string|null 적용할 키 (없으면 null)
*/
private function matchingBreakpointKey(array $responsive): ?string
{
$matched = [];
foreach ($responsive as $breakpoint => $override) {
if (! is_array($override)) {
continue;
}
$range = $this->parseBreakpointRange((string) $breakpoint);
if ($range === null) {
continue;
}
[$min, $max] = $range;
if ($min > self::DESKTOP_VIEWPORT_WIDTH || $max < self::DESKTOP_VIEWPORT_WIDTH) {
continue;
}
$matched[] = [
'key' => (string) $breakpoint,
'isPreset' => isset(self::BREAKPOINT_PRESETS[$breakpoint]),
'width' => $max - $min,
];
}
if ($matched === []) {
return null;
}
usort($matched, function (array $a, array $b): int {
if ($a['isPreset'] !== $b['isPreset']) {
return $a['isPreset'] ? 1 : -1;
}
return $a['width'] <=> $b['width'];
});
return $matched[0]['key'];
}
/**
* responsive 브레이크포인트 키를 [min, max] 범위로 파싱합니다.
*
* 프리셋(`desktop`/`portable`/`mobile`/`tablet`)과 `1024-`, `1280-1535`,
* `-599` 같은 숫자 범위를 지원합니다. `min > max` 인 잘못된 범위는 무시합니다
* (React `ResponsiveManager::parseRange()` 와 동일).
*
* @param string $breakpoint 브레이크포인트 키
* @return array{0: int, 1: int}|null [min, max] (파싱 불가 시 null)
*/
private function parseBreakpointRange(string $breakpoint): ?array
{
if (isset(self::BREAKPOINT_PRESETS[$breakpoint])) {
return self::BREAKPOINT_PRESETS[$breakpoint];
}
if (! preg_match('/^(-?\d*)-(-?\d*)$/', $breakpoint, $matches)) {
return null;
}
$min = $matches[1] === '' ? 0 : (int) $matches[1];
$max = $matches[2] === '' ? PHP_INT_MAX : (int) $matches[2];
return $min <= $max ? [$min, $max] : null;
}
/**
* 컴포넌트를 렌더링해야 하는지 판정합니다 (if / condition / conditions).
*
* React RenderHelpers.evaluateRenderCondition과 동일한 우선순위를 따릅니다:
* `if` → `condition`(별칭) → `conditions`(AND/OR 그룹 또는 if/else 체인).
*
* @param array $component 컴포넌트 정의
* @param array $context 데이터 컨텍스트
* @param ExpressionEvaluator $evaluator 표현식 평가기
* @return bool 렌더링 대상이면 true
*/
private function shouldRender(array $component, array $context, ExpressionEvaluator $evaluator): bool
{
if (isset($component['if'])) {
return $this->evaluateBooleanExpression($component['if'], $context, $evaluator);
}
if (isset($component['condition'])) {
return $this->evaluateBooleanExpression($component['condition'], $context, $evaluator);
}
if (! isset($component['conditions'])) {
return true;
}
return $this->evaluateConditions($component['conditions'], $context, $evaluator);
}
/**
* conditions 속성(AND/OR 그룹 또는 if/else 체인)을 평가합니다.
*
* - 문자열 / `{and: [...]}` / `{or: [...]}` → 조건식 평가
* - `[{if: ...}, {if: ...}, {}]` → 하나라도 매칭되면 true (if 없는 항목은 else 브랜치)
* - 위 어느 형식도 아니면 **렌더링**한다 — React `evaluateRenderCondition()` 이 알 수 없는
* 형식에 대해 경고 후 true 를 반환하므로, 여기서 false 를 주면 봇 화면에서만 노드가 사라진다.
*
* @param mixed $conditions conditions 속성 값
* @param array $context 데이터 컨텍스트
* @param ExpressionEvaluator $evaluator 표현식 평가기
* @return bool 평가 결과
*/
private function evaluateConditions(mixed $conditions, array $context, ExpressionEvaluator $evaluator): bool
{
if ($this->isConditionExpression($conditions)) {
return $this->evaluateConditionExpression($conditions, $context, $evaluator);
}
if ($this->isConditionBranches($conditions)) {
foreach ($conditions as $branch) {
if (! is_array($branch)) {
continue;
}
// if 없는 항목 = else 브랜치 (항상 매칭)
if (! isset($branch['if'])) {
return true;
}
if ($this->evaluateConditionExpression($branch['if'], $context, $evaluator)) {
return true;
}
}
return false;
}
// 알 수 없는 형식 → 렌더링 (React 동형)
return true;
}
/**
* 값이 단일 ConditionExpression(문자열 / `{and:[]}` / `{or:[]}`) 인지 판정합니다.
*
* React `ConditionEvaluator.isConditionExpression()` 과 동일한 판정입니다.
*
* @param mixed $value 판정 대상
* @return bool ConditionExpression 이면 true
*/
private function isConditionExpression(mixed $value): bool
{
if (is_string($value) || is_bool($value)) {
return true;
}
if (is_array($value) && ! array_is_list($value)) {
return array_key_exists('and', $value) || array_key_exists('or', $value);
}
return false;
}
/**
* 값이 ConditionBranch[] 인지 판정합니다.
*
* 빈 배열은 브랜치 배열로 보지 않으며, 첫 항목에 `if` 또는 `then` 이 있어야 합니다
* (React `ConditionEvaluator.isConditionBranches()` 와 동일).
*
* @param mixed $value 판정 대상
* @return bool ConditionBranch[] 이면 true
*/
private function isConditionBranches(mixed $value): bool
{
if (! is_array($value) || ! array_is_list($value) || $value === []) {
return false;
}
$first = $value[0];
if (! is_array($first)) {
return false;
}
return array_key_exists('if', $first) || array_key_exists('then', $first);
}
/**
* 조건식(문자열 또는 AND/OR 그룹)을 평가합니다.
*
* 빈 AND 그룹은 true, 빈 OR 그룹은 false 를 반환합니다 (React와 동일).
*
* @param mixed $condition 조건식
* @param array $context 데이터 컨텍스트
* @param ExpressionEvaluator $evaluator 표현식 평가기
* @return bool 평가 결과
*/
private function evaluateConditionExpression(mixed $condition, array $context, ExpressionEvaluator $evaluator): bool
{
if (! is_array($condition)) {
return $this->evaluateBooleanExpression($condition, $context, $evaluator);
}
if (array_key_exists('and', $condition)) {
if (! is_array($condition['and']) || $condition['and'] === []) {
return true;
}
foreach ($condition['and'] as $sub) {
if (! $this->evaluateConditionExpression($sub, $context, $evaluator)) {
return false;
}
}
return true;
}
if (array_key_exists('or', $condition)) {
if (! is_array($condition['or']) || $condition['or'] === []) {
return false;
}
foreach ($condition['or'] as $sub) {
if ($this->evaluateConditionExpression($sub, $context, $evaluator)) {
return true;
}
}
return false;
}
// 알 수 없는 조건 형식
return false;
}
/**
* 단일 조건 표현식을 boolean으로 평가합니다.
*
* 문자열 결과의 falsy 판정 목록은 React RenderHelpers.evaluateIfCondition과
* 동일합니다 (`''`, `false`, `0`, `null`, `undefined` — 대소문자·공백 무시).
*
* @param mixed $condition 조건 표현식 (문자열 또는 boolean)
* @param array $context 데이터 컨텍스트
* @param ExpressionEvaluator $evaluator 표현식 평가기
* @return bool 평가 결과
*/
private function evaluateBooleanExpression(mixed $condition, array $context, ExpressionEvaluator $evaluator): bool
{
if (is_bool($condition)) {
return $condition;
}
// 조건이 비어 있으면 조건 없음으로 간주 (React: `if (!ifCondition) return true`)
if ($condition === null || $condition === '') {
return true;
}
$resolved = $evaluator->evaluate((string) $condition, $context);
return ! in_array(strtolower(trim($resolved)), ['', 'false', '0', 'null', 'undefined'], true);
}
/**
* 선언적 렌더 모드로 컴포넌트를 HTML로 변환합니다.
*
* 우선순위가 renderTag() 와 반대인 것은 의도된 것이다 — renderTag() 는 text 를
* children 보다 먼저 쓰지만(React DynamicRenderer 동형), 이 경로는 자체 렌더링을
* 가진 집합 컴포넌트(Select·Pagination·HtmlContent 등) 전용이라 모드 출력이 먼저다.
* React 에서도 Select 는 options prop 으로 스스로 option 을 그리고 text/children 을
* 무시하므로, 여기서 text 를 우선하면 옵션 목록이 통째로 사라져 오히려 어긋난다.
*
* @param string $mode 렌더 모드명 (render_modes 키)
* @param string $tag 외부 래퍼 HTML 태그
* @param array $configEntry seo-config.json의 component_map 엔트리
@@ -298,7 +704,7 @@ class ComponentHtmlMapper
// 텍스트 콘텐츠 fallback
if ($innerHtml === '') {
$innerHtml = $this->resolveTextContent($component, $props, $context, $evaluator);
$innerHtml = $this->resolveTextContent($component, $props, $context, $evaluator, $tag);
}
return "<{$tag}{$attrs}>{$innerHtml}</{$tag}>";
@@ -322,17 +728,26 @@ class ComponentHtmlMapper
return "<{$tag}{$attrs}>";
}
$innerHtml = $this->renderChildren($component, $context, $evaluator);
// 노드 레벨 text가 있으면 children보다 우선 (React DynamicRenderer와 동일 우선순위).
// text 키가 있으면 해석 결과가 빈 문자열이어도 그것이 최종 값이다 — React 는
// text !== undefined 인 순간 children 경로로 내려가지 않는다(DynamicRenderer.tsx:2591,2639).
$nodeText = $this->resolveNodeText($component, $context, $evaluator);
if ($innerHtml === '') {
$innerHtml = $this->resolveTextContent($component, $props, $context, $evaluator);
if ($nodeText !== null) {
$innerHtml = $nodeText;
} else {
$innerHtml = $this->renderChildren($component, $context, $evaluator);
if ($innerHtml === '') {
$innerHtml = $this->resolveTextContent($component, $props, $context, $evaluator, $tag);
}
}
// dangerouslySetInnerHTML 처리
// dangerouslySetInnerHTML 처리 — 일반 화면과 동일 강도로 정화 후 삽입
if ($innerHtml === '' && isset($props['dangerouslySetInnerHTML'])) {
$rawHtml = $evaluator->evaluate((string) $props['dangerouslySetInnerHTML'], $context);
if ($rawHtml !== '') {
$innerHtml = $rawHtml;
$innerHtml = $this->htmlSanitizer()->sanitize($rawHtml);
}
}
@@ -387,39 +802,37 @@ class ComponentHtmlMapper
$html = '';
foreach ($data as $item) {
if ($itemAttrs) {
// 속성 기반 렌더링 (이미지 갤러리 등)
$attrStr = '';
foreach ($itemAttrs as $attrName => $fieldPattern) {
$value = $this->resolveFieldPattern($fieldPattern, $item);
if ($value !== '') {
// src 속성의 상대 경로를 절대 경로로 변환
if ($attrName === 'src' && ! str_starts_with($value, 'http')) {
$value = url($value);
}
$attrStr .= " {$attrName}=\"".e($value).'"';
$attrStr = $itemAttrs ? $this->buildIterateItemAttributes($itemAttrs, $item) : '';
if ($itemContent !== null) {
// 콘텐츠 기반 렌더링 (탭 리스트, 선택 목록 등)
// item_attrs 가 함께 선언되면 속성과 라벨을 모두 그린다 — `<option value="x">라벨</option>`
// 처럼 둘이 다 필요한 요소를 표현하기 위함이다.
$content = $this->resolveFieldPattern($itemContent, $item);
$evaluatedContent = $content === ''
? ''
: e($evaluator->evaluate((string) $content, $context));
if ($evaluatedContent === '' && $attrStr === '') {
continue;
}
$badge = '';
if ($badgeField && isset($item[$badgeField])) {
$evaluatedBadge = $evaluator->evaluate((string) $item[$badgeField], $context);
if ($evaluatedBadge !== '' && $evaluatedBadge !== '0') {
$badge = ' <span>('.e($evaluatedBadge).')</span>';
}
}
$html .= "<{$itemTag}{$attrStr}>".$evaluatedContent.$badge."</{$itemTag}>";
} elseif ($itemAttrs) {
// 속성 기반 렌더링 (이미지 갤러리 등)
if (in_array($itemTag, $this->selfClosing)) {
$html .= "<{$itemTag}{$attrStr}>";
} else {
$html .= "<{$itemTag}{$attrStr}></{$itemTag}>";
}
} elseif ($itemContent !== null) {
// 콘텐츠 기반 렌더링 (탭 리스트 등)
$content = $this->resolveFieldPattern($itemContent, $item);
if ($content !== '') {
$evaluatedContent = e($evaluator->evaluate((string) $content, $context));
$badge = '';
if ($badgeField && isset($item[$badgeField])) {
$evaluatedBadge = $evaluator->evaluate((string) $item[$badgeField], $context);
if ($evaluatedBadge !== '' && $evaluatedBadge !== '0') {
$badge = ' <span>('.e($evaluatedBadge).')</span>';
}
}
$html .= "<{$itemTag}>".$evaluatedContent.$badge."</{$itemTag}>";
}
} else {
// 단순 아이템 (문자열)
$value = is_string($item) ? e($item) : '';
@@ -430,6 +843,34 @@ class ComponentHtmlMapper
return $html;
}
/**
* iterate 모드 아이템의 속성 문자열을 만듭니다.
*
* @param array $itemAttrs render_modes 의 item_attrs 정의
* @param mixed $item 현재 아이템
* @return string 속성 문자열 (앞에 공백 포함, 없으면 빈 문자열)
*/
private function buildIterateItemAttributes(array $itemAttrs, mixed $item): string
{
$attrStr = '';
foreach ($itemAttrs as $attrName => $fieldPattern) {
$value = $this->resolveFieldPattern($fieldPattern, $item);
if ($value === '') {
continue;
}
// src 속성의 상대 경로를 절대 경로로 변환
if ($attrName === 'src' && ! str_starts_with($value, 'http')) {
$value = url($value);
}
$attrStr .= " {$attrName}=\"".e($value).'"';
}
return $attrStr;
}
/**
* format 타입: 포맷 문자열의 {key} 플레이스홀더를 props로 치환
*
@@ -492,7 +933,14 @@ class ComponentHtmlMapper
}
/**
* raw 타입: 원본 HTML/텍스트를 그대로 출력
* raw 타입: 콘텐츠를 `isHtml` 판정에 따라 평문 또는 정화된 HTML 로 출력
*
* 일반 화면의 `HtmlContent` 컴포지트와 동일한 규칙입니다.
* - `isHtml=false` → 평문 (전체 이스케이프)
* - `isHtml=true`(기본) → 정화 후 HTML 로 출력
*
* 정화·이스케이프를 생략하면 봇 화면에서만 사용자 작성 `<script>` 가 살아남아,
* 주소에 봇 파라미터를 붙이는 것만으로 실행됩니다.
*
* @param array $modeConfig render_modes 엔트리
* @param array $configEntry component_map 엔트리
@@ -515,7 +963,28 @@ class ComponentHtmlMapper
return '';
}
return $evaluator->evaluate((string) $contentExpr, $context);
$content = $evaluator->evaluate((string) $contentExpr, $context);
if ($content === '') {
return '';
}
// isHtml 미지정은 HTML 로 간주 (HtmlContent 의 기본값 isHtml = true 와 동일)
if (! $this->evaluateBooleanExpression($props['isHtml'] ?? true, $context, $evaluator)) {
return e($content);
}
return $this->htmlSanitizer()->sanitize($content);
}
/**
* HTML 정화기를 반환합니다 (지연 생성).
*
* @return HtmlSanitizer 정화기
*/
private function htmlSanitizer(): HtmlSanitizer
{
return $this->htmlSanitizer ??= new HtmlSanitizer;
}
/**
@@ -1077,18 +1546,22 @@ class ComponentHtmlMapper
* @param ExpressionEvaluator $evaluator 표현식 평가기
* @return string 텍스트 콘텐츠
*/
private function resolveTextContent(array $component, array $props, array $context, ExpressionEvaluator $evaluator): string
private function resolveTextContent(array $component, array $props, array $context, ExpressionEvaluator $evaluator, string $tag = ''): string
{
// 1. 컴포넌트 레벨 text 속성 (최우선)
if (isset($component['text'])) {
$text = $evaluator->evaluate((string) $component['text'], $context);
if ($text !== '') {
return e($text);
}
// 1. 컴포넌트 레벨 text 속성 (최우선) — 키가 있으면 빈 값이어도 그것이 최종 값
$nodeText = $this->resolveNodeText($component, $context, $evaluator);
if ($nodeText !== null) {
return $nodeText;
}
$skipValueProp = in_array(strtolower($tag), self::VALUE_NOT_TEXT_TAGS, true);
// 2. props 레벨 텍스트 추출 (seo-config.json의 text_props)
foreach ($this->textProps as $textProp) {
if ($textProp === 'value' && $skipValueProp) {
continue;
}
if (isset($props[$textProp])) {
$text = $evaluator->evaluate((string) $props[$textProp], $context);
if ($text !== '') {
@@ -1100,6 +1573,40 @@ class ComponentHtmlMapper
return '';
}
/**
* 노드 레벨 text 속성을 해석합니다.
*
* @param array $component 컴포넌트 정의
* @param array $context 데이터 컨텍스트
* @param ExpressionEvaluator $evaluator 표현식 평가기
* @return string 이스케이프된 텍스트 (없으면 빈 문자열)
*/
private function resolveNodeText(array $component, array $context, ExpressionEvaluator $evaluator): ?string
{
if (! array_key_exists('text', $component)) {
return null;
}
$expression = (string) $component['text'];
// JSX 시맨틱: bool / null 은 렌더되지 않는다.
// React 는 단일 바인딩 text 를 raw 값으로 받아 그대로 자식에 넘기므로
// {false} / {null} 이 화면에 나오지 않는다 (DynamicRenderer.tsx 의 renderChildren).
// 문자열화하면 'false' 라는 글자가 봇 화면에만 노출된다.
//
// 판정에만 evaluateRaw 를 쓰고 출력은 evaluate 로 만든다 — evaluate 가 파이프·인라인
// `$t:` 토큰 후처리를 담당하므로, 이를 건너뛰면 `?? '$t:key'` 같은 폴백 문자열의
// 번역 토큰이 봇 화면에 그대로 남는다.
$resolved = $evaluator->evaluateRaw($expression, $context);
if (is_bool($resolved) || $resolved === null) {
return '';
}
$text = $evaluator->evaluate($expression, $context);
return $text === '' ? '' : e($text);
}
/**
* 반복 렌더링을 처리합니다.
*
@@ -1134,6 +1641,14 @@ class ComponentHtmlMapper
$templateComponent = $component;
unset($templateComponent['iteration']);
// responsive 오버라이드가 항목 렌더링 시 iteration을 다시 주입해
// 무한 재귀가 되지 않도록 함께 제거한다.
if (isset($templateComponent['responsive']) && is_array($templateComponent['responsive'])) {
foreach (array_keys($templateComponent['responsive']) as $breakpoint) {
unset($templateComponent['responsive'][$breakpoint]['iteration']);
}
}
$html = '';
foreach (array_values($data) as $index => $item) {
$iterContext = array_merge($context, [
+25 -13
View File
@@ -15,12 +15,18 @@ class DataSourceResolver
* @param array $routeParams 라우트 파라미터 (예: ['id' => '123', 'slug' => 'clothes'])
* @param string $locale 로케일
* @param array $queryParams URL 쿼리 파라미터 (예: ['page' => '2', 'sort' => 'latest'])
* @param array $extraContext 엔드포인트/params 표현식 평가에 사용할 추가 컨텍스트 (_global 등)
* @return array data_source ID → 응답 데이터 매핑
*/
public function resolve(array $dataSources, array $seoDataSourceIds, array $routeParams, string $locale, array $queryParams = []): array
public function resolve(array $dataSources, array $seoDataSourceIds, array $routeParams, string $locale, array $queryParams = [], array $extraContext = []): array
{
$context = [];
$evalContext = array_merge($extraContext, [
'route' => array_merge($extraContext['route'] ?? [], $routeParams),
'query' => $queryParams,
]);
foreach ($dataSources as $ds) {
$dsId = $ds['id'] ?? '';
@@ -34,11 +40,11 @@ class DataSourceResolver
continue;
}
// 라우트 파라미터 치환 (예: {{route.id}} → 123)
$endpoint = $this->resolveEndpoint($endpoint, $routeParams);
// 엔드포인트 표현식 치환 ({{route.id}}, {{query.q}}, {{_global.xxx}})
$endpoint = $this->resolveEndpoint($endpoint, $evalContext);
// params 해석 ({{query.xxx}}, {{route.xxx}} 표현식 치환)
$resolvedParams = $this->resolveParams($ds['params'] ?? [], $routeParams, $queryParams);
$resolvedParams = $this->resolveParams($ds['params'] ?? [], $routeParams, $queryParams, $extraContext);
// API 호출
$data = $this->callApi($endpoint, $ds, $locale, $resolvedParams);
@@ -51,16 +57,21 @@ class DataSourceResolver
/**
* 엔드포인트의 표현식을 치환합니다.
*
* `{{route.xxx}}` 뿐 아니라 `{{query.xxx}}` / `{{_global.xxx}}` 등 컨텍스트 표현식을
* 모두 해석합니다 — 검색 결과처럼 엔드포인트 문자열 안에서 쿼리·전역 상태를 보간하는
* 데이터소스가 있기 때문입니다. 미해석 시 표현식이 URL에 그대로 남아 호출이 실패합니다.
*
* @param string $endpoint 원본 엔드포인트
* @param array $routeParams 라우트 파라미터
* @param array $evalContext 평가 컨텍스트 (route/query/_global 등)
* @return string 치환된 엔드포인트
*/
private function resolveEndpoint(string $endpoint, array $routeParams): string
private function resolveEndpoint(string $endpoint, array $evalContext): string
{
// {{route.xxx}} 및 {{route?.xxx}} 패턴 치환 (optional chaining 포함)
return (string) preg_replace_callback('/\{\{route\??\.(\w+)\}\}/', function ($matches) use ($routeParams) {
return $routeParams[$matches[1]] ?? '';
}, $endpoint);
if (! str_contains($endpoint, '{{')) {
return $endpoint;
}
return app(ExpressionEvaluator::class)->evaluate($endpoint, $evalContext);
}
/**
@@ -72,19 +83,20 @@ class DataSourceResolver
* @param array $params 원본 params 정의
* @param array $routeParams 라우트 파라미터
* @param array $queryParams 쿼리 파라미터
* @param array $extraContext 추가 평가 컨텍스트 (_global 등)
* @return array 해석된 params (키 → 값)
*/
private function resolveParams(array $params, array $routeParams, array $queryParams): array
private function resolveParams(array $params, array $routeParams, array $queryParams, array $extraContext = []): array
{
if (empty($params)) {
return [];
}
$resolved = [];
$evalContext = [
$evalContext = array_merge($extraContext, [
'route' => $routeParams,
'query' => $queryParams,
];
]);
$evaluator = app(ExpressionEvaluator::class);
+130 -18
View File
@@ -83,8 +83,9 @@ class ExpressionEvaluator
public function evaluateRaw(string $expression, array $context): mixed
{
// 단일 {{expr}} 패턴인 경우 원본 값 반환
if (preg_match('/^\{\{(.+?)\}\}$/', trim($expression), $matches)) {
$expr = trim($matches[1]);
$trimmed = trim($expression);
if ($this->isSingleBinding($trimmed)) {
$expr = trim(substr($trimmed, 2, -2));
// 파이프 표현식: 원본 값을 파이프로 변환 후 반환
if (PipeRegistry::hasPipes($expr)) {
@@ -101,6 +102,14 @@ class ExpressionEvaluator
return $value;
}
// 비교·논리 연산은 참/거짓 값으로 돌려준다.
// `resolveToValue()` 는 경로/리터럴 해석기라 `(a ?? 'text') === 'html'` 같은
// 비교식을 null 로 되돌린다. 그 null 이 확장 주입 props 의 기본값으로 흘러들면
// (예: `isHtml ?? true`) 레이아웃이 선언한 판정이 통째로 뒤집힌다.
if ($this->isBooleanExpression($expr)) {
return $this->coerceBooleanString($this->evaluate($trimmed, $context));
}
// 연산자/함수 호출/리터럴이 포함된 표현식은 resolveToValue로 처리
if (str_contains($expr, '??') || str_contains($expr, '?') || preg_match('/[\w$]+\s*\(/', $expr)
|| str_starts_with($expr, '{') || str_contains($expr, '...')) {
@@ -114,6 +123,105 @@ class ExpressionEvaluator
return $this->evaluate($expression, $context);
}
/**
* 표현식이 비교·논리 연산인지 판정합니다.
*
* 삼항(`? :`)과 화살표 함수(`=>`)는 결과가 참/거짓이 아니므로 제외합니다
* (`??` 와 `?.` 은 삼항이 아니라 제외 대상에서 먼저 걷어냅니다).
*
* @param string $expr `{{}}` 를 벗겨낸 표현식
* @return bool 비교·논리 연산이면 true
*/
private function isBooleanExpression(string $expr): bool
{
$normalized = str_replace(['??', '?.'], '', $expr);
if (str_contains($normalized, '=>') || str_contains($normalized, '?')) {
return false;
}
if (str_starts_with(trim($expr), '!')) {
return true;
}
return preg_match('/(===|!==|==|!=|>=|<=|>|<|&&|\|\|)/', $normalized) === 1;
}
/**
* 참/거짓 문자열을 bool 로 되돌립니다.
*
* `||` 처럼 피연산자 값을 그대로 돌려주는 연산도 있으므로, 참/거짓 문자열이
* 아니면 원본 문자열을 유지합니다.
*
* @param string $value 평가 결과 문자열
* @return mixed bool 또는 원본 문자열
*/
private function coerceBooleanString(string $value): mixed
{
return match ($value) {
'true' => true,
'false' => false,
default => $value,
};
}
/**
* 평가 결과 문자열의 truthy 여부를 판정합니다.
*
* 논리 연산자(`||`, `&&`)의 단락 평가 기준입니다.
*
* @param string $value 평가 결과 문자열
* @return bool truthy 이면 true
*/
private function isTruthyValue(string $value): bool
{
return $value !== '' && $value !== 'false' && $value !== '0';
}
/**
* 표현식이 단일 {{expr}} 바인딩 하나로만 구성되는지 판정합니다.
*
* `{{a}} - {{b}}` 처럼 바인딩이 둘 이상이면 false 를 반환해야 합니다.
* 정규식 `/^\{\{(.+?)\}\}$/` 는 양끝 앵커 때문에 이런 다중 바인딩도 매치되어
* 내부가 `a}} - {{b` 로 잘못 해석되므로, 중괄호 깊이를 직접 추적합니다.
* 객체 리터럴(`{{ {outer: {inner: 'v'}} }}`)처럼 내부에 `}}` 가 등장하는
* 경우까지 정확히 구분하기 위함입니다.
*
* @param string $trimmed 앞뒤 공백이 제거된 표현식
* @return bool 단일 바인딩이면 true
*/
private function isSingleBinding(string $trimmed): bool
{
$length = strlen($trimmed);
if ($length < 5 || ! str_starts_with($trimmed, '{{') || ! str_ends_with($trimmed, '}}')) {
return false;
}
// 여는 `{{` 를 깊이 2 로 두고 스캔 — 마지막 문자 이전에 깊이가 0 이 되면 바인딩이 둘 이상
$depth = 2;
for ($i = 2; $i < $length; $i++) {
$char = $trimmed[$i];
if ($char === '{') {
$depth++;
continue;
}
if ($char !== '}') {
continue;
}
$depth--;
if ($depth === 0) {
return $i === $length - 1;
}
}
return false;
}
/**
* ?? 연산자를 포함한 표현식을 원본 값으로 평가합니다.
*
@@ -156,6 +264,7 @@ class ExpressionEvaluator
// 표현식으로 재귀 해석
return $this->resolvePath($fallback, $context);
}
/**
* SEO 메타 표현식을 컨텍스트와 함께 평가하여 최종 문자열을 반환합니다.
*
@@ -196,7 +305,7 @@ class ExpressionEvaluator
// 인라인 $t:key 토큰 해석 ({{}} 외부 텍스트 내 $t:key|param=value 패턴)
if (str_contains($result, '$t:')) {
$result = preg_replace_callback('/\$t:([\w.\-]+(?:\|[\w.\-]+=[\w.\-{}]+)*)/', function ($matches) use ($context) {
$result = preg_replace_callback('/\$t:(?:defer:)?([\w.\-]+(?:\|[\w.\-]+=[\w.\-{}]+)*)/', function ($matches) use ($context) {
return $this->resolveTranslation('$t:'.$matches[1], $context);
}, $result);
}
@@ -213,7 +322,11 @@ class ExpressionEvaluator
/**
* $t: 번역 키를 해석합니다.
*
* @param string $expression 번역 표현식 ($t:key 또는 $t:key|param=value)
* `$t:defer:key` 형태(프론트엔드에서 렌더 시점까지 해석을 미루는 표기)도
* 동일한 키로 취급합니다 — SEO는 서버에서 한 번에 해석하므로 지연 개념이
* 없고, `defer:` 를 키에 포함시키면 사전 조회가 실패해 빈 문자열이 됩니다.
*
* @param string $expression 번역 표현식 ($t:key, $t:defer:key 또는 $t:key|param=value)
* @param array $context 데이터 컨텍스트 (파라미터 값의 {{}} 표현식 해석용)
* @return string 번역된 문자열
*/
@@ -221,6 +334,10 @@ class ExpressionEvaluator
{
$key = substr($expression, 3);
if (str_starts_with($key, 'defer:')) {
$key = substr($key, 6);
}
// 파라미터 분리: $t:key|param1=value1|param2=value2
$params = [];
if (str_contains($key, '|')) {
@@ -386,36 +503,31 @@ class ExpressionEvaluator
}
// 2. 논리 OR: a || b
// JS 시맨틱 — boolean이 아니라 "첫 truthy 피연산자"를 반환한다.
// ({{query?.q || ''}} 같은 표현식이 값 대신 'true'가 되는 것을 방지)
if (str_contains($expr, '||')) {
$parts = $this->splitOutsideBrackets($expr, '||');
if (count($parts) === 2) {
$leftVal = $this->evaluateExpression(trim($parts[0]), $context);
if ($leftVal !== '' && $leftVal !== 'false' && $leftVal !== '0') {
return 'true';
}
$rightVal = $this->evaluateExpression(trim($parts[1]), $context);
if ($rightVal !== '' && $rightVal !== 'false' && $rightVal !== '0') {
return 'true';
if ($this->isTruthyValue($leftVal)) {
return $leftVal;
}
return 'false';
return $this->evaluateExpression(trim($parts[1]), $context);
}
}
// 3. 논리 AND: a && b
// JS 시맨틱 — 좌변이 falsy면 좌변을, 아니면 우변을 반환한다.
if (str_contains($expr, '&&')) {
$parts = $this->splitOutsideBrackets($expr, '&&');
if (count($parts) === 2) {
$leftVal = $this->evaluateExpression(trim($parts[0]), $context);
if ($leftVal === '' || $leftVal === 'false' || $leftVal === '0') {
return 'false';
}
$rightVal = $this->evaluateExpression(trim($parts[1]), $context);
if ($rightVal === '' || $rightVal === 'false' || $rightVal === '0') {
return 'false';
if (! $this->isTruthyValue($leftVal)) {
return $leftVal;
}
return 'true';
return $this->evaluateExpression(trim($parts[1]), $context);
}
}
+300
View File
@@ -0,0 +1,300 @@
<?php
namespace App\Seo;
use Illuminate\Support\Facades\Log;
/**
* 봇 화면에 삽입되는 사용자 작성 HTML 을 정화합니다.
*
* 일반 화면(React)은 `HtmlContent` 컴포지트가 DOMPurify 로 정화한 결과를 그리므로,
* 봇 화면도 **같은 강도**로 정화해야 두 화면의 출력이 일치합니다. 정화하지 않으면
* 봇 화면에서만 `<script>` / `onerror` 등이 살아 있어, 주소에 봇 파라미터를 붙이는
* 것만으로 저장된 스크립트가 실행됩니다.
*
* 차단 목록은 아래 파일의 DOMPurify 설정을 옮긴 것입니다 — 한쪽만 고치면 두 화면의
* 정화 강도가 어긋나므로 **함께 갱신**해야 합니다.
*
* @see templates/_bundled/sirsoft-basic/src/components/composite/HtmlContent.tsx
* @see docs/backend/seo-system.md "봇 화면의 HTML 정화"
*/
class HtmlSanitizer
{
/**
* 정화 대상 HTML 을 감쌀 래퍼 요소 id.
*
* DOM 파서가 요구하는 문서 골격을 씌운 뒤 이 요소의 자식만 되돌려 받습니다.
*/
private const ROOT_ID = 'g7-seo-sanitize-root';
/**
* 요소와 내용을 통째로 제거할 태그 목록.
*
* 스크립트 실행 · 외부 콘텐츠 삽입 · 문서 구조 조작처럼 내부 텍스트를 남기는 것조차
* 위험하거나 무의미한 태그입니다. (DOMPurify 의 `FORBID_CONTENTS` 계열 동작)
*/
private const DROP_WITH_CONTENT = [
'script', 'noscript', 'style', 'template',
'iframe', 'frame', 'frameset',
'title', 'head',
'svg', 'math',
'plaintext', 'xmp', 'listing',
'noframes', 'noembed',
'audio', 'video',
];
/**
* 요소만 벗기고 내부 텍스트는 남길 태그 목록.
*
* 본문 텍스트를 품고 있을 수 있어 통째로 버리면 콘텐츠가 사라지는 태그입니다.
* (DOMPurify 의 `KEEP_CONTENT: true` 기본 동작)
*/
private const UNWRAP_KEEP_CONTENT = [
'object', 'embed', 'applet', 'portal',
'link', 'meta', 'base',
'form', 'input', 'textarea', 'select', 'option', 'button',
'body', 'html',
'source', 'track', 'canvas',
'details', 'dialog',
'marquee', 'slot',
];
/**
* 제거할 속성 목록 (`on*` 이벤트 핸들러는 전부 별도로 제거).
*/
private const FORBID_ATTRS = [
'formaction', 'xlink:href', 'action', 'srcdoc', 'ping',
];
/**
* URL 값을 담는 속성 목록 (스킴 검사 대상).
*/
private const URL_ATTRS = ['href', 'src', 'srcset', 'poster', 'background', 'cite', 'longdesc'];
/**
* URL 속성에 허용하는 스킴.
*/
private const ALLOWED_SCHEMES = ['http', 'https', 'mailto', 'tel', 'sms', 'ftp', 'cid', 'xmpp', 'callto'];
/**
* `data:` URL 중 허용하는 형태 (이미지 한정 — svg 는 스크립트 실행 벡터라 제외).
*/
private const ALLOWED_DATA_URL = '/^data:image\/(png|jpe?g|gif|webp|avif|bmp);/i';
/**
* 사용자 작성 HTML 을 정화해 반환합니다.
*
* 파싱에 실패하면 정화되지 않은 HTML 을 내보내지 않고 전체를 이스케이프합니다
* (실패 시 안전한 쪽으로 기웁니다).
*
* @param string $html 정화할 HTML
* @return string 정화된 HTML
*/
public function sanitize(string $html): string
{
if (trim($html) === '') {
return '';
}
if (! class_exists(\DOMDocument::class)) {
return e($html);
}
$document = new \DOMDocument('1.0', 'UTF-8');
$previous = libxml_use_internal_errors(true);
try {
$loaded = $document->loadHTML(
'<!DOCTYPE html><html><head><meta charset="utf-8"></head><body><div id="'
.self::ROOT_ID.'">'.$html.'</div></body></html>',
LIBXML_NOERROR | LIBXML_NOWARNING
);
if (! $loaded) {
return e($html);
}
$root = $document->getElementById(self::ROOT_ID);
if (! $root instanceof \DOMElement) {
return e($html);
}
$this->cleanNode($root);
return $this->innerHtml($document, $root);
} catch (\Throwable $e) {
Log::warning('봇 화면 HTML 정화 실패 — 전체 이스케이프로 대체', [
'error' => $e->getMessage(),
]);
return e($html);
} finally {
libxml_clear_errors();
libxml_use_internal_errors($previous);
}
}
/**
* 노드와 그 자손을 재귀적으로 정화합니다.
*
* @param \DOMNode $node 대상 노드
*/
private function cleanNode(\DOMNode $node): void
{
// 자식 목록을 먼저 복사한다 — 순회 중 DOM 을 변경하므로 라이브 NodeList 를 쓰면 항목을 건너뛴다.
$children = [];
foreach ($node->childNodes as $child) {
$children[] = $child;
}
foreach ($children as $child) {
if ($child instanceof \DOMElement) {
$this->cleanElement($child);
continue;
}
// 주석은 봇 화면에 남길 이유가 없고 조건부 주석 등 파서 혼란 요인이 된다.
if ($child instanceof \DOMComment) {
$child->parentNode?->removeChild($child);
}
}
}
/**
* 단일 요소를 정화합니다 (제거 / 언랩 / 속성 정리).
*
* @param \DOMElement $element 대상 요소
*/
private function cleanElement(\DOMElement $element): void
{
$tag = strtolower($element->tagName);
if (in_array($tag, self::DROP_WITH_CONTENT, true)) {
$element->parentNode?->removeChild($element);
return;
}
if (in_array($tag, self::UNWRAP_KEEP_CONTENT, true)) {
$this->cleanNode($element);
$this->unwrap($element);
return;
}
$this->cleanAttributes($element);
$this->cleanNode($element);
}
/**
* 요소를 제거하고 자식 노드를 부모의 같은 자리에 올립니다.
*
* @param \DOMElement $element 대상 요소
*/
private function unwrap(\DOMElement $element): void
{
$parent = $element->parentNode;
if ($parent === null) {
return;
}
while ($element->firstChild !== null) {
$parent->insertBefore($element->firstChild, $element);
}
$parent->removeChild($element);
}
/**
* 요소의 속성을 정리합니다.
*
* @param \DOMElement $element 대상 요소
*/
private function cleanAttributes(\DOMElement $element): void
{
$attributes = [];
foreach ($element->attributes as $attribute) {
$attributes[] = $attribute->nodeName;
}
foreach ($attributes as $name) {
$lower = strtolower($name);
// 이벤트 핸들러 전량 제거 (onerror, onload, onanimationend, ...)
if (str_starts_with($lower, 'on')) {
$element->removeAttribute($name);
continue;
}
if (in_array($lower, self::FORBID_ATTRS, true)) {
$element->removeAttribute($name);
continue;
}
if (in_array($lower, self::URL_ATTRS, true)
&& ! $this->isAllowedUrl($element->getAttribute($name))) {
$element->removeAttribute($name);
}
}
// 외부 링크에 rel 보강 (일반 화면의 HtmlContent 후처리와 동일)
if (strtolower($element->tagName) === 'a' && ! $element->hasAttribute('rel')) {
$href = $element->getAttribute('href');
if (str_starts_with($href, 'http://') || str_starts_with($href, 'https://')) {
$element->setAttribute('rel', 'noopener noreferrer');
}
}
}
/**
* URL 속성 값이 허용된 스킴인지 판정합니다.
*
* 상대 경로 · 앵커 · 프로토콜 상대 경로는 허용하고, `javascript:` 처럼 스크립트를
* 실행할 수 있는 스킴은 차단합니다.
*
* @param string $url 검사할 URL
* @return bool 허용 여부
*/
private function isAllowedUrl(string $url): bool
{
$trimmed = trim($url);
if ($trimmed === '') {
return true;
}
// 제어문자를 끼워 넣어 스킴 검사를 우회하는 시도를 막는다 (`java\tscript:` 등)
$normalized = strtolower(preg_replace('/[\x00-\x20]+/', '', $trimmed) ?? '');
if (preg_match(self::ALLOWED_DATA_URL, $normalized) === 1) {
return true;
}
// 스킴이 없으면 상대 경로 / 앵커 / 쿼리 → 허용
if (preg_match('/^([a-z][a-z0-9+.-]*):/', $normalized, $matches) !== 1) {
return true;
}
return in_array($matches[1], self::ALLOWED_SCHEMES, true);
}
/**
* 요소의 내부 HTML 을 문자열로 반환합니다.
*
* @param \DOMDocument $document 소속 문서
* @param \DOMElement $element 대상 요소
* @return string 내부 HTML
*/
private function innerHtml(\DOMDocument $document, \DOMElement $element): string
{
$html = '';
foreach ($element->childNodes as $child) {
$html .= $document->saveHTML($child);
}
return $html;
}
}
+86 -27
View File
@@ -95,6 +95,39 @@ class SeoRenderer implements SeoRendererInterface
$queryParams = $request->query();
// 레이아웃 초기 상태를 프론트엔드(TemplateApp)와 동일한 순서로 반영한다:
// 레이아웃 최상위 initLocal/state·initGlobal(없는 키만) → init_actions setState
// initActions (camelCase, LayoutService 병합 결과) 또는 init_actions (snake_case, 원본 JSON) 둘 다 지원
$initActions = $mergedLayout['initActions'] ?? $mergedLayout['init_actions'] ?? [];
// 데이터소스 엔드포인트/params 표현식이 참조할 수 있도록 _global 을 먼저 구성한다.
// (예: 검색 결과 엔드포인트의 {{_global.searchActiveTab ?? 'all'}})
$preContext = [
'route' => array_merge($routeParams, ['path' => $url]),
'query' => $queryParams,
'_global' => $this->buildGlobalContext(),
];
// 레이아웃 최상위 initGlobal → _global (기존 키는 보존)
foreach ($this->resolveInitStateBlock($mergedLayout['initGlobal'] ?? [], $preContext) as $key => $value) {
if (! array_key_exists($key, $preContext['_global'])) {
$preContext['_global'][$key] = $value;
}
}
// init_actions의 setState(target: global) → _global
$globalFromActions = $this->resolveInitActionState($initActions, 'global', $preContext);
// target: global 인 setState가 _local 하위 객체를 싣는 경우 _local로 병합
// (프론트엔드 setGlobalState가 globalState._local을 갱신하는 동작과 동일)
$localFromGlobalActions = [];
if (isset($globalFromActions['_local']) && is_array($globalFromActions['_local'])) {
$localFromGlobalActions = $globalFromActions['_local'];
unset($globalFromActions['_local']);
}
$preContext['_global'] = array_merge($preContext['_global'], $globalFromActions);
$context = [];
if (! empty($seoDataSourceIds)) {
$context = $this->dataSourceResolver->resolve(
@@ -102,25 +135,30 @@ class SeoRenderer implements SeoRendererInterface
$seoDataSourceIds,
$routeParams,
$locale,
$queryParams
$queryParams,
$preContext
);
}
// route 정보를 context에 추가 (path: 현재 URL 경로, + 동적 파라미터)
$context['route'] = array_merge($routeParams, ['path' => $url]);
// route/query/_global 을 데이터소스 결과와 합쳐 렌더 컨텍스트를 구성
$context['route'] = $preContext['route'];
$context['query'] = $preContext['query'];
$context['_global'] = $preContext['_global'];
// query 파라미터도 context에 추가
$context['query'] = $queryParams;
// 레이아웃 최상위 initLocal (없으면 state — 하위 호환) → _local
// _local 은 데이터소스 결과를 참조할 수 있어야 하므로 호출 이후에 평가한다.
$local = $this->resolveInitStateBlock(
$mergedLayout['initLocal'] ?? $mergedLayout['state'] ?? [],
$context
);
// SEO 컨텍스트에 _global/_local 추가
// 프론트엔드에서 window.G7Config로 주입되는 설정을 서버사이드에서도 동일하게 제공
$context['_global'] = $this->buildGlobalContext();
$local = array_merge(
$local,
$this->resolveInitActionState($initActions, 'local', $context),
$localFromGlobalActions
);
// init_actions의 setState(target: local)을 평가하여 _local 초기화
// 프론트엔드에서 init_actions로 설정하는 _local 상태를 SEO 렌더링에서도 동일하게 반영
// initActions (camelCase, LayoutService 병합 결과) 또는 init_actions (snake_case, 원본 JSON) 둘 다 지원
$initActions = $mergedLayout['initActions'] ?? $mergedLayout['init_actions'] ?? [];
$context['_local'] = $this->resolveInitLocalState($initActions, $context);
$context['_local'] = $local;
// 5.1. initGlobal 매핑: 데이터소스 결과를 _global 경로에 주입
// 프론트엔드에서 data_source의 initGlobal 설정으로 _global에 매핑하는 것과 동일
@@ -909,28 +947,52 @@ class SeoRenderer implements SeoRendererInterface
}
/**
* init_actions의 setState(target: local)을 평가하여 _local 초기값을 반환합니다.
* 레이아웃 최상위 초기 상태 블록(initLocal/state/initGlobal)의 값을 평가합니다.
*
* 프론트엔드에서 init_actions 실행 시 setState로 설정하는 _local 상태를
* 프론트엔드 TemplateApp이 레이아웃 레벨 initLocal/initGlobal을 상태에 적용하는 것과
* 동일하게, 각 값의 {{}} 표현식을 해석해 반환합니다.
*
* @param mixed $block 초기 상태 블록 (키 → 값)
* @param array $context 현재 컨텍스트 (route, query 등 포함)
* @return array 평가된 초기 상태
*/
private function resolveInitStateBlock(mixed $block, array $context): array
{
if (! is_array($block) || $block === []) {
return [];
}
$resolved = [];
foreach ($block as $key => $value) {
$resolved[$key] = $this->resolveInitActionValue($value, $context);
}
return $resolved;
}
/**
* init_actions의 setState를 대상(target)별로 평가하여 초기값을 반환합니다.
*
* 프론트엔드에서 init_actions 실행 시 setState로 설정하는 _local/_global 상태를
* SEO 렌더링에서도 동일하게 반영합니다. 이를 통해 탭 상태, 페이지네이션 초기값 등
* _local 기반 조건부 렌더링이 SEO에서도 정상 동작합니다.
* 상태 기반 조건부 렌더링이 SEO에서도 정상 동작합니다.
*
* 처리 대상:
* - handler: "setState" + params.target: "local" (또는 target 미지정)
* - handler: "setState" + params.target 이 $target 과 일치 (target 미지정은 local)
* - params 내 {{}} 표현식을 ExpressionEvaluator로 평가
* - 배열 리터럴, 객체 리터럴 등 정적 값은 그대로 사용
*
* 스킵 대상:
* - handler가 setState가 아닌 항목 (loadFromLocalStorage, closeModal 등)
* - target이 "global"인 항목
*
* @param array $initActions 레이아웃의 init_actions 배열
* @param string $target 대상 상태 (`local` 또는 `global`)
* @param array $context 현재 컨텍스트 (route, query 등 포함)
* @return array _local 초기값
* @return array 평가된 초기값
*/
private function resolveInitLocalState(array $initActions, array $context): array
private function resolveInitActionState(array $initActions, string $target, array $context): array
{
$local = [];
$state = [];
// setState에서 제외할 메타 키 (상태 값이 아닌 핸들러 제어용 키)
$metaKeys = ['target', 'handler', 'comment'];
@@ -942,10 +1004,7 @@ class SeoRenderer implements SeoRendererInterface
}
$params = $action['params'] ?? [];
$target = $params['target'] ?? 'local';
// global 대상은 스킵 (_global은 buildGlobalContext + applyInitGlobalMapping이 담당)
if ($target === 'global') {
if (($params['target'] ?? 'local') !== $target) {
continue;
}
@@ -954,11 +1013,11 @@ class SeoRenderer implements SeoRendererInterface
continue;
}
$local[$key] = $this->resolveInitActionValue($value, $context);
$state[$key] = $this->resolveInitActionValue($value, $context);
}
}
return $local;
return $state;
}
/**