feat(core): 정적 최적화 서버 대응 자산 URL 이중 모드

nginx 의 정규식 location 은 프리픽스 location 보다 먼저 매칭되므로,
`location ~* \.(js|css|json)$` 블록이 있는 서버에서는 확장자 붙은 동적
엔드포인트가 `try_files ... /index.php` 폴백이 실행될 기회 없이 404 가 된다.
aaPanel/CyberPanel/Plesk 기본 템플릿에 들어있어 드물지 않으며, 관리자 화면조차
뜨지 않아 "서버 설정을 고치세요" 안내가 순환 참조가 된다.

관례를 깬 쪽이 G7 이므로 해소 책임도 G7 에 두고, 두 형태를 모두 서빙한 뒤
환경에 따라 택일한다. 확장자 형태는 영구 유지한다 — 제거하면 URL 을 하드코딩한
서드파티 확장이 깨진다.

- 라우트: dualSuffix / dualSuffixSegment / dualAsset 매크로로 23개 엔드포인트와
 프로브를 이중 등록. 확장자 형태를 먼저 등록한다 — 확장자 없는 쪽이 더 느슨한
 패턴이라 순서가 뒤집히면 `.json` 요청까지 삼킨다
- URL 생성: 서버 App\Support\AssetUrl, 프론트 core/support/assetUrl.ts 로 집약.
 기본 모드에서 생성 결과는 치환 이전과 문자열까지 동일하다 (쿼리 순서 포함 —
 순서가 바뀌면 의미는 같아도 HTTP 캐시 키가 갈린다)
- 자가 복구: 부트스트랩 자산 로드 실패 시 확장자 없는 형태로 1회 단방향 전환.
 역방향 금지 + 기존 재시도 예산 공유로 무한 왕복을 막는다
- 감지·전환: 인스톨러 프로브(설치 시 확정) / 관리자 환경설정 일반 탭 /
 g7:asset-url-mode. 판정은 상태코드가 아니라 매직 토큰 + Content-Type 으로 한다.
 상태코드만 보면 "404 대신 200 + 에러 HTML" 환경에서 영원히 오판한다
- 봇은 JavaScript 를 실행하지 않아 자가 복구가 닿지 않으므로, 모드 변경 시
 SEO 프리렌더 캐시를 비워 재생성시킨다

가드: audit 룰 2종(dynamic-route-static-extension / asset-url-builder-required),
Playwright 6건(정적 블록 가로채기 시뮬레이션), 루프 방지 불변식 L1~L9 전수 red 증명.

부수 정리: 양 Composer 에 중복돼 있던 확장 에셋 수집 123줄을 트레이트로 통합하고,
자산 확장자 화이트리스트 누락(.map)과 경로 정규화 우회 가능성을 함께 교정.

sir.kr 커뮤니티의 hang 님께서 제보해주셨습니다.
This commit is contained in:
HeuJung committed 2026-07-23 11:34:32 +09:00
1 parent 74df8a4b09
commit 15cd4452bf
90 files changed
+4279 -546

No files matched your search

