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

@@ -0,0 +1,125 @@
<?php
namespace App\Console\Commands;
use App\Seo\Contracts\SeoCacheManagerInterface;
use App\Services\SettingsService;
use App\Support\AssetUrl;
use Illuminate\Console\Command;
/**
* 자산 URL 모드 조회/전환 Artisan 커맨드 (이슈 #486 §9)
*
* 정적 최적화 블록(`location ~* \.(js|css|json)$`)이 동적 응답을 가로채는 서버에서는
* **관리자 화면 자체가 뜨지 않는다**. "브라우저로 설정을 바꾸세요" 는 순환 참조이므로
* CLI 탈출구가 반드시 필요하다.
*
* ```
* php artisan g7:asset-url-mode # 현재 모드 + 진단 안내
* php artisan g7:asset-url-mode extensionless # 전환
* ```
*/
class AssetUrlModeCommand extends Command
{
/**
* @var string 커맨드 시그니처
*/
protected $signature = 'g7:asset-url-mode
{mode? : 전환할 모드 (extension | extensionless). 생략 시 현재 모드만 출력}';
/**
* @var string 커맨드 설명
*/
protected $description = '자산 URL 모드를 조회하거나 전환합니다 (정적 최적화 서버 대응)';
/**
* 커맨드를 실행합니다.
*
* @param SettingsService $settingsService 환경설정 서비스
* @param SeoCacheManagerInterface $seoCacheManager SEO 캐시 매니저
* @return int 종료 코드
*/
public function handle(SettingsService $settingsService, SeoCacheManagerInterface $seoCacheManager): int
{
$current = AssetUrl::mode();
$requested = $this->argument('mode');
if ($requested === null) {
$this->showStatus($current);
return Command::SUCCESS;
}
if (! in_array($requested, [AssetUrl::MODE_EXTENSION, AssetUrl::MODE_EXTENSIONLESS], true)) {
$this->error(__('asset_url_mode.invalid', ['mode' => $requested]));
return Command::FAILURE;
}
if ($requested === $current) {
$this->info(__('asset_url_mode.already', ['mode' => $current]));
return Command::SUCCESS;
}
$saved = $settingsService->saveSettings([
'_tab' => 'general',
'general' => ['asset_url_mode' => $requested],
]);
if (! $saved) {
$this->error(__('asset_url_mode.save_failed'));
return Command::FAILURE;
}
// SEO 프리렌더 캐시에는 생성 시점의 자산 URL 이 그대로 구워져 있다.
// 모드를 바꾸면 그 URL 들이 전부 어긋나므로 함께 비운다 (계획서 §알려진 한계).
$seoCacheManager->clearAll();
$this->info(__('asset_url_mode.switched', ['from' => $current, 'to' => $requested]));
$this->line(__('asset_url_mode.seo_cache_cleared'));
return Command::SUCCESS;
}
/**
* 현재 모드와 진단 안내를 출력합니다.
*
* @param string $current 현재 모드
*/
private function showStatus(string $current): void
{
$this->line('');
$this->line(' '.__('asset_url_mode.current', ['mode' => $current]));
$this->line('');
// audit:allow asset-url-builder-required reason: 두 모드의 URL 형태를 나란히
// 보여주는 대조표라 빌더로 생성할 수 없다 (빌더는 현재 모드 하나만 만든다).
$rows = $current === AssetUrl::MODE_EXTENSION
? [
['/api/templates/{id}/routes.json', '/api/templates/{id}/routes'],
['/api/modules/bundle.js', '/api/modules/bundle/js'],
['/api/templates/assets/{id}/js/a.js', '/api/templates/assets/{id}?file=js/a.js'],
]
: [
['/api/templates/{id}/routes', '/api/templates/{id}/routes.json'],
['/api/modules/bundle/js', '/api/modules/bundle.js'],
['/api/templates/assets/{id}?file=js/a.js', '/api/templates/assets/{id}/js/a.js'],
];
$this->table(
[__('asset_url_mode.table.in_use'), __('asset_url_mode.table.alternative')],
$rows,
);
$this->line(' '.__('asset_url_mode.diagnose_title'));
$this->line(' curl -i '.rtrim(config('app.url'), '/').'/api/system/asset-probe.js');
$this->line(' curl -i '.rtrim(config('app.url'), '/').'/api/system/asset-probe');
$this->line('');
$this->line(' '.__('asset_url_mode.diagnose_hint'));
$this->line('');
$this->line(' '.__('asset_url_mode.switch_hint'));
$this->line('');
}
}
+7 -6
View File
@@ -41,6 +41,7 @@ use App\Models\Plugin;
use App\Models\Template;
use App\Providers\CoreServiceProvider;
use App\Services\LayoutExtensionService;
use App\Support\AssetUrl;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
@@ -1066,8 +1067,8 @@ class ModuleManager implements ModuleManagerInterface
if (isset($builtPaths['js']) || isset($builtPaths['css'])) {
$assets = [
'js' => isset($builtPaths['js']) ? "/api/modules/assets/{$identifier}/".$builtPaths['js'] : null,
'css' => isset($builtPaths['css']) ? "/api/modules/assets/{$identifier}/".$builtPaths['css'] : null,
'js' => isset($builtPaths['js']) ? AssetUrl::moduleAsset($identifier, $builtPaths['js']) : null,
'css' => isset($builtPaths['css']) ? AssetUrl::moduleAsset($identifier, $builtPaths['css']) : null,
'priority' => $loadingConfig['priority'] ?? 100,
];
}
@@ -1156,8 +1157,8 @@ class ModuleManager implements ModuleManagerInterface
if (isset($builtPaths['js']) || isset($builtPaths['css'])) {
$assets = [
'js' => isset($builtPaths['js']) ? "/api/modules/assets/{$identifier}/".$builtPaths['js'] : null,
'css' => isset($builtPaths['css']) ? "/api/modules/assets/{$identifier}/".$builtPaths['css'] : null,
'js' => isset($builtPaths['js']) ? AssetUrl::moduleAsset($identifier, $builtPaths['js']) : null,
'css' => isset($builtPaths['css']) ? AssetUrl::moduleAsset($identifier, $builtPaths['css']) : null,
'priority' => $loadingConfig['priority'] ?? 100,
];
}
@@ -1304,8 +1305,8 @@ class ModuleManager implements ModuleManagerInterface
if (isset($builtPaths['js']) || isset($builtPaths['css'])) {
$assets = [
'js' => isset($builtPaths['js']) ? "/api/modules/assets/{$identifier}/".$builtPaths['js'] : null,
'css' => isset($builtPaths['css']) ? "/api/modules/assets/{$identifier}/".$builtPaths['css'] : null,
'js' => isset($builtPaths['js']) ? AssetUrl::moduleAsset($identifier, $builtPaths['js']) : null,
'css' => isset($builtPaths['css']) ? AssetUrl::moduleAsset($identifier, $builtPaths['css']) : null,
'priority' => $loadingConfig['priority'] ?? 100,
];
}
+7 -6
View File
@@ -41,6 +41,7 @@ use App\Models\Template;
use App\Providers\CoreServiceProvider;
use App\Services\DriverRegistryService;
use App\Services\LayoutExtensionService;
use App\Support\AssetUrl;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
@@ -1094,8 +1095,8 @@ class PluginManager implements PluginManagerInterface
if (isset($builtPaths['js']) || isset($builtPaths['css'])) {
$assets = [
'js' => isset($builtPaths['js']) ? "/api/plugins/assets/{$identifier}/".$builtPaths['js'] : null,
'css' => isset($builtPaths['css']) ? "/api/plugins/assets/{$identifier}/".$builtPaths['css'] : null,
'js' => isset($builtPaths['js']) ? AssetUrl::pluginAsset($identifier, $builtPaths['js']) : null,
'css' => isset($builtPaths['css']) ? AssetUrl::pluginAsset($identifier, $builtPaths['css']) : null,
'priority' => $loadingConfig['priority'] ?? 100,
];
}
@@ -1190,8 +1191,8 @@ class PluginManager implements PluginManagerInterface
if (isset($builtPaths['js']) || isset($builtPaths['css'])) {
$assets = [
'js' => isset($builtPaths['js']) ? "/api/plugins/assets/{$identifier}/".$builtPaths['js'] : null,
'css' => isset($builtPaths['css']) ? "/api/plugins/assets/{$identifier}/".$builtPaths['css'] : null,
'js' => isset($builtPaths['js']) ? AssetUrl::pluginAsset($identifier, $builtPaths['js']) : null,
'css' => isset($builtPaths['css']) ? AssetUrl::pluginAsset($identifier, $builtPaths['css']) : null,
'priority' => $loadingConfig['priority'] ?? 100,
];
}
@@ -1268,8 +1269,8 @@ class PluginManager implements PluginManagerInterface
if (isset($builtPaths['js']) || isset($builtPaths['css'])) {
$assets = [
'js' => isset($builtPaths['js']) ? "/api/plugins/assets/{$identifier}/".$builtPaths['js'] : null,
'css' => isset($builtPaths['css']) ? "/api/plugins/assets/{$identifier}/".$builtPaths['css'] : null,
'js' => isset($builtPaths['js']) ? AssetUrl::pluginAsset($identifier, $builtPaths['js']) : null,
'css' => isset($builtPaths['css']) ? AssetUrl::pluginAsset($identifier, $builtPaths['css']) : null,
'priority' => $loadingConfig['priority'] ?? 100,
];
}
@@ -8,6 +8,7 @@ use App\Extension\Helpers\EditorSpecAssembler;
use App\Http\Controllers\Api\Base\AdminBaseController;
use App\Services\PermissionService;
use App\Services\TemplateService;
use App\Support\AssetUrl;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
@@ -88,17 +89,19 @@ class AdminTemplateAssetController extends AdminBaseController
}
$extensionCacheVersion = (int) app(CacheInterface::class)->get('ext.cache_version', 0);
$version = $extensionCacheVersion > 0 ? "?v={$extensionCacheVersion}" : '';
$version = $extensionCacheVersion > 0 ? $extensionCacheVersion : null;
return $this->success(
__('templates.messages.editor_assets_retrieved'),
[
'identifier' => $identifier,
'js' => ["/api/templates/assets/{$identifier}/js/components.iife.js{$version}"],
'js' => [AssetUrl::templateAsset($identifier, 'js/components.iife.js', $version)],
// CSS 는 편집기 전용 엔드포인트로 — 다크 셀렉터를 프리뷰 마커로 치환해 서빙
// 일반 자산 서빙은 원본.
// URI 가 `components` 가 아니라 `component-styles` 인 이유: 확장자를 떼면
// `editor/components.json` 의 확장자 없는 형태와 충돌한다.
'css' => $cssAvailable
? ["/api/admin/templates/{$identifier}/editor/components.css{$version}"]
? [AssetUrl::suffixed("/api/admin/templates/{$identifier}/editor/component-styles", 'css', $version)]
: [],
'manifest_present' => true,
'manifest_source' => $jsSource,
@@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers\Api\Public;
use App\Http\Controllers\Api\Base\PublicBaseController;
use Illuminate\Http\Response;
/**
* 자산 URL 모드 감지 프로브.
*
* 서버(nginx/Apache)의 정적 최적화 블록이 확장자 붙은 동적 응답을 가로채는지
* 판정하기 위한 대조 엔드포인트다. 브라우저가 아래 두 URL 을 쌍으로 요청한다.
*
* ```text
* GET /api/system/asset-probe.js → 확장자 형태 (정적 블록의 표적)
* GET /api/system/asset-probe → 대조군
* ```
*
* | probe.js | probe | 판정 |
* |---|---|---|
* | 성공 | 성공 | `extension` — 확장자 유지 가능 |
* | 실패 | 성공 | `extensionless` — 정적 블록 가로채기 확정 |
* | 실패 | 실패 | 모드 문제 아님 (PHP/라우팅 장애) — 별도 안내 |
*
* ## 판정은 상태코드가 아니라 본문이다
*
* 클라이언트는 `res.ok && body.includes(PROBE_TOKEN)` 로 판정해야 한다.
* 상태코드만 보면 "404 대신 200 + 에러 HTML" 이나 catch-all 200 페이지를
* 반환하는 설정에서 영원히 `extension` 으로 오판해, 재감지를 몇 번 눌러도
* 같은 오답이 나온다.
*
* ## 감지는 반드시 브라우저에서 수행한다
*
* 서버측에서 자기 `APP_URL` 로 curl 하면 loopback 이 nginx vhost·SSL·프록시
* 체인을 우회하거나 다른 vhost 를 타서 오판한다.
*
* ## 실물 파일을 두지 않는다
*
* `public/` 하위에 실제 `asset-probe.js` 파일이 존재하면 nginx 가 그것을
* 성공적으로 서빙해 거짓 양성이 된다. 본 라우트는 반드시 실물 파일이 없는
* 경로여야 한다.
*/
class AssetProbeController extends PublicBaseController
{
/**
* 프로브 성공 판정용 매직 토큰.
*
* 클라이언트·테스트가 응답 본문에서 이 문자열을 찾아 성공을 판정한다.
*/
public const PROBE_TOKEN = 'G7_ASSET_PROBE_OK';
/**
* 프로브 응답을 반환합니다.
*
* DB 에 접근하지 않으며(설치 전에도 응답 가능) 캐시되지 않습니다.
* ResponseHelper 의 JSON 봉투를 쓰지 않는 이유: 이 엔드포인트의 목적은
* "정적 자산으로 오인될 응답"을 실제로 흉내내는 것이므로, 자바스크립트
* Content-Type 과 본문 형태를 그대로 유지해야 대표성이 있다.
*
* @return Response 매직 토큰을 담은 자바스크립트 응답
*/
public function probe(): Response
{
$body = "/* G7 asset URL mode probe */\n"
."window.__g7AssetProbe = '".self::PROBE_TOKEN."';\n";
return response($body, 200, [
'Content-Type' => 'application/javascript; charset=utf-8',
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
'Pragma' => 'no-cache',
'X-Content-Type-Options' => 'nosniff',
]);
}
}
@@ -71,14 +71,16 @@ class PublicModuleController extends PublicBaseController
*
* @param ServeModuleAssetRequest $request 검증된 요청 (경로, 확장자 검증 완료)
* @param string $identifier 모듈 식별자 (vendor-module 형식)
* @param string $path 에셋 경로 (dist/js/module.iife.js 등)
* @return BinaryFileResponse|JsonResponse|Response 파일 응답 또는 에러 응답
*/
public function serveAsset(
ServeModuleAssetRequest $request,
string $identifier,
string $path
string $identifier
): BinaryFileResponse|JsonResponse|Response {
// 파일 경로는 FormRequest 에서 받는다 — 확장자 모드는 `{path}` 라우트 세그먼트,
// 확장자 없는 모드는 `?file=` 쿼리로 오며 prepareForValidation() 이 이를 흡수한다.
$path = (string) $request->validated('path');
// FormRequest에서 이미 보안 검증 완료
// API 사용량 기록
$this->logApiUsage('modules.assets', ['identifier' => $identifier, 'path' => $path]);
@@ -70,14 +70,16 @@ class PublicPluginController extends PublicBaseController
*
* @param ServePluginAssetRequest $request 검증된 요청 (경로, 확장자 검증 완료)
* @param string $identifier 플러그인 식별자 (vendor-plugin 형식)
* @param string $path 에셋 경로 (dist/js/plugin.iife.js 등)
* @return BinaryFileResponse|JsonResponse|Response 파일 응답 또는 에러 응답
*/
public function serveAsset(
ServePluginAssetRequest $request,
string $identifier,
string $path
string $identifier
): BinaryFileResponse|JsonResponse|Response {
// 파일 경로는 FormRequest 에서 받는다 — 확장자 모드는 `{path}` 라우트 세그먼트,
// 확장자 없는 모드는 `?file=` 쿼리로 오며 prepareForValidation() 이 이를 흡수한다.
$path = (string) $request->validated('path');
// FormRequest에서 이미 보안 검증 완료
// API 사용량 기록
$this->logApiUsage('plugins.assets', ['identifier' => $identifier, 'path' => $path]);
@@ -88,13 +88,16 @@ class PublicTemplateController extends PublicBaseController
/**
* 템플릿 정적 파일 서빙
*
* @param ServeTemplateAssetRequest $request 요청 (FormRequest 검증)
* @param ServeTemplateAssetRequest $request 요청 (FormRequest 검증, 파일 경로 `path` 포함)
* @param string $identifier 템플릿 식별자
* @param string $path 요청 경로
* @return BinaryFileResponse|JsonResponse|Response 파일 응답 또는 에러
*/
public function serveAsset(ServeTemplateAssetRequest $request, string $identifier, string $path): BinaryFileResponse|JsonResponse|Response
public function serveAsset(ServeTemplateAssetRequest $request, string $identifier): BinaryFileResponse|JsonResponse|Response
{
// 파일 경로는 FormRequest 에서 받는다 — 확장자 모드는 `{path}` 라우트 세그먼트,
// 확장자 없는 모드는 `?file=` 쿼리로 오며 prepareForValidation() 이 이를 흡수한다.
$path = (string) $request->validated('path');
// FormRequest에서 이미 보안 검증 완료
// API 사용량 기록
$this->logApiUsage('templates.assets', ['identifier' => $identifier, 'path' => $path]);
@@ -4,6 +4,7 @@ namespace App\Http\Requests\Public\Module;
use App\Rules\AllowedModuleFileType;
use App\Rules\SafeModulePath;
use App\Support\Routing\DualExtensionRoute;
use Illuminate\Foundation\Http\FormRequest;
class ServeModuleAssetRequest extends FormRequest
@@ -12,6 +13,8 @@ class ServeModuleAssetRequest extends FormRequest
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
*
* @return bool 항상 true (권한은 미들웨어 책임)
*/
public function authorize(): bool
{
@@ -21,8 +24,11 @@ class ServeModuleAssetRequest extends FormRequest
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, mixed>
* @return array<string, mixed> 검증 규칙 배열
*/
// audit:allow core-formrequest-hook-filter reason: 자산 서빙 경로 검증은 파일시스템
// 화이트리스트(SafeModulePath + AllowedModuleFileType)가 유일한 방어선이다.
// 확장이 필터로 규칙을 대체할 수 있으면 경로 탈출·임의 파일 읽기가 열린다.
public function rules(): array
{
// 모듈 식별자로부터 기준 경로 구성 (모듈 루트)
@@ -35,7 +41,7 @@ class ServeModuleAssetRequest extends FormRequest
'required',
'string',
new SafeModulePath($basePath),
new AllowedModuleFileType(),
new AllowedModuleFileType,
],
];
}
@@ -45,10 +51,11 @@ class ServeModuleAssetRequest extends FormRequest
*/
protected function prepareForValidation(): void
{
// 라우트 파라미터를 검증 데이터에 병합
// 라우트 파라미터를 검증 데이터에 병합.
// 확장자 없는 모드에서는 파일 경로가 `?file=` 쿼리로 온다 (경로 확장자 회피).
$this->merge([
'identifier' => $this->route('identifier'),
'path' => $this->route('path'),
'path' => $this->route('path') ?? $this->query(DualExtensionRoute::FILE_QUERY_PARAM),
]);
}
@@ -4,6 +4,7 @@ namespace App\Http\Requests\Public\Plugin;
use App\Rules\AllowedPluginFileType;
use App\Rules\SafePluginPath;
use App\Support\Routing\DualExtensionRoute;
use Illuminate\Foundation\Http\FormRequest;
class ServePluginAssetRequest extends FormRequest
@@ -12,6 +13,8 @@ class ServePluginAssetRequest extends FormRequest
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
*
* @return bool 항상 true (권한은 미들웨어 책임)
*/
public function authorize(): bool
{
@@ -21,8 +24,11 @@ class ServePluginAssetRequest extends FormRequest
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, mixed>
* @return array<string, mixed> 검증 규칙 배열
*/
// audit:allow core-formrequest-hook-filter reason: 자산 서빙 경로 검증은 파일시스템
// 화이트리스트(SafePluginPath + AllowedPluginFileType)가 유일한 방어선이다.
// 확장이 필터로 규칙을 대체할 수 있으면 경로 탈출·임의 파일 읽기가 열린다.
public function rules(): array
{
// 플러그인 식별자로부터 기준 경로 구성 (플러그인 루트)
@@ -35,7 +41,7 @@ class ServePluginAssetRequest extends FormRequest
'required',
'string',
new SafePluginPath($basePath),
new AllowedPluginFileType(),
new AllowedPluginFileType,
],
];
}
@@ -48,7 +54,7 @@ class ServePluginAssetRequest extends FormRequest
// 라우트 파라미터를 검증 데이터에 병합
$this->merge([
'identifier' => $this->route('identifier'),
'path' => $this->route('path'),
'path' => $this->route('path') ?? $this->query(DualExtensionRoute::FILE_QUERY_PARAM),
]);
}
@@ -4,6 +4,7 @@ namespace App\Http\Requests\Public\Template;
use App\Rules\AllowedTemplateFileType;
use App\Rules\SafeTemplatePath;
use App\Support\Routing\DualExtensionRoute;
use Illuminate\Foundation\Http\FormRequest;
class ServeTemplateAssetRequest extends FormRequest
@@ -12,6 +13,8 @@ class ServeTemplateAssetRequest extends FormRequest
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
*
* @return bool 항상 true (권한은 미들웨어 책임)
*/
public function authorize(): bool
{
@@ -20,7 +23,13 @@ class ServeTemplateAssetRequest extends FormRequest
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, mixed> 검증 규칙 배열
*/
// audit:allow core-formrequest-hook-filter reason: 자산 서빙 경로 검증은 파일시스템
// 화이트리스트(SafeTemplatePath + AllowedTemplateFileType)가 유일한 방어선이다.
// 확장이 필터로 규칙을 대체할 수 있으면 경로 탈출·임의 파일 읽기가 열린다.
// 확장 가능한 "동적 필드" 가 없는 요청이라 룰의 취지(필드 확장)도 해당하지 않는다.
public function rules(): array
{
// 템플릿 식별자로부터 기준 경로 구성
@@ -33,7 +42,7 @@ class ServeTemplateAssetRequest extends FormRequest
'required',
'string',
new SafeTemplatePath($basePath),
new AllowedTemplateFileType(),
new AllowedTemplateFileType,
],
];
}
@@ -43,10 +52,13 @@ class ServeTemplateAssetRequest extends FormRequest
*/
protected function prepareForValidation(): void
{
// 라우트 파라미터를 검증 데이터에 병합
// 라우트 파라미터를 검증 데이터에 병합.
// 확장자 없는 모드에서는 파일 경로가 경로 세그먼트가 아니라 `?file=` 쿼리로 온다
// (nginx 정적 최적화 블록이 URL 경로의 확장자만 보고 가로채는 것을 회피).
// 어느 형태로 오든 컨트롤러는 동일하게 `path` 만 본다.
$this->merge([
'identifier' => $this->route('identifier'),
'path' => $this->route('path'),
'path' => $this->route('path') ?? $this->query(DualExtensionRoute::FILE_QUERY_PARAM),
]);
}
@@ -64,4 +76,4 @@ class ServeTemplateAssetRequest extends FormRequest
'path.string' => __('validation.asset.path.string'),
];
}
}
}
@@ -5,6 +5,7 @@ namespace App\Http\Requests\Settings;
use App\Extension\HookManager;
use App\Models\Attachment;
use App\Search\Engines\DatabaseFulltextEngine;
use App\Support\AssetUrl;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
@@ -174,6 +175,13 @@ class SaveSettingsRequest extends FormRequest
'general.language' => $this->getTabRules($tab, 'general', [Rule::in(config('app.supported_locales', ['ko', 'en']))]),
'general.currency' => ['nullable', 'string', 'max:10'],
'general.maintenance_mode' => ['nullable', 'boolean'],
// 자산 URL 방식 — 정적 최적화 서버 대응 (이슈 #486).
// 임의 문자열이 들어오면 AssetUrl::mode() 가 기본값으로 폴백하지만,
// 저장 단계에서 막아 설정 파일에 뜻 모를 값이 남지 않게 한다.
'general.asset_url_mode' => ['nullable', 'string', Rule::in([
AssetUrl::MODE_EXTENSION,
AssetUrl::MODE_EXTENSIONLESS,
])],
'general.site_logo' => ['nullable', 'array'],
'general.site_logo.*' => ['integer', Rule::exists(Attachment::class, 'id')],
+2 -153
View File
@@ -8,17 +8,18 @@ use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Http\View\Composers\Traits\CollectsActiveExtensionMeta;
use App\Http\View\Composers\Traits\CollectsExtensionAssets;
use App\Http\View\Composers\Traits\CollectsTemplateExternals;
use App\Services\ModuleSettingsService;
use App\Services\PluginSettingsService;
use App\Services\SettingsService;
use App\Services\TemplateService;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
class TemplateComposer
{
use CollectsActiveExtensionMeta;
use CollectsExtensionAssets;
use CollectsTemplateExternals;
/**
@@ -115,156 +116,4 @@ class TemplateComposer
$view->with('appConfig', $appConfig);
$view->with('templateExternals', $templateExternals);
}
/**
* 확장 프론트엔드 병합 번들 URL을 계산합니다.
*
* 활성 global 에셋(JS/CSS)이 하나라도 있는 타입만 해당 번들 URL을 채우고,
* 없으면 null을 두어 프론트가 로드를 스킵하게 한다. URL은 same-origin
* (`/api/...`)이어야 gdpr preblocker 의 same-origin 통과 규칙에 자기 차단되지
* 않는다(CDN 호스팅 금지).
*
* @param array $moduleAssets 수집된 모듈 개별 에셋 맵
* @param array $pluginAssets 수집된 플러그인 개별 에셋 맵
* @param int $version 확장 캐시 버전
* @return array{moduleJs: ?string, moduleCss: ?string, pluginJs: ?string, pluginCss: ?string}
*/
private function buildExtensionBundleUrls(array $moduleAssets, array $pluginAssets, int $version): array
{
$hasJs = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['js'])));
$hasCss = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['css'])));
return [
'moduleJs' => $hasJs($moduleAssets) ? "/api/modules/bundle.js?v={$version}" : null,
'moduleCss' => $hasCss($moduleAssets) ? "/api/modules/bundle.css?v={$version}" : null,
'pluginJs' => $hasJs($pluginAssets) ? "/api/plugins/bundle.js?v={$version}" : null,
'pluginCss' => $hasCss($pluginAssets) ? "/api/plugins/bundle.css?v={$version}" : null,
];
}
/**
* 활성화된 모듈의 프론트엔드 에셋 정보를 수집합니다.
*
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}>
*/
private function collectModuleAssets(): array
{
$assets = [];
try {
// ModuleManager에서 활성화된 모듈 목록 조회
$activeModules = $this->moduleManager->getActiveModules();
// 캐시 버전 조회 (브라우저 캐시 무효화용)
$cacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
foreach ($activeModules as $identifier => $module) {
// 모듈에 에셋이 있는지 확인
if (! $module->hasAssets()) {
continue;
}
$builtPaths = $module->getBuiltAssetPaths();
$loadingConfig = $module->getAssetLoadingConfig();
$assetConfig = $module->getAssets();
// global 전략인 경우에만 수집 (layout, lazy는 레이아웃에서 처리)
if ($loadingConfig['strategy'] !== 'global') {
continue;
}
$moduleAsset = [
'priority' => $loadingConfig['priority'],
];
// JS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['js'])) {
$moduleAsset['js'] = "/api/modules/assets/{$identifier}/".$builtPaths['js']."?v={$cacheVersion}";
}
// CSS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['css'])) {
$moduleAsset['css'] = "/api/modules/assets/{$identifier}/".$builtPaths['css']."?v={$cacheVersion}";
}
// 외부 스크립트 (조건부 로드용)
if (! empty($assetConfig['external'])) {
$moduleAsset['external'] = $assetConfig['external'];
}
$assets[$identifier] = $moduleAsset;
}
// 우선순위 기준 정렬 (낮을수록 먼저)
uasort($assets, fn ($a, $b) => $a['priority'] <=> $b['priority']);
} catch (\Exception $e) {
// 에러 발생 시 빈 배열 반환 (에셋 로드 실패해도 앱 진행)
Log::warning('Failed to collect module assets: '.$e->getMessage());
}
return $assets;
}
/**
* 활성화된 플러그인의 프론트엔드 에셋 정보를 수집합니다.
*
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}>
*/
private function collectPluginAssets(): array
{
$assets = [];
try {
// PluginManager에서 활성화된 플러그인 목록 조회
$activePlugins = $this->pluginManager->getActivePlugins();
// 캐시 버전 조회 (브라우저 캐시 무효화용)
$cacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
foreach ($activePlugins as $identifier => $plugin) {
// 플러그인에 에셋이 있는지 확인
if (! $plugin->hasAssets()) {
continue;
}
$builtPaths = $plugin->getBuiltAssetPaths();
$loadingConfig = $plugin->getAssetLoadingConfig();
$assetConfig = $plugin->getAssets();
// global 전략인 경우에만 수집 (layout, lazy는 레이아웃에서 처리)
if ($loadingConfig['strategy'] !== 'global') {
continue;
}
$pluginAsset = [
'priority' => $loadingConfig['priority'],
];
// JS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['js'])) {
$pluginAsset['js'] = "/api/plugins/assets/{$identifier}/".$builtPaths['js']."?v={$cacheVersion}";
}
// CSS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['css'])) {
$pluginAsset['css'] = "/api/plugins/assets/{$identifier}/".$builtPaths['css']."?v={$cacheVersion}";
}
// 외부 스크립트 (조건부 로드용)
if (! empty($assetConfig['external'])) {
$pluginAsset['external'] = $assetConfig['external'];
}
$assets[$identifier] = $pluginAsset;
}
// 우선순위 기준 정렬 (낮을수록 먼저)
uasort($assets, fn ($a, $b) => $a['priority'] <=> $b['priority']);
} catch (\Exception $e) {
// 에러 발생 시 빈 배열 반환 (에셋 로드 실패해도 앱 진행)
Log::warning('Failed to collect plugin assets: '.$e->getMessage());
}
return $assets;
}
}
@@ -0,0 +1,143 @@
<?php
namespace App\Http\View\Composers\Traits;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Support\AssetUrl;
use Illuminate\Support\Facades\Log;
/**
* 활성 확장(모듈·플러그인)의 프론트엔드 에셋 수집 및 번들 URL 생성.
*
* `TemplateComposer`(admin)와 `UserTemplateComposer`(user)가 공유한다. 두 클래스는
* 이 세 메서드를 주석까지 통째로 중복 보유하고 있었고(123줄), 그래서 한쪽만 고치면
* 다른 쪽이 조용히 어긋나는 구조였다. 트레이트로 승격해 그 가능성을 제거한다.
*
* URL 생성은 전부 `AssetUrl` 을 경유한다 — 자산 URL 이중 모드(확장자 유지/제거)를
* 한 곳에서 결정하기 위함이다.
*
* 사용하는 클래스는 `$moduleManager` / `$pluginManager` 프로퍼티를 가져야 한다.
*
* @see AssetUrl
*/
trait CollectsExtensionAssets
{
/**
* 확장 병합 번들 URL 을 생성합니다.
*
* 병합 번들은 same-origin(`/api/...`)이어야 한다. 외부 origin/CDN 은 GDPR
* 프리블로커에 자기 차단되므로 호스팅하지 않는다.
*
* @param array<string, mixed> $moduleAssets 수집된 모듈 개별 에셋 맵
* @param array<string, mixed> $pluginAssets 수집된 플러그인 개별 에셋 맵
* @param int $version 확장 캐시 버전
* @return array{moduleJs: ?string, moduleCss: ?string, pluginJs: ?string, pluginCss: ?string} 번들 URL 맵
*/
private function buildExtensionBundleUrls(array $moduleAssets, array $pluginAssets, int $version): array
{
$hasJs = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['js'])));
$hasCss = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['css'])));
return [
'moduleJs' => $hasJs($moduleAssets) ? AssetUrl::extensionBundle('modules', 'js', $version) : null,
'moduleCss' => $hasCss($moduleAssets) ? AssetUrl::extensionBundle('modules', 'css', $version) : null,
'pluginJs' => $hasJs($pluginAssets) ? AssetUrl::extensionBundle('plugins', 'js', $version) : null,
'pluginCss' => $hasCss($pluginAssets) ? AssetUrl::extensionBundle('plugins', 'css', $version) : null,
];
}
/**
* 활성화된 모듈의 프론트엔드 에셋 정보를 수집합니다.
*
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}> 식별자별 에셋 맵
*/
private function collectModuleAssets(): array
{
return $this->collectExtensionAssets(
'modules',
fn () => $this->moduleManager->getActiveModules(),
'Failed to collect module assets: '
);
}
/**
* 활성화된 플러그인의 프론트엔드 에셋 정보를 수집합니다.
*
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}> 식별자별 에셋 맵
*/
private function collectPluginAssets(): array
{
return $this->collectExtensionAssets(
'plugins',
fn () => $this->pluginManager->getActivePlugins(),
'Failed to collect plugin assets: '
);
}
/**
* 확장 에셋 수집 공통 구현.
*
* 모듈/플러그인은 수집 대상 조회 방법과 로그 문구만 다르고 나머지 로직이 동일하다.
*
* @param string $type `modules` 또는 `plugins`
* @param callable $activeResolver 활성 확장 목록을 반환하는 콜백
* @param string $logPrefix 실패 시 경고 로그 접두사
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}> 식별자별 에셋 맵
*/
private function collectExtensionAssets(string $type, callable $activeResolver, string $logPrefix): array
{
$assets = [];
try {
$active = $activeResolver();
// 캐시 버전 조회 (브라우저 캐시 무효화용)
$cacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
foreach ($active as $identifier => $extension) {
// 확장에 에셋이 있는지 확인
if (! $extension->hasAssets()) {
continue;
}
$builtPaths = $extension->getBuiltAssetPaths();
$loadingConfig = $extension->getAssetLoadingConfig();
$assetConfig = $extension->getAssets();
// global 전략인 경우에만 수집 (layout, lazy는 레이아웃에서 처리)
if ($loadingConfig['strategy'] !== 'global') {
continue;
}
$asset = [
'priority' => $loadingConfig['priority'],
];
// JS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['js'])) {
$asset['js'] = AssetUrl::extensionAsset($type, $identifier, $builtPaths['js'], $cacheVersion);
}
// CSS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['css'])) {
$asset['css'] = AssetUrl::extensionAsset($type, $identifier, $builtPaths['css'], $cacheVersion);
}
// 외부 스크립트 (조건부 로드용)
if (! empty($assetConfig['external'])) {
$asset['external'] = $assetConfig['external'];
}
$assets[$identifier] = $asset;
}
// 우선순위 기준 정렬 (낮을수록 먼저)
uasort($assets, fn ($a, $b) => $a['priority'] <=> $b['priority']);
} catch (\Exception $e) {
// 에러 발생 시 빈 배열 반환 (에셋 로드 실패해도 앱 진행)
Log::warning($logPrefix.$e->getMessage());
}
return $assets;
}
}
@@ -8,12 +8,12 @@ use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Http\View\Composers\Traits\CollectsActiveExtensionMeta;
use App\Http\View\Composers\Traits\CollectsExtensionAssets;
use App\Http\View\Composers\Traits\CollectsTemplateExternals;
use App\Services\ModuleSettingsService;
use App\Services\PluginSettingsService;
use App\Services\SettingsService;
use App\Services\TemplateService;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
@@ -24,6 +24,7 @@ use Illuminate\View\View;
class UserTemplateComposer
{
use CollectsActiveExtensionMeta;
use CollectsExtensionAssets;
use CollectsTemplateExternals;
/**
@@ -121,156 +122,4 @@ class UserTemplateComposer
$view->with('appConfig', $appConfig);
$view->with('templateExternals', $templateExternals);
}
/**
* 확장 프론트엔드 병합 번들 URL을 계산합니다.
*
* 활성 global 에셋(JS/CSS)이 하나라도 있는 타입만 해당 번들 URL을 채우고,
* 없으면 null을 두어 프론트가 로드를 스킵하게 한다. URL은 same-origin
* (`/api/...`)이어야 gdpr preblocker 의 same-origin 통과 규칙에 자기 차단되지
* 않는다(CDN 호스팅 금지).
*
* @param array $moduleAssets 수집된 모듈 개별 에셋 맵
* @param array $pluginAssets 수집된 플러그인 개별 에셋 맵
* @param int $version 확장 캐시 버전
* @return array{moduleJs: ?string, moduleCss: ?string, pluginJs: ?string, pluginCss: ?string}
*/
private function buildExtensionBundleUrls(array $moduleAssets, array $pluginAssets, int $version): array
{
$hasJs = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['js'])));
$hasCss = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['css'])));
return [
'moduleJs' => $hasJs($moduleAssets) ? "/api/modules/bundle.js?v={$version}" : null,
'moduleCss' => $hasCss($moduleAssets) ? "/api/modules/bundle.css?v={$version}" : null,
'pluginJs' => $hasJs($pluginAssets) ? "/api/plugins/bundle.js?v={$version}" : null,
'pluginCss' => $hasCss($pluginAssets) ? "/api/plugins/bundle.css?v={$version}" : null,
];
}
/**
* 활성화된 모듈의 프론트엔드 에셋 정보를 수집합니다.
*
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}>
*/
private function collectModuleAssets(): array
{
$assets = [];
try {
// ModuleManager에서 활성화된 모듈 목록 조회
$activeModules = $this->moduleManager->getActiveModules();
// 캐시 버전 조회 (브라우저 캐시 무효화용)
$cacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
foreach ($activeModules as $identifier => $module) {
// 모듈에 에셋이 있는지 확인
if (! $module->hasAssets()) {
continue;
}
$builtPaths = $module->getBuiltAssetPaths();
$loadingConfig = $module->getAssetLoadingConfig();
$assetConfig = $module->getAssets();
// global 전략인 경우에만 수집 (layout, lazy는 레이아웃에서 처리)
if ($loadingConfig['strategy'] !== 'global') {
continue;
}
$moduleAsset = [
'priority' => $loadingConfig['priority'],
];
// JS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['js'])) {
$moduleAsset['js'] = "/api/modules/assets/{$identifier}/".$builtPaths['js']."?v={$cacheVersion}";
}
// CSS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['css'])) {
$moduleAsset['css'] = "/api/modules/assets/{$identifier}/".$builtPaths['css']."?v={$cacheVersion}";
}
// 외부 스크립트 (조건부 로드용)
if (! empty($assetConfig['external'])) {
$moduleAsset['external'] = $assetConfig['external'];
}
$assets[$identifier] = $moduleAsset;
}
// 우선순위 기준 정렬 (낮을수록 먼저)
uasort($assets, fn ($a, $b) => $a['priority'] <=> $b['priority']);
} catch (\Exception $e) {
// 에러 발생 시 빈 배열 반환 (에셋 로드 실패해도 앱 진행)
Log::warning('Failed to collect module assets: '.$e->getMessage());
}
return $assets;
}
/**
* 활성화된 플러그인의 프론트엔드 에셋 정보를 수집합니다.
*
* @return array<string, array{js?: string, css?: string, priority: int, external?: array}>
*/
private function collectPluginAssets(): array
{
$assets = [];
try {
// PluginManager에서 활성화된 플러그인 목록 조회
$activePlugins = $this->pluginManager->getActivePlugins();
// 캐시 버전 조회 (브라우저 캐시 무효화용)
$cacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
foreach ($activePlugins as $identifier => $plugin) {
// 플러그인에 에셋이 있는지 확인
if (! $plugin->hasAssets()) {
continue;
}
$builtPaths = $plugin->getBuiltAssetPaths();
$loadingConfig = $plugin->getAssetLoadingConfig();
$assetConfig = $plugin->getAssets();
// global 전략인 경우에만 수집 (layout, lazy는 레이아웃에서 처리)
if ($loadingConfig['strategy'] !== 'global') {
continue;
}
$pluginAsset = [
'priority' => $loadingConfig['priority'],
];
// JS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['js'])) {
$pluginAsset['js'] = "/api/plugins/assets/{$identifier}/".$builtPaths['js']."?v={$cacheVersion}";
}
// CSS 빌드 경로 (캐시 버전 파라미터 추가)
if (! empty($builtPaths['css'])) {
$pluginAsset['css'] = "/api/plugins/assets/{$identifier}/".$builtPaths['css']."?v={$cacheVersion}";
}
// 외부 스크립트 (조건부 로드용)
if (! empty($assetConfig['external'])) {
$pluginAsset['external'] = $assetConfig['external'];
}
$assets[$identifier] = $pluginAsset;
}
// 우선순위 기준 정렬 (낮을수록 먼저)
uasort($assets, fn ($a, $b) => $a['priority'] <=> $b['priority']);
} catch (\Exception $e) {
// 에러 발생 시 빈 배열 반환 (에셋 로드 실패해도 앱 진행)
Log::warning('Failed to collect plugin assets: '.$e->getMessage());
}
return $assets;
}
}
+32 -13
View File
@@ -2,19 +2,31 @@
namespace App\Providers;
use App\Contracts\Extension\HookManagerInterface;
use App\Contracts\Extension\ModuleManagerInterface;
use App\Contracts\Extension\PluginManagerInterface;
use App\Contracts\Notifications\ChannelReadinessCheckerInterface;
use App\Extension\HookManager;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Http\View\Composers\TemplateComposer;
use App\Http\View\Composers\UserTemplateComposer;
use App\Listeners\ExtensionCompatibilityAlertListener;
use App\Notifications\NotificationChannelManager;
use App\Services\ChannelReadinessService;
use App\Services\GeoIpService;
use App\Support\Routing\DualExtensionRoute;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;
use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Laravel\Boost\BoostServiceProvider;
class AppServiceProvider extends ServiceProvider
{
@@ -23,48 +35,55 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
// 자산 URL 이중 모드 Route 매크로 (dualSuffix / dualAsset).
// boot() 가 아니라 register() 에서 등록하는 이유: 라우트 파일은 프레임워크의
// 라우팅 부트스트랩(boot 단계)에서 로드되므로, 프로바이더 간 boot 순서에
// 의존하면 매크로 미정의 시점에 라우트가 로드될 수 있다. 모든 프로바이더의
// register() 는 어떤 boot() 보다 먼저 실행되므로 여기가 유일하게 안전한 지점이다.
DualExtensionRoute::register();
// NOTE: Faker 부재 시 FakerShim 대체는 app/Support/SampleData/bootstrap.php 에서 처리
// (composer autoload.files 진입점 — vendor/autoload.php 로드 직후 실행되어
// Laravel 의 fake() 헬퍼 정의 시점에 \Faker\Factory 가 이미 alias 되어 있음)
// 알림 발송 공통 디스패처 — 채널 독립 발송 + 발송 전후 G7 훅 실행
$this->app->singleton(
\Illuminate\Notifications\ChannelManager::class,
fn ($app) => new \App\Notifications\NotificationChannelManager($app)
ChannelManager::class,
fn ($app) => new NotificationChannelManager($app)
);
// 채널 Readiness 검증 — 미설정 채널 발송 사전 차단
$this->app->singleton(
\App\Contracts\Notifications\ChannelReadinessCheckerInterface::class,
\App\Services\ChannelReadinessService::class
ChannelReadinessCheckerInterface::class,
ChannelReadinessService::class
);
// TODO: TemplateManagerInterface 바인딩을 추가해야 함
// PluginManagerInterface 바인딩
$this->app->bind(
\App\Contracts\Extension\PluginManagerInterface::class,
\App\Extension\PluginManager::class
PluginManagerInterface::class,
PluginManager::class
);
// ModuleManagerInterface 바인딩
$this->app->bind(
\App\Contracts\Extension\ModuleManagerInterface::class,
\App\Extension\ModuleManager::class
ModuleManagerInterface::class,
ModuleManager::class
);
// HookManagerInterface 바인딩
$this->app->bind(
\App\Contracts\Extension\HookManagerInterface::class,
\App\Extension\HookManager::class
HookManagerInterface::class,
HookManager::class
);
// GeoIpService 싱글톤 등록
$this->app->singleton(\App\Services\GeoIpService::class);
$this->app->singleton(GeoIpService::class);
// Laravel Boost (개발 전용 - dont-discover 대상, 클래스 존재 시에만 등록)
if (class_exists(\Laravel\Boost\BoostServiceProvider::class)) {
$this->app->register(\Laravel\Boost\BoostServiceProvider::class);
if (class_exists(BoostServiceProvider::class)) {
$this->app->register(BoostServiceProvider::class);
}
}
+4
View File
@@ -20,6 +20,10 @@ class AllowedModuleFileType implements ValidationRule
// Data
'json',
// Source maps — dev 빌드의 `//# sourceMappingURL` 이 개별 에셋 서빙 URL 을
// 가리키므로 허용 필요. prod 는 ExtensionBundleService 가 참조 자체를 strip 한다.
'map',
// Images
'png', 'jpg', 'jpeg', 'svg', 'webp', 'gif', 'ico',
+4
View File
@@ -20,6 +20,10 @@ class AllowedPluginFileType implements ValidationRule
// Data
'json',
// Source maps — dev 빌드의 `//# sourceMappingURL` 이 개별 에셋 서빙 URL 을
// 가리키므로 허용 필요. prod 는 ExtensionBundleService 가 참조 자체를 strip 한다.
'map',
// Images
'png', 'jpg', 'jpeg', 'svg', 'webp', 'gif', 'ico',
+8 -4
View File
@@ -20,6 +20,10 @@ class AllowedTemplateFileType implements ValidationRule
// Data
'json',
// Source maps — dev 빌드 산출물의 소스맵 참조 대응.
// prod 빌드는 소스맵 참조를 포함하지 않는다.
'map',
// Images
'png', 'jpg', 'jpeg', 'svg', 'webp', 'gif',
@@ -32,26 +36,26 @@ class AllowedTemplateFileType implements ValidationRule
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!is_string($value)) {
if (! is_string($value)) {
$fail(__('validation.template_path.must_be_string'));
return;
}
$extension = strtolower(pathinfo($value, PATHINFO_EXTENSION));
if (!in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
if (! in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
$fail(__('validation.template_path.file_type_not_allowed', [
'extension' => $extension,
'allowed' => implode(', ', self::ALLOWED_EXTENSIONS),
]));
return;
}
}
/**
* 허용된 확장자 목록 반환
*
* @return array
*/
public static function getAllowedExtensions(): array
{
+2 -1
View File
@@ -12,6 +12,7 @@ use App\Services\LayoutService;
use App\Services\PluginSettingsService;
use App\Services\SettingsService;
use App\Services\TemplateService;
use App\Support\AssetUrl;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;
@@ -689,7 +690,7 @@ class SeoRenderer implements SeoRendererInterface
foreach ($cssPaths as $cssPath) {
// dist/ 접두사 제거 (서빙 경로에서는 dist가 자동 추가됨)
$servePath = preg_replace('#^dist/#', '', $cssPath);
$urls[] = '/api/templates/assets/'.$templateIdentifier.'/'.$servePath;
$urls[] = AssetUrl::templateAsset($templateIdentifier, $servePath);
}
return $urls;
+6 -1
View File
@@ -7,6 +7,7 @@ use App\Extension\PluginManager;
use App\Extension\Storage\CoreStorageDriver;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Http\View\Composers\TemplateComposer;
use App\Support\AssetUrl;
use Illuminate\Support\Facades\Log;
/**
@@ -414,7 +415,11 @@ class ExtensionBundleService
return preg_replace_callback($pattern, function (array $m) use ($typeSegment, $identifier) {
$mapFile = ltrim($m[1], './');
return '//# sourceMappingURL=/api/'.$typeSegment.'/assets/'.$identifier.'/dist/js/'.basename($mapFile);
return '//# sourceMappingURL='.AssetUrl::extensionAsset(
$typeSegment,
$identifier,
'dist/js/'.basename($mapFile)
);
}, $content) ?? $content;
}
+36
View File
@@ -7,6 +7,7 @@ use App\Contracts\Repositories\AttachmentRepositoryInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\HookManager;
use App\Http\Resources\AttachmentResource;
use App\Seo\Contracts\SeoCacheManagerInterface;
use App\Support\ConfigCacheHelper;
use App\Support\OpcacheStatus;
use Illuminate\Support\Facades\Artisan;
@@ -44,6 +45,27 @@ class SettingsService
ConfigCacheHelper::rebuild();
}
/**
* 자산 URL 방식 변경에 따라 SEO 프리렌더 캐시를 비웁니다.
*
* SEO 캐시에는 생성 시점의 자산 URL 이 문자열로 구워져 있어, 모드가 바뀌면
* 그 URL 들이 전부 어긋난다. 사람 방문자는 브라우저 자가 복구가 살리지만
* 검색엔진 봇은 JavaScript 를 실행하지 않으므로 캐시를 비워 재생성시켜야 한다.
*
* 캐시 삭제 실패가 설정 저장 자체를 되돌리지는 않는다 — 설정은 이미 저장됐고,
* 캐시는 TTL 만료나 `seo:clear` 로도 회복 가능한 부수 상태다.
*/
private function clearSeoCacheForAssetUrlMode(): void
{
try {
app(SeoCacheManagerInterface::class)->clearAll();
} catch (\Throwable $e) {
Log::warning('자산 URL 방식 변경 후 SEO 캐시 삭제 실패 — seo:clear 로 수동 삭제 필요', [
'error' => $e->getMessage(),
]);
}
}
/**
* 모든 시스템 설정을 조회합니다.
*
@@ -476,12 +498,26 @@ class SettingsService
$existingSettings = $this->configRepository->getCategory($tab);
$mergedSettings = array_merge($existingSettings, $tabSettings);
// 자산 URL 방식이 바뀌는지 저장 **전에** 판정한다 (이슈 #486).
// 저장 후에는 이전 값을 알 수 없어 변경 여부를 판별할 수 없다.
$assetUrlModeChanged = $tab === 'general'
&& array_key_exists('asset_url_mode', $tabSettings)
&& ($existingSettings['asset_url_mode'] ?? null) !== $tabSettings['asset_url_mode'];
// 해당 카테고리 설정 저장
$result = $this->configRepository->saveCategory($tab, $mergedSettings);
if ($result) {
$this->invalidateSettingsCache();
// SEO 프리렌더 캐시에는 생성 시점의 자산 URL 이 그대로 구워져 있다.
// 모드가 바뀌면 그 URL 들이 전부 어긋나는데, 봇은 JavaScript 를 실행하지
// 않아 브라우저 자가 복구가 닿지 않는다 → 캐시를 비워 재생성시킨다.
// CLI(`g7:asset-url-mode`)와 동일한 처리 (계획서 §알려진 한계).
if ($assetUrlModeChanged) {
$this->clearSeoCacheForAssetUrlMode();
}
// drivers 탭은 queue/broadcasting/cache 등 long-running worker에 영향
// SettingsServiceProvider는 worker boot 시점에 한 번만 config 적용하므로
// 워커가 정상 종료 후 재시작되도록 신호 전송 (cache 기반, 즉시 종료 X)
+11 -5
View File
@@ -1739,13 +1739,19 @@ class TemplateService
*/
private function sanitizePath(string $path): string
{
// ../ 및 ..\ 패턴 제거
$path = str_replace(['../', '..\\'], '', $path);
// ../ 및 ..\ 패턴 제거 — 결과가 안정될 때까지 반복한다.
//
// 1회성 치환이면 제거 자체가 새 패턴을 만들어낸다:
// '....//' → 가운데 '../' 제거 → '../' (탈출 시퀀스 복원)
// 현재는 FormRequest 의 realpath 검사가 앞단에서 막고 있으나,
// 방어 계층이 하나 무력한 상태로 두지 않는다.
do {
$previous = $path;
$path = str_replace(['../', '..\\'], '', $path);
} while ($path !== $previous);
// 절대 경로 방지
$path = ltrim($path, '/\\');
return $path;
return ltrim($path, '/\\');
}
/**
+252
View File
@@ -0,0 +1,252 @@
<?php
namespace App\Support;
use App\Support\Routing\DualExtensionRoute;
/**
* 자산·동적 엔드포인트 URL 생성기 (서버측 SSoT).
*
* ## 왜 필요한가
*
* G7 은 동적 API 엔드포인트에 정적 파일 확장자를 붙여 쓴다. 그런데 nginx/Apache 의
* 표준적 정적 최적화 블록(`location ~* \.(js|css|json)$`)은 URL 마지막 확장자로
* 분기하며, nginx 에서 정규식 location 은 프리픽스 location 보다 먼저 매칭되므로
* `try_files ... /index.php` 폴백이 실행될 기회가 없다. 그런 환경에서는 확장자 붙은
* 동적 응답이 PHP 에 도달하지 못하고 404 가 된다.
*
* 라우트는 이미 두 형태로 등록되어 있다(`DualExtensionRoute`). 남은 문제는 **URL 을
* 만드는 쪽**이 13개 지점에 흩어져 하드코딩되어 있었다는 것이다. 한 곳만 빠뜨려도
* 그 자산만 404 가 되고, 어느 지점이 빠졌는지는 화면이 죽어야 알 수 있다.
* 그래서 생성 경로를 여기 하나로 모은다.
*
* ## 모드
*
* `general.asset_url_mode` 설정값을 따른다.
*
* | 모드 | 의미 |
* |---|---|
* | `extension` (기본) | 확장자 유지 — 정상 환경. 확장자 기반 캐시/gzip 최적화를 보존한다 |
* | `extensionless` | 확장자 제거 — 정적 블록이 가로채는 환경 |
*
* 기본값이 `extension` 인 이유는 계획서 §"채택 방향" 을 따른다. 확장자를 일괄 제거하면
* `expires max` / `gzip_static` / CDN TTL 규칙이 함께 걸린 다수의 정상 환경에서
* 그 최적화를 전부 잃는다.
*
* @see DualExtensionRoute 라우트 이중 등록
*/
class AssetUrl
{
/**
* 확장자 유지 모드 식별자.
*/
public const MODE_EXTENSION = 'extension';
/**
* 확장자 제거 모드 식별자.
*/
public const MODE_EXTENSIONLESS = 'extensionless';
/**
* 확장자 없는 자산 URL 에서 파일 경로를 담는 쿼리 파라미터명.
*/
public const FILE_QUERY_PARAM = 'file';
/**
* 테스트/렌더 단위에서 모드를 강제하기 위한 오버라이드 값.
*
* null 이면 설정값을 조회한다.
*/
private static ?string $modeOverride = null;
/**
* 현재 자산 URL 모드를 반환합니다.
*
* 설정 조회가 실패해도(설치 전·마이그레이션 전 등) 예외를 던지지 않고
* 기본 모드로 폴백한다 — 이 값은 blade 렌더 경로에서 읽히므로 여기서
* 터지면 화면 전체가 죽는다.
*
* @return string `extension` 또는 `extensionless`
*/
public static function mode(): string
{
if (self::$modeOverride !== null) {
return self::$modeOverride;
}
try {
$mode = g7_core_settings('general.asset_url_mode', self::MODE_EXTENSION);
} catch (\Throwable $e) {
return self::MODE_EXTENSION;
}
return $mode === self::MODE_EXTENSIONLESS ? self::MODE_EXTENSIONLESS : self::MODE_EXTENSION;
}
/**
* 현재 모드가 확장자 없는 모드인지 여부를 반환합니다.
*
* @return bool 확장자 없는 모드이면 true
*/
public static function isExtensionless(): bool
{
return self::mode() === self::MODE_EXTENSIONLESS;
}
/**
* 모드를 강제로 지정합니다 (테스트 전용).
*
* @param string|null $mode 강제할 모드. null 이면 오버라이드 해제
*/
public static function forceMode(?string $mode): void
{
self::$modeOverride = $mode;
}
/**
* 템플릿 자산 URL 을 생성합니다.
*
* 템플릿은 서버가 `dist/` 를 자동 부가하므로 `$path` 는 `dist/` 를 포함하지 않는다
* (`TemplateService::getAssetFilePath`). 모듈/플러그인과 비대칭이므로 주의.
*
* @param string $identifier 템플릿 식별자
* @param string $path `dist/` 이하 파일 경로 (예: `js/components.iife.js`)
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
* @return string 생성된 URL
*/
public static function templateAsset(string $identifier, string $path, int|string|null $version = null): string
{
return self::asset('templates', $identifier, $path, $version);
}
/**
* 모듈 자산 URL 을 생성합니다.
*
* 모듈은 모듈 루트 기준이라 `$path` 에 `dist/` 를 직접 포함해야 한다
* (`ModuleService::getAssetFilePath`).
*
* @param string $identifier 모듈 식별자
* @param string $path 모듈 루트 기준 파일 경로 (예: `dist/js/x.iife.js`)
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
* @return string 생성된 URL
*/
public static function moduleAsset(string $identifier, string $path, int|string|null $version = null): string
{
return self::asset('modules', $identifier, $path, $version);
}
/**
* 플러그인 자산 URL 을 생성합니다.
*
* @param string $identifier 플러그인 식별자
* @param string $path 플러그인 루트 기준 파일 경로 (예: `dist/js/x.iife.js`)
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
* @return string 생성된 URL
*/
public static function pluginAsset(string $identifier, string $path, int|string|null $version = null): string
{
return self::asset('plugins', $identifier, $path, $version);
}
/**
* 확장 타입을 인자로 받는 자산 URL 생성기.
*
* 모듈/플러그인을 같은 코드 경로로 처리하는 호출부(공용 트레이트 등)용.
* 타입이 컴파일 시점에 정해져 있으면 `moduleAsset()` / `pluginAsset()` 를 쓴다.
*
* @param string $type `templates` / `modules` / `plugins`
* @param string $identifier 확장 식별자
* @param string $path 파일 경로
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
* @return string 생성된 URL
*/
public static function extensionAsset(string $type, string $identifier, string $path, int|string|null $version = null): string
{
return self::asset($type, $identifier, $path, $version);
}
/**
* 확장 병합 번들 URL 을 생성합니다.
*
* 접미사(js/css)가 번들 종류를 구분하므로 제거할 수 없다.
* 확장자 없는 모드에서는 경로 세그먼트로 내린다 (`bundle.js` → `bundle/js`).
*
* @param string $type `modules` 또는 `plugins`
* @param string $kind `js` 또는 `css`
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
* @return string 생성된 URL
*/
public static function extensionBundle(string $type, string $kind, int|string|null $version = null): string
{
$base = self::isExtensionless()
? "/api/{$type}/bundle/{$kind}"
: "/api/{$type}/bundle.{$kind}";
return $base.self::versionQuery($version);
}
/**
* 고정 접미사를 갖는 동적 엔드포인트 URL 을 생성합니다.
*
* 확장자 없는 모드에서는 접미사를 제거한다 (`routes.json` → `routes`).
*
* @param string $path 접미사를 제외한 경로 (예: `/api/templates/foo/routes`)
* @param string $suffix 접미사 (예: `json`)
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
* @return string 생성된 URL
*/
public static function suffixed(string $path, string $suffix, int|string|null $version = null): string
{
$base = rtrim($path, '/');
$normalized = ltrim($suffix, '.');
$url = self::isExtensionless() ? $base : $base.'.'.$normalized;
return $url.self::versionQuery($version);
}
/**
* 확장 자산 URL 을 생성하는 공통 구현.
*
* 확장자 없는 모드에서는 파일 경로를 `?file=` 쿼리로 옮긴다. 경로가 곧 파일명이라
* 접미사만 떼어낼 수 없기 때문이며, nginx 의 location 정규식이 쿼리스트링을 제외한
* 경로에만 매칭되므로 이 형태가 안전하다.
*
* @param string $type `templates` / `modules` / `plugins`
* @param string $identifier 확장 식별자
* @param string $path 파일 경로
* @param int|string|null $version 캐시 무효화 버전
* @return string 생성된 URL
*/
private static function asset(string $type, string $identifier, string $path, int|string|null $version): string
{
$path = ltrim($path, '/');
if (! self::isExtensionless()) {
return "/api/{$type}/assets/{$identifier}/{$path}".self::versionQuery($version);
}
$query = self::FILE_QUERY_PARAM.'='.rawurlencode($path);
if ($version !== null && $version !== '') {
$query .= '&v='.$version;
}
return "/api/{$type}/assets/{$identifier}?{$query}";
}
/**
* 캐시 무효화 쿼리스트링을 생성합니다.
*
* @param int|string|null $version 버전 값
* @return string `?v=...` 또는 빈 문자열
*/
private static function versionQuery(int|string|null $version): string
{
if ($version === null || $version === '') {
return '';
}
return '?v='.$version;
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Support\Routing;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
/**
* 동적 응답 라우트를 "확장자 형태"와 "확장자 없는 형태" 두 벌로 동시 등록하는 Route 매크로.
*
* ## 배경
*
* G7 은 동적 API 엔드포인트에 정적 파일 확장자를 붙여 쓴다 (`/api/templates/{id}/routes.json`).
* 그런데 nginx/Apache 의 표준적 정적 최적화 블록은 URL 마지막 확장자로 분기하며,
* nginx 에서 정규식 location 은 프리픽스 location 보다 먼저 매칭되므로
* `try_files ... /index.php` 폴백이 실행될 기회 자체가 없다.
*
* ```nginx
* location ~* \.(js|css|json)$ { expires max; access_log off; }
* ```
*
* 이 설정 하에서는 PHP 로 요청이 넘어가지 않고 nginx 가 직접 파일시스템을 열려 시도해
* 404 가 되며, G7 은 부트스트랩 자산부터 죽는다. 관례를 깬 쪽이 G7 이므로 해소 책임도
* G7 에 있다는 판단으로, 두 형태를 모두 서빙하고 환경에 따라 택일한다.
*
* ## 규칙
*
* - 고정 접미사 엔드포인트는 접미사를 뗀다 (`routes.json` → `routes`)
* - 와일드카드 자산 라우트는 경로가 곧 파일명이라 뗄 수 없으므로 쿼리로 옮긴다
* (`assets/{id}/js/a.js` → `assets/{id}?file=js/a.js`).
* nginx 의 location 정규식은 쿼리스트링을 제외한 경로에만 매칭되므로 안전하다.
* - 두 형태 모두 영구 유지한다. 확장자 형태를 제거하면 URL 을 하드코딩한
* 서드파티 확장이 깨진다.
*
* ## 등록 순서
*
* 확장자 형태를 항상 **먼저** 등록한다. 확장자 없는 형태가 더 느슨한 패턴이라
* (예: `layouts/{tpl}/{layoutName}` 의 `layoutName` 정규식은 `.` 를 포함해 greedy)
* 순서가 뒤집히면 확장자 없는 라우트가 `.json` 요청까지 삼킨다.
*
* @see DualRouteProxy
*/
class DualExtensionRoute
{
/**
* 확장자 없는 자산 라우트에서 파일 경로를 담는 쿼리 파라미터명.
*/
public const FILE_QUERY_PARAM = 'file';
/**
* Route 매크로 3종(`dualSuffix` / `dualSuffixSegment` / `dualAsset`)을 등록합니다.
*
* `AppServiceProvider::register()` 에서 호출됩니다. boot() 가 아닌 이유:
* 라우트 파일은 프레임워크 라우팅 부트스트랩(boot 단계)에서 로드되므로,
* 프로바이더 간 boot 순서에 의존하면 매크로 미정의 시점에 라우트가 로드될 수 있다.
* 모든 프로바이더의 register() 는 어떤 boot() 보다 먼저 실행된다.
*/
public static function register(): void
{
static::registerDualSuffix();
static::registerDualSuffixSegment();
static::registerDualAsset();
}
/**
* `Route::dualSuffix()` 매크로를 등록합니다.
*
* 고정 접미사를 갖는 엔드포인트를 두 형태로 등록합니다.
*
* ```php
* Route::dualSuffix('templates/{identifier}/routes', 'json', [Ctrl::class, 'getRoutes'])
* ->name('api.public.templates.routes');
* // → GET templates/{identifier}/routes.json (name: api.public.templates.routes)
* // → GET templates/{identifier}/routes (name: api.public.templates.routes.extensionless)
* ```
*/
private static function registerDualSuffix(): void
{
Route::macro('dualSuffix', function (string $uri, string $suffix, mixed $action): DualRouteProxy {
/** @var Router $this */
$base = rtrim($uri, '/');
// 확장자 형태를 먼저 등록 (더 구체적인 패턴이 우선 매칭되어야 함)
$extension = $this->get($base.'.'.ltrim($suffix, '.'), $action);
$extensionless = $this->get($base, $action);
return new DualRouteProxy($extension, $extensionless);
});
}
/**
* `Route::dualSuffixSegment()` 매크로를 등록합니다.
*
* 접미사 자체가 의미를 담아 **뗄 수 없는** 엔드포인트용입니다.
* `bundle.js` 와 `bundle.css` 는 접미사를 제거하면 둘 다 `bundle` 이 되어 충돌하므로,
* 접미사를 삭제하는 대신 경로 세그먼트로 내린다.
*
* ```php
* Route::dualSuffixSegment('modules/bundle', 'js', [Ctrl::class, 'serveBundleJs'])
* ->name('api.public.modules.bundle.js');
* // → GET modules/bundle.js (name: api.public.modules.bundle.js)
* // → GET modules/bundle/js (name: api.public.modules.bundle.js.extensionless)
* ```
*/
private static function registerDualSuffixSegment(): void
{
Route::macro('dualSuffixSegment', function (string $uri, string $suffix, mixed $action): DualRouteProxy {
/** @var Router $this */
$base = rtrim($uri, '/');
$normalized = ltrim($suffix, '.');
$extension = $this->get($base.'.'.$normalized, $action);
$extensionless = $this->get($base.'/'.$normalized, $action);
return new DualRouteProxy($extension, $extensionless);
});
}
/**
* `Route::dualAsset()` 매크로를 등록합니다.
*
* 와일드카드 파일 경로를 갖는 자산 서빙 엔드포인트를 두 형태로 등록합니다.
* 확장자 형태는 `{path}` 세그먼트로, 확장자 없는 형태는 `?file=` 쿼리로 경로를 받으며
* 양쪽 모두 동일 컨트롤러로 들어갑니다 (흡수는 각 FormRequest 의
* `prepareForValidation()` 이 담당).
*
* ```php
* Route::dualAsset('templates/assets/{identifier}', [Ctrl::class, 'serveAsset'])
* ->name('api.public.templates.assets');
* // → GET templates/assets/{identifier}/{path} where path = .*
* // → GET templates/assets/{identifier} (?file=js/a.js)
* ```
*/
private static function registerDualAsset(): void
{
Route::macro('dualAsset', function (string $uri, mixed $action): DualRouteProxy {
/** @var Router $this */
$base = rtrim($uri, '/');
// 확장자 형태를 먼저 등록 (경로 세그먼트가 더 구체적)
$extension = $this->get($base.'/{path}', $action)->where('path', '.*');
$extensionless = $this->get($base, $action);
return new DualRouteProxy($extension, $extensionless);
});
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Support\Routing;
use Illuminate\Routing\Route;
/**
* 이중 등록된 두 라우트(확장자 형태 · 확장자 없는 형태)를 하나처럼 체이닝하기 위한 프록시.
*
* `Route::dualSuffix()` / `Route::dualAsset()` 매크로가 반환하며, `name()` 을 제외한
* 모든 호출(`middleware()`, `where()`, `defaults()` 등)을 양쪽 라우트에 그대로 전달한다.
* 한쪽에만 적용되어 조용히 어긋나는 상황을 구조적으로 차단하는 것이 목적이다.
*
* @mixin Route
*/
class DualRouteProxy
{
/**
* 확장자 없는 형태의 라우트 이름에 붙는 접미사.
*
* 두 라우트에 같은 이름을 주면 Laravel 의 이름 조회가 나중에 등록된 쪽으로
* 덮여 `route()` 결과가 조용히 바뀐다. 확장자 형태가 기존 이름을 유지하고
* 확장자 없는 형태만 접미사를 갖는다 (하위호환).
*/
public const EXTENSIONLESS_NAME_SUFFIX = '.extensionless';
/**
* @param Route $extension 확장자 형태 라우트 (예: `templates/{id}/routes.json`)
* @param Route $extensionless 확장자 없는 형태 라우트 (예: `templates/{id}/routes`)
*/
public function __construct(
private readonly Route $extension,
private readonly Route $extensionless,
) {}
/**
* 확장자 형태 라우트를 반환합니다.
*
* @return Route 확장자 형태 라우트 인스턴스
*/
public function extensionRoute(): Route
{
return $this->extension;
}
/**
* 확장자 없는 형태 라우트를 반환합니다.
*
* @return Route 확장자 없는 형태 라우트 인스턴스
*/
public function extensionlessRoute(): Route
{
return $this->extensionless;
}
/**
* 두 라우트에 이름을 부여합니다.
*
* 확장자 형태는 전달된 이름을 그대로, 확장자 없는 형태는
* `.extensionless` 접미사를 붙여 등록합니다.
*
* @param string $name 라우트 이름
* @return self 체이닝을 위한 자기 자신
*/
public function name(string $name): self
{
$this->extension->name($name);
$this->extensionless->name($name.self::EXTENSIONLESS_NAME_SUFFIX);
return $this;
}
/**
* 그 외 모든 호출을 두 라우트에 동일하게 전달합니다.
*
* @param string $method 호출된 메서드명
* @param array<int, mixed> $arguments 전달 인자
* @return self 체이닝을 위한 자기 자신
*/
public function __call(string $method, array $arguments): self
{
$this->extension->{$method}(...$arguments);
$this->extensionless->{$method}(...$arguments);
return $this;
}
}