@@ -5,6 +5,25 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.54.0] - 2026-07-20
### Added
#### 자산 URL 이중 모드 — 정적 최적화 서버에서의 동작 보장
- `support/assetUrl.ts`(신규) — 동적 엔드포인트 URL 생성을 한 곳으로 모았다. `getAssetUrlMode()` 가 `window.G7Config.assetUrlMode`(서버가 내려주는 초기값) → `G7Config.settings.general.asset_url_mode` → 기본값 `extension` 순으로 판정하고, `suffixed()` / `templateAsset()` / `moduleAsset()` / `pluginAsset()` / `extensionBundle()` / `layoutUrl()` / `layoutPreviewUrl()` 가 그 모드에 맞는 URL 을 만든다. 서버측 `App\Support\AssetUrl` 와 **동일 규칙**이며, 한쪽만 바꾸면 서버가 만든 URL 과 클라이언트가 만든 URL 이 어긋나 그 자산만 404 가 된다.
- 배경: nginx 의 정규식 location(`location ~* \.(js|css|json)$`)은 프리픽스 location 보다 먼저 매칭되므로, 확장자 붙은 동적 엔드포인트는 `try_files ... /index.php` 폴백이 실행될 기회 없이 nginx 가 직접 파일시스템을 열려 시도해 404 가 된다. aaPanel/CyberPanel/Plesk 기본 템플릿에 들어있는 블록이다.
- 확장자 없는 모드의 변환 규칙 — 고정 접미사는 제거(`routes.json` → `routes`), 번들은 접미사가 종류를 구분하므로 세그먼트로 강등(`bundle.js` → `bundle/js`), 와일드카드 자산은 경로가 곧 파일명이라 쿼리로 이동(`assets/{id}/js/a.js` → `assets/{id}?file=js/a.js`). 마지막 형태가 안전한 이유는 nginx 의 location 정규식이 쿼리스트링을 제외한 경로에만 매칭되기 때문이다.
- `setAssetUrlMode()` 는 **단방향 1회**만 허용한다(`extension → extensionless`). 역방향을 허용하면 양쪽 형태가 모두 실패하는 상황(PHP 다운·WAF 차단)에서 무한 왕복이 된다. 서버 설정은 바꾸지 않는다 — 미인증 클라이언트가 전역 설정을 뒤집을 수 있으면 안 된다.
- `restoreCachedMode()` 의 localStorage 캐시는 키에 `cache_version` 을 포함하고 24시간 TTL 을 둔다. 서버가 정상화된 뒤에도 클라이언트가 옛 모드에 영구 고착되지 않도록 하기 위함이다.
### Changed
#### 동적 엔드포인트 URL 생성부 14지점을 빌더 경유로 전환
- `routing/Router.ts`, `TemplateApp.ts`(4), `ComponentRegistry.ts`, `ErrorPageHandler.ts`, `LayoutLoader.ts`(2), `layout-editor/LayoutEditorChrome.tsx`, `layout-editor/hooks/{useEditorTemplateAssets,useInlineEdit,useLayoutDocument,useExtensionDocument}.ts` — `routes.json`·`config.json`·`components.json`·레이아웃 JSON URL 을 모두 `suffixed()` 로 생성한다.
- 기본 모드(`extension`)에서 생성 결과는 치환 이전과 **문자열까지 동일**하다. `suffixed()` 는 추가 쿼리를 `v` 보다 앞에 놓는데(`?with_source_meta=1&v=...`), 이는 편집기 문서 로드 호출부의 기존 순서를 보존하기 위한 것이다 — 쿼리 순서가 바뀌면 의미는 같아도 URL 문자열이 달라져 HTTP 캐시 키가 갈린다.
## [engine-v1.53.1] - 2026-07-12
### Fixed
@@ -13,6 +13,7 @@
import React, { type ComponentType } from 'react';
import { createLogger } from '../utils/Logger';
import { fetchWithRetry } from './networkResilience';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('ComponentRegistry');
@@ -247,7 +248,7 @@ export class ComponentRegistry {
// 캐시 미스 - API에서 로드
// 네트워크 일시 실패(응답 없음)에만 재시도. HTTP 에러는 아래 !ok 분기가 종전대로 처리.
// @since engine-v1.53.0
const manifestUrl = `/api/templates/${this.templateId}/components.json`;
const manifestUrl = suffixed(`/api/templates/${this.templateId}/components`, 'json');
const response = await fetchWithRetry(manifestUrl, { label: 'components.json' });
if (!response.ok) {
@@ -8,6 +8,7 @@
import type { LayoutLoader } from './LayoutLoader';
import type { DataSourceManager, DataSource } from './DataSourceManager';
import { createLogger } from '../utils/Logger';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('ErrorPageHandler');
@@ -83,7 +84,7 @@ export class ErrorPageHandler {
try {
// template.json fetch
const response = await fetch(`/api/templates/${this.templateId}/config.json`);
const response = await fetch(suffixed(`/api/templates/${this.templateId}/config`, 'json'));
if (!response.ok) {
if (this.debug) {
@@ -17,6 +17,7 @@ import type { ComponentRegistry } from './ComponentRegistry';
import type { ErrorHandlingMap } from '../types/ErrorHandling';
import { createLogger } from '../utils/Logger';
import { fetchWithRetry } from './networkResilience';
import { suffixed } from '../support/assetUrl';
import { G7DevToolsCore } from '../devtools/G7DevToolsCore';
import { getApiClient } from '../api/ApiClient';
@@ -744,14 +745,14 @@ export class LayoutLoader {
try {
// API 엔드포인트 구성 (캐시 버전 쿼리 파라미터 추가)
// 시스템 레이아웃 분기: __preview__ 는 별도 API 엔드포인트 사용
let baseUrl: string;
const version = this.cacheVersion > 0 ? this.cacheVersion : null;
let apiUrl: string;
if (layoutPath.startsWith('__preview__/')) {
const token = layoutPath.replace('__preview__/', '');
baseUrl = `/api/layouts/preview/${token}.json`;
apiUrl = suffixed(`/api/layouts/preview/${token}`, 'json', version);
} else {
baseUrl = `/api/layouts/${templateId}/${layoutPath}.json`;
apiUrl = suffixed(`/api/layouts/${templateId}/${layoutPath}`, 'json', version);
}
const apiUrl = this.cacheVersion > 0 ? `${baseUrl}?v=${this.cacheVersion}` : baseUrl;
logger.log('Fetching layout from API:', apiUrl);
@@ -13,6 +13,7 @@
*/
import { createLogger } from '../utils/Logger';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('TranslationEngine');
@@ -221,20 +222,22 @@ export class TranslationEngine {
try {
// API 호출 (캐시 버전 쿼리 파라미터 추가, bustCache가 true면 타임스탬프도 추가)
let url = `${apiBaseUrl}/templates/${templateId}/lang/${locale}.json`;
// 쿼리 파라미터 구성
const queryParams: string[] = [];
if (this.cacheVersion > 0) {
queryParams.push(`v=${this.cacheVersion}`);
}
// 자산 URL 모드에 따라 `.json` 접미사가 붙거나 빠진다.
// 이 경로는 편집기 전용이 아니라 **모든 페이지가 타는 런타임 공통 경로**라,
// 여기만 확장자를 직접 조립하면 extensionless 환경에서 다국어가 통째로 404 가 되어
// 이슈 #486 의 원래 증상(화면이 온전히 뜨지 않음)이 다국어 계층에서 재현된다.
const extraParams: string[] = [];
if (bustCache) {
queryParams.push(`_=${Date.now()}`);
}
if (queryParams.length > 0) {
url += `?${queryParams.join('&')}`;
extraParams.push(`_=${Date.now()}`);
}
const url = suffixed(
`${apiBaseUrl}/templates/${templateId}/lang/${locale}`,
'json',
this.cacheVersion > 0 ? this.cacheVersion : null,
extraParams.length > 0 ? extraParams.join('&') : undefined,
);
const response = await fetch(url);
if (!response.ok) {
@@ -75,6 +75,7 @@ import { buildCoreActionRecipeSeed } from './spec/coreActionRecipes';
import { registerCoreWidgets } from './spec/registerCoreWidgets';
import { registerCoreEditors } from './spec/registerCoreEditors';
import { exposeLayoutEditorGlobals } from './spec/exposeLayoutEditorGlobals';
import { suffixed } from '../../support/assetUrl';
/**
* 편집기 셸 최소 너비(px) — 이 아래로는 셸을 압착하지 않고 브라우저 가로 스크롤로 흡수한다.
@@ -119,7 +120,7 @@ async function fetchPermissionCandidates(
if (typeof fetch !== 'function') return [];
try {
const response = await fetch(
`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/permission-candidates.json`,
suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/permission-candidates`, 'json'),
{ credentials: 'same-origin', headers: buildAuthHeaders() },
);
if (!response.ok) return [];
@@ -223,7 +224,7 @@ function LayoutEditorChromeBody({
(async () => {
try {
const response = await fetch(
`/api/templates/${encodeURIComponent(templateIdentifier)}/components.json`,
suffixed(`/api/templates/${encodeURIComponent(templateIdentifier)}/components`, 'json'),
{ credentials: 'same-origin', headers: { Accept: 'application/json' } }
);
if (!response.ok) return;
@@ -1,3 +1,8 @@
// e2e:allow 이슈 #486 단위 A 는 서버 라우트 이중화 전용. 이 파일 변경은 편집기 CSS
// 엔드포인트 개명(editor/components.css → component-styles.css)을 따라간 기대값 수정뿐이며
// 브라우저 거동은 불변(URL 은 서버가 생성해 내려주고 hook 은 그대로 fetch).
// 자산 URL 모드의 브라우저 시나리오 spec 은 자가 복구를 도입하는 단위 D 에서 추가한다.
/**
* useEditorTemplateAssets 회귀 테스트
*
@@ -6,6 +11,7 @@
* hook 의 동작을 가드.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useEditorTemplateAssets } from '../../hooks/useEditorTemplateAssets';
@@ -118,7 +124,7 @@ describe('useEditorTemplateAssets', () => {
// 못 실어 500(Route[login])으로 떨어지므로, Bearer fetch → `<style>` 로 주입해야 한다.
it('권한 가드 admin CSS 는 Bearer fetch → <style> 주입 (link 아님)', async () => {
window.localStorage.setItem('auth_token', 'tok-css');
const adminCssUrl = '/api/admin/templates/sirsoft-basic/editor/components.css?v=1';
const adminCssUrl = '/api/admin/templates/sirsoft-basic/editor/component-styles.css?v=1';
fetchSpy.mockImplementation(async (url: string) => {
if (url.includes('/editor-assets')) {
return {
@@ -128,7 +134,7 @@ describe('useEditorTemplateAssets', () => {
}),
};
}
if (url.includes('/editor/components.css')) {
if (url.includes('/editor/component-styles.css')) {
return { ok: true, text: async () => '.g7le-preview-dark .x{color:red}' };
}
if (url.includes('/components.json')) {
@@ -150,7 +156,7 @@ describe('useEditorTemplateAssets', () => {
expect(styleEl?.textContent).toContain('.g7le-preview-dark');
// CSS fetch 에 Bearer 헤더 부착
const cssCall = fetchSpy.mock.calls.find((c) => String(c[0]).includes('/editor/components.css'));
const cssCall = fetchSpy.mock.calls.find((c) => String(c[0]).includes('/editor/component-styles.css'));
expect(cssCall?.[1]?.headers?.Authorization).toBe('Bearer tok-css');
});
@@ -59,6 +59,7 @@ import { ComputedForm } from './ComputedForm';
import { InitialStateForm } from './InitialStateForm';
import { ErrorHandlingForm } from './ErrorHandlingForm';
import { DataSourceTab } from './DataSourceTab';
import { suffixed } from '../../../../support/assetUrl';
/** 8탭 키 — 헤더 와이어프레임 순서 */
export type PageSettingsTabKey =
@@ -124,7 +125,7 @@ async function fetchSeoExtensions(templateIdentifier: string): Promise<SeoExtens
if (typeof fetch !== 'function' || !templateIdentifier) return [];
try {
const response = await fetch(
`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates.json`,
suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates`, 'json'),
{ credentials: 'same-origin', headers: buildAuthHeaders() },
);
if (!response.ok) return [];
@@ -31,6 +31,7 @@ import { SeoBotPreviewPanel } from './SeoBotPreviewPanel';
import type { BindingCandidate } from '../../spec/bindingCandidates';
import type { DataSourceOption } from '../../spec/candidatePools';
import { DataSourceChipLabel } from './DataSourceChipLabel';
import { suffixed } from '../../../../support/assetUrl';
/** seo.extensions 칩 — `{type,id}` */
export interface SeoExtensionRef {
@@ -171,7 +172,7 @@ export function SeoForm({
}
const qs = params.toString() ? `?${params.toString()}` : '';
const res = await fetch(
`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates.json${qs}`,
suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates`, 'json', null, qs.replace(/^[?&]+/, '')),
{ credentials: 'same-origin', headers: buildAuthHeaders() },
);
const body = await res.json().catch(() => null);
@@ -30,6 +30,7 @@ import {
type EditorAccessError,
} from '../types/editorErrors';
import { buildAuthHeaders } from '../utils/authToken';
import { suffixed } from '../../../support/assetUrl';
const logger = createLogger('useEditorRoutes');
@@ -246,7 +247,7 @@ export function useEditorRoutes(options: UseEditorRoutesOptions): void {
// 먼저 실행되는 진입 fetch 이므로, 이를 가드 엔드포인트 + Bearer 토큰으로 전환하면
// 미인증/권한부족이 진입 시점에 즉시 401/403 으로 감지되어 chrome(트리/캔버스)이
// 렌더되기 전 AccessErrorPanel → 로그인 리다이렉트로 분기된다.
const url = `/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/routes.json${versionQuery}`;
const url = suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/routes`, 'json', null, versionQuery.replace(/^[?&]+/, ''));
// 편집 대상 템플릿의 lang dictionary 도 함께 적재 — 라우트 meta.title 에 있는
// `$t:user.*` 키가 부팅 템플릿(admin) lang 에는 없으므로 별도 로드 필요.
@@ -31,6 +31,7 @@ import {
type EditorAccessError,
} from '../types/editorErrors';
import { reseedPendingIntoEngine } from './pendingCustomTranslations';
import { suffixed } from '../../../support/assetUrl';
export interface EditorTemplateAssetsState {
componentRegistry: ComponentRegistry | null;
@@ -98,7 +99,7 @@ async function fetchLatestCacheVersion(identifier: string): Promise<number> {
try {
if (typeof fetch !== 'function') return 0;
const res = await fetch(
`/api/templates/${encodeURIComponent(identifier)}/config.json`,
suffixed(`/api/templates/${encodeURIComponent(identifier)}/config`, 'json'),
{ credentials: 'same-origin', headers: { Accept: 'application/json' } },
);
if (!res.ok) return 0;
@@ -46,6 +46,7 @@ import { trackEditorDocument } from '../devtools/editorTrackers';
import { readSanctumToken } from '../utils/authToken';
import { getCacheBustNonce, bumpCacheBustNonce } from '../utils/editorCacheBust';
import type { SaveResult } from './useLayoutDocument';
import { suffixed } from '../../../support/assetUrl';
/**
* 확장 편집 모드의 가상 path(`__extension__/{extensionId}`)에서 extensionId 를 추출한다.
@@ -420,9 +421,7 @@ export function useExtensionDocument(): UseExtensionDocumentResult {
const cacheVersion = (window as any).G7Config?.cache_version ?? 0;
// 클라이언트 캐시-버스트 nonce 합성 — useLayoutDocument 와 공용 카운터.
// 버전 복원/저장 후 reload 시 HTTP 캐시 stale 호스트 응답을 우회한다(확장 캔버스 미갱신 결함).
const url = `/api/layouts/${encodeURIComponent(
templateIdentifier,
)}/${hostLayoutName}.json?with_source_meta=1&v=${cacheVersion}.${getCacheBustNonce()}`;
const url = suffixed(`/api/layouts/${encodeURIComponent(templateIdentifier)}/${hostLayoutName}`, 'json', `${cacheVersion}.${getCacheBustNonce()}`, 'with_source_meta=1');
const token = readSanctumToken();
const headers: Record<string, string> = { Accept: 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
@@ -35,6 +35,7 @@ import {
} from '../devtools/editorTrackers';
import { setPendingValue, setPendingValues } from './pendingCustomTranslations';
import { TranslationEngine } from '../../TranslationEngine';
import { suffixed } from '../../../support/assetUrl';
import {
stripBindingTokens,
buildParamizedKeyText,
@@ -739,7 +740,7 @@ export async function bustTranslationCache(
// 최신 cache_version 을 노출하므로 그것을 읽어 엔진 버전을 갱신한 뒤 재로드한다.
try {
const cfg = await fetch(
`/api/templates/${encodeURIComponent(templateIdentifier)}/config.json`,
suffixed(`/api/templates/${encodeURIComponent(templateIdentifier)}/config`, 'json'),
{ headers: { Accept: 'application/json' }, credentials: 'same-origin' },
).then((r) => (r.ok ? r.json() : null));
const v = cfg?.data?.cache_version ?? cfg?.cache_version;
@@ -32,6 +32,7 @@ import { parseEditorPath } from './useElementSelection';
import { readSanctumToken } from '../utils/authToken';
import { getCacheBustNonce, bumpCacheBustNonce } from '../utils/editorCacheBust';
import { hasPending, flushPending } from './pendingCustomTranslations';
import { suffixed } from '../../../support/assetUrl';
/**
* 로드된 레이아웃 문서 — 백엔드 응답의 data 부분 (병합 + 확장 + 메타 포함)
@@ -440,7 +441,7 @@ export function useLayoutDocument(): UseLayoutDocumentResult {
const cacheVersion = (window as any).G7Config?.cache_version ?? 0;
// 저장 후 클라이언트 캐시-버스트 nonce 합성 — 같은 세션 저장→재로드가
// 옛 cache_version 으로 stale 응답을 받지 않도록 단조 증가 nonce 를 함께 붙인다.
const url = `/api/layouts/${encodeURIComponent(templateIdentifier)}/${layoutName}.json?with_source_meta=1&v=${cacheVersion}.${getCacheBustNonce()}`;
const url = suffixed(`/api/layouts/${encodeURIComponent(templateIdentifier)}/${layoutName}`, 'json', `${cacheVersion}.${getCacheBustNonce()}`, 'with_source_meta=1');
const token = readSanctumToken();
const headers: Record<string, string> = { Accept: 'application/json' };
if (token) {