feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)
공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다. 브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도 남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데 자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기 하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발 대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다. 런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다. 자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그 실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML 에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다. 편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다. 두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의 custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에 의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다. 확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을 고치면 그 변경을 감지해 재게시까지 예약된다. FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접 넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로 나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린 스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과 분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠 화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를 함께 뒀다. 동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에 써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
1 parent
72f2e94c1a
commit
3945b6f1b3
1042 files changed
+107435
-947
No files matched your search
@@ -0,0 +1,222 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Exceptions\CustomAssetOperationException;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Requests\Admin\Extension\ReadExtensionCustomAssetRequest;
|
||||
use App\Http\Requests\Admin\Extension\SaveExtensionCustomAssetRequest;
|
||||
use App\Http\Requests\Admin\Extension\UploadExtensionCustomAssetRequest;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use App\Services\CustomAssetService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 확장 사용자 추가 에셋(`custom/`) 어드민 컨트롤러
|
||||
*
|
||||
* 운영자가 자기 CSS·JS·폰트·이미지를 화면에서 직접 넣고 고칠 수 있게 한다. 레이아웃
|
||||
* 편집기의 [커스텀 자산] 모달이 본 API 를 호출한다.
|
||||
*
|
||||
* 모듈·플러그인·템플릿을 **한 엔드포인트**가 다룬다. 타입별로 나누면 같은 검증·문서·테스트가
|
||||
* 세 벌로 갈리고, 그중 하나만 약해지면 그 경로가 조용한 우회로가 된다. 기존
|
||||
* `extensions/{type}/{identifier}` 선례(확장 복구 API)와 같은 형태다.
|
||||
*
|
||||
* 권한은 라우트의 permission 미들웨어(`core.extensions.custom_assets.manage`)가 담당한다.
|
||||
* 레이아웃 편집 권한과 **분리**된 이유: 여기서 올린 스크립트는 그 레이아웃 한 장이 아니라
|
||||
* 사이트 전 화면에서 실행되므로, 레이아웃을 고칠 수 있다는 것이 곧 그 권한이 될 수 없다.
|
||||
*/
|
||||
class AdminExtensionCustomAssetController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* 라우트 파라미터(단수) → 해석기 어휘(복수)
|
||||
*
|
||||
* 라우트는 기존 확장 공통 API 와 같은 단수형을 쓰고(`module|plugin|template`),
|
||||
* 해석기·서빙은 디렉토리 이름과 같은 복수형을 쓴다. 변환을 한 곳에 모아 둔다 —
|
||||
* 흩어지면 한쪽 표기만 고쳐 놓고 다른 쪽에서 조용히 빈 목록이 된다.
|
||||
*/
|
||||
private const TYPE_MAP = [
|
||||
'module' => 'modules',
|
||||
'plugin' => 'plugins',
|
||||
'template' => 'templates',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private CustomAssetService $service,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋 목록 조회.
|
||||
*
|
||||
* @param string $type 확장 타입 (`module` | `plugin` | `template`)
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return JsonResponse 파일 목록 + 편집기 메타(허용 확장자·크기 상한)
|
||||
*/
|
||||
public function index(string $type, string $identifier): JsonResponse
|
||||
{
|
||||
try {
|
||||
$files = $this->service->list($this->resolveType($type), $identifier);
|
||||
} catch (CustomAssetOperationException $e) {
|
||||
return $this->error($e->errorKey, 422, null, $e->params);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('사용자 추가 에셋 목록 조회 실패', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->error('custom_assets.errors.read_failed', 500, $e, ['path' => 'custom/']);
|
||||
}
|
||||
|
||||
return $this->success('custom_assets.messages.listed', [
|
||||
'files' => $files,
|
||||
'editable_extensions' => CustomAssetService::EDITABLE_EXTENSIONS,
|
||||
'uploadable_extensions' => AllowedTemplateFileType::getAllowedExtensions(),
|
||||
'max_text_bytes' => CustomAssetService::MAX_TEXT_BYTES,
|
||||
'max_upload_bytes' => CustomAssetService::MAX_UPLOAD_BYTES,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트 파일 본문 조회.
|
||||
*
|
||||
* @param ReadExtensionCustomAssetRequest $request 검증된 요청 (`path`)
|
||||
* @param string $type 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return JsonResponse 본문 응답
|
||||
*/
|
||||
public function show(ReadExtensionCustomAssetRequest $request, string $type, string $identifier): JsonResponse
|
||||
{
|
||||
$path = (string) $request->validated('path');
|
||||
|
||||
try {
|
||||
$file = $this->service->read($this->resolveType($type), $identifier, $path);
|
||||
} catch (CustomAssetOperationException $e) {
|
||||
return $this->error($e->errorKey, 422, null, $e->params);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('사용자 추가 에셋 본문 조회 실패', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->error('custom_assets.errors.read_failed', 500, $e, ['path' => $path]);
|
||||
}
|
||||
|
||||
return $this->success('custom_assets.messages.listed', $file);
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트 파일 본문 저장 (없으면 생성).
|
||||
*
|
||||
* @param SaveExtensionCustomAssetRequest $request 검증된 요청 (`path`, `content`)
|
||||
* @param string $type 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return JsonResponse 저장 결과
|
||||
*/
|
||||
public function store(SaveExtensionCustomAssetRequest $request, string $type, string $identifier): JsonResponse
|
||||
{
|
||||
$path = (string) $request->validated('path');
|
||||
|
||||
try {
|
||||
$saved = $this->service->save(
|
||||
$this->resolveType($type),
|
||||
$identifier,
|
||||
$path,
|
||||
(string) $request->validated('content'),
|
||||
);
|
||||
} catch (CustomAssetOperationException $e) {
|
||||
return $this->error($e->errorKey, 422, null, $e->params);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('사용자 추가 에셋 저장 실패', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->error('custom_assets.errors.write_failed', 500, $e, ['path' => $path]);
|
||||
}
|
||||
|
||||
return $this->success('custom_assets.messages.saved', $saved);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 업로드 (폰트·이미지 등 바이너리 포함).
|
||||
*
|
||||
* @param UploadExtensionCustomAssetRequest $request 검증된 요청 (`file`, `directory`)
|
||||
* @param string $type 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return JsonResponse 업로드 결과
|
||||
*/
|
||||
public function upload(UploadExtensionCustomAssetRequest $request, string $type, string $identifier): JsonResponse
|
||||
{
|
||||
$directory = $request->validated('directory');
|
||||
|
||||
try {
|
||||
$uploaded = $this->service->upload(
|
||||
$this->resolveType($type),
|
||||
$identifier,
|
||||
$request->file('file'),
|
||||
is_string($directory) ? $directory : null,
|
||||
);
|
||||
} catch (CustomAssetOperationException $e) {
|
||||
return $this->error($e->errorKey, 422, null, $e->params);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('사용자 추가 에셋 업로드 실패', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->error('custom_assets.errors.write_failed', 500, $e, ['path' => (string) $directory]);
|
||||
}
|
||||
|
||||
return $this->success('custom_assets.messages.uploaded', $uploaded);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 삭제.
|
||||
*
|
||||
* @param ReadExtensionCustomAssetRequest $request 검증된 요청 (`path`)
|
||||
* @param string $type 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return JsonResponse 삭제 결과
|
||||
*/
|
||||
public function destroy(ReadExtensionCustomAssetRequest $request, string $type, string $identifier): JsonResponse
|
||||
{
|
||||
$path = (string) $request->validated('path');
|
||||
|
||||
try {
|
||||
$this->service->delete($this->resolveType($type), $identifier, $path);
|
||||
} catch (CustomAssetOperationException $e) {
|
||||
return $this->error($e->errorKey, 422, null, $e->params);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('사용자 추가 에셋 삭제 실패', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->error('custom_assets.errors.delete_failed', 500, $e, ['path' => $path]);
|
||||
}
|
||||
|
||||
return $this->success('custom_assets.messages.deleted', ['path' => $path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 라우트 타입 파라미터를 해석기 어휘로 바꿉니다.
|
||||
*
|
||||
* 라우트 정규식이 이미 세 값으로 제한하지만, 매핑에 없으면 그대로 넘긴다 —
|
||||
* 해석기가 알 수 없는 타입을 무효로 판정해 422 를 만든다(빈 목록으로 조용히
|
||||
* 통과시키지 않는다).
|
||||
*
|
||||
* @param string $type 라우트 파라미터
|
||||
* @return string 해석기 어휘
|
||||
*/
|
||||
private function resolveType(string $type): string
|
||||
{
|
||||
return self::TYPE_MAP[$type] ?? $type;
|
||||
}
|
||||
}
|
||||
@@ -390,10 +390,19 @@ class ModuleController extends AdminBaseController
|
||||
$moduleName = $validated['module_name'];
|
||||
$deleteData = $validated['delete_data'] ?? false;
|
||||
|
||||
$result = $this->moduleService->uninstallModule($moduleName, $deleteData, $uninstallFailureReason);
|
||||
$result = $this->moduleService->uninstallModule(
|
||||
$moduleName,
|
||||
$deleteData,
|
||||
$uninstallFailureReason,
|
||||
$preservedBackups
|
||||
);
|
||||
|
||||
if ($result) {
|
||||
return $this->success('module.uninstall_success');
|
||||
// 운영자가 넣은 `custom/` 은 삭제 전에 사본을 남긴다 — 그 경로를 응답에 실어
|
||||
// 알리지 않으면 로그를 뒤지지 않는 한 사본의 존재를 알 수 없다.
|
||||
return $this->success('module.uninstall_success', [
|
||||
'preserved_backups' => $preservedBackups ?? [],
|
||||
]);
|
||||
} else {
|
||||
return $this->error('module.uninstall_failed', 400, null, [
|
||||
'error' => $uninstallFailureReason ?? __('modules.errors.unknown_error'),
|
||||
|
||||
@@ -397,10 +397,19 @@ class PluginController extends AdminBaseController
|
||||
$pluginName = $validated['plugin_name'];
|
||||
$deleteData = $validated['delete_data'] ?? false;
|
||||
|
||||
$result = $this->pluginService->uninstallPlugin($pluginName, $deleteData, $uninstallFailureReason);
|
||||
$result = $this->pluginService->uninstallPlugin(
|
||||
$pluginName,
|
||||
$deleteData,
|
||||
$uninstallFailureReason,
|
||||
$preservedBackups
|
||||
);
|
||||
|
||||
if ($result) {
|
||||
return $this->success('plugins.uninstall_success');
|
||||
// 운영자가 넣은 `custom/` 은 삭제 전에 사본을 남긴다 — 그 경로를 응답에 실어
|
||||
// 알리지 않으면 로그를 뒤지지 않는 한 사본의 존재를 알 수 없다.
|
||||
return $this->success('plugins.uninstall_success', [
|
||||
'preserved_backups' => $preservedBackups ?? [],
|
||||
]);
|
||||
} else {
|
||||
return $this->error('plugins.uninstall_failed', 400, null, [
|
||||
'error' => $uninstallFailureReason ?? __('plugins.errors.unknown_error'),
|
||||
|
||||
@@ -286,10 +286,14 @@ class TemplateController extends AdminBaseController
|
||||
$templateName = $validated['template_name'];
|
||||
$deleteData = $validated['delete_data'] ?? false;
|
||||
|
||||
$result = $this->templateService->uninstallTemplate($templateName, $deleteData);
|
||||
$result = $this->templateService->uninstallTemplate($templateName, $deleteData, $preservedBackups);
|
||||
|
||||
if ($result) {
|
||||
return $this->success('templates.uninstall_success');
|
||||
// 운영자가 넣은 `custom/` 은 삭제 전에 사본을 남긴다 — 그 경로를 응답에 실어
|
||||
// 알리지 않으면 로그를 뒤지지 않는 한 사본의 존재를 알 수 없다.
|
||||
return $this->success('templates.uninstall_success', [
|
||||
'preserved_backups' => $preservedBackups ?? [],
|
||||
]);
|
||||
} else {
|
||||
return $this->error('templates.uninstall_failed', 400, null, [
|
||||
'error' => __('templates.errors.unknown_error'),
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin\Extension;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\SafeCustomAssetPath;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋 본문 조회·삭제 요청 검증
|
||||
*
|
||||
* 권한 검사는 라우트의 permission 미들웨어(core.extensions.custom_assets.manage)가 담당한다.
|
||||
*
|
||||
* 조회와 삭제가 같은 요청 클래스를 쓰는 이유: 둘 다 "존재하는 파일 하나를 경로로 지목"
|
||||
* 이라는 동일한 입력이고, 검증 강도가 갈리면 약한 쪽이 우회로가 된다.
|
||||
*/
|
||||
class ReadExtensionCustomAssetRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 확인 — 권한은 permission 미들웨어가 담당.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
// 삭제는 폰트·이미지도 대상이므로 확장자 제한을 두지 않는다. 편집 가능 여부는
|
||||
// 서비스가 판정한다 — 여기서 편집 확장자로 좁히면 올린 폰트를 지울 수 없다.
|
||||
'path' => ['required', 'string', 'max:255', new SafeCustomAssetPath],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('core.extension_custom_asset.read_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'path.required' => __('custom_assets.validation.path_required'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin\Extension;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\SafeCustomAssetPath;
|
||||
use App\Services\CustomAssetService;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋 본문 저장 요청 검증
|
||||
*
|
||||
* 권한 검사는 라우트의 permission 미들웨어(core.extensions.custom_assets.manage)가 담당하므로
|
||||
* authorize()는 true 를 고정 반환한다.
|
||||
*/
|
||||
class SaveExtensionCustomAssetRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 확인 — 권한은 permission 미들웨어가 담당.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
'path' => ['required', 'string', 'max:255', new SafeCustomAssetPath(CustomAssetService::EDITABLE_EXTENSIONS)],
|
||||
// 빈 문자열 저장을 허용한다 — 운영자가 CSS 를 통째로 비우는 것은 정당한 조작이고,
|
||||
// 그것을 막으면 파일을 지우는 것 말고는 되돌릴 방법이 없어진다.
|
||||
'content' => ['present', 'string', 'max:'.CustomAssetService::MAX_TEXT_BYTES],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('core.extension_custom_asset.save_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'path.required' => __('custom_assets.validation.path_required'),
|
||||
'content.present' => __('custom_assets.validation.content_present'),
|
||||
'content.max' => __('custom_assets.errors.too_large_to_edit', [
|
||||
'limit' => (string) CustomAssetService::MAX_TEXT_BYTES,
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin\Extension;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use App\Rules\SafeCustomAssetPath;
|
||||
use App\Services\CustomAssetService;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋 업로드 요청 검증
|
||||
*
|
||||
* 권한 검사는 라우트의 permission 미들웨어(core.extensions.custom_assets.manage)가 담당한다.
|
||||
*
|
||||
* 허용 확장자는 자산 서빙과 **같은 목록**(`AllowedTemplateFileType`)을 쓴다. 여기만 넓히면
|
||||
* 올릴 수는 있는데 서빙되지 않는 파일이 생기고, 여기만 좁히면 서빙 규칙이 사문화된다.
|
||||
*/
|
||||
class UploadExtensionCustomAssetRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 확인 — 권한은 permission 미들웨어가 담당.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$maxKilobytes = (int) (CustomAssetService::MAX_UPLOAD_BYTES / 1024);
|
||||
|
||||
$rules = [
|
||||
'file' => [
|
||||
'required',
|
||||
'file',
|
||||
'max:'.$maxKilobytes,
|
||||
'mimes:'.implode(',', AllowedTemplateFileType::getAllowedExtensions()),
|
||||
],
|
||||
// 하위 디렉토리는 선택 — 없으면 `custom/` 바로 아래에 놓인다.
|
||||
'directory' => ['nullable', 'string', 'max:200', new SafeCustomAssetPath],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('core.extension_custom_asset.upload_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'file.required' => __('custom_assets.validation.file_required'),
|
||||
'file.file' => __('custom_assets.validation.file_invalid'),
|
||||
'file.mimes' => __('custom_assets.validation.file_mimes', [
|
||||
'allowed' => implode(', ', AllowedTemplateFileType::getAllowedExtensions()),
|
||||
]),
|
||||
'file.max' => __('custom_assets.errors.upload_too_large', [
|
||||
'limit' => (string) CustomAssetService::MAX_UPLOAD_BYTES,
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Requests\Public\Template;
|
||||
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use App\Rules\SafeTemplatePath;
|
||||
use App\Support\CustomAssets;
|
||||
use App\Support\Routing\DualExtensionRoute;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
@@ -32,9 +33,19 @@ class ServeTemplateAssetRequest extends FormRequest
|
||||
// 확장 가능한 "동적 필드" 가 없는 요청이라 룰의 취지(필드 확장)도 해당하지 않는다.
|
||||
public function rules(): array
|
||||
{
|
||||
// 템플릿 식별자로부터 기준 경로 구성
|
||||
// 템플릿 식별자로부터 기준 경로 구성.
|
||||
//
|
||||
// 컨테인먼트 기준은 **실제로 읽는 디렉토리**여야 한다. 템플릿 자산은 `dist/` 이하가
|
||||
// 기본이지만 운영자 소유 디렉토리(`custom/`)만은 그 밖에 있고, 서빙측
|
||||
// `TemplateService::getAssetFilePath()` 가 그 분기를 갖는다. 기준을 `dist` 로
|
||||
// 고정하면 `custom/**` 은 realpath 가 실패해 문자열 접두 비교로만 통과하므로,
|
||||
// 검증한 경로와 읽는 경로가 서로 다른 상태가 된다. 두 곳의 분기를 같은 조건으로
|
||||
// 맞춰 둔다 — 한쪽만 바뀌면 custom 서빙이 조용히 깨지거나 검증이 헐거워진다.
|
||||
$identifier = $this->route('identifier');
|
||||
$basePath = base_path("templates/{$identifier}/dist");
|
||||
$requestedPath = (string) $this->input('path');
|
||||
$basePath = str_starts_with($requestedPath, CustomAssets::DIRECTORY.'/')
|
||||
? base_path("templates/{$identifier}")
|
||||
: base_path("templates/{$identifier}/dist");
|
||||
|
||||
return [
|
||||
'identifier' => ['required', 'string'],
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Resources;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use App\Support\TemplateExternals;
|
||||
use Composer\Semver\Semver;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -118,8 +119,18 @@ class TemplateResource extends BaseApiResource
|
||||
'components' => $this->getValue('components', ['basic' => [], 'composite' => []]),
|
||||
'license' => $this->getValue('license'),
|
||||
'metadata' => $this->getValue('metadata', []),
|
||||
// 외부 리소스 (template.json externals) — 정규화 책임은 TemplateExternals 에 위임
|
||||
'externals' => TemplateExternals::normalize($this->getValue('externals', [])),
|
||||
// 외부 리소스 (template.json externals) — 정규화 책임은 TemplateExternals 에 위임.
|
||||
// `asset` 항목의 URL 해석에는 식별자와 캐시 버전이 필요하므로 뷰 컴포저
|
||||
// (CollectsTemplateExternals) 와 같은 인자를 넘긴다 — 빠뜨리면 `asset` 항목이
|
||||
// "식별자 미상" 으로 조용히 버려져 응답에서 사라진다.
|
||||
'externals' => TemplateExternals::normalize(
|
||||
$this->getValue('externals', []),
|
||||
$this->getValue('identifier'),
|
||||
// 트레이트를 사용하는 클래스 경유로 호출한다 — 트레이트 정적 메서드
|
||||
// 직접 호출(`ClearsTemplateCaches::`)은 PHP 8.1+ E_DEPRECATED 라
|
||||
// 템플릿 상세 응답마다 로그를 남긴다 (AssetUrl::staticExtBase 와 동형).
|
||||
ExtensionStaticCacheService::getExtensionCacheVersion(),
|
||||
),
|
||||
// 의존성 상세 정보
|
||||
'dependencies' => $this->getDetailedDependencies(),
|
||||
// 타임스탬프
|
||||
|
||||
@@ -8,6 +8,7 @@ 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\CollectsCustomAssets;
|
||||
use App\Http\View\Composers\Traits\CollectsExtensionAssets;
|
||||
use App\Http\View\Composers\Traits\CollectsTemplateExternals;
|
||||
use App\Services\ModuleSettingsService;
|
||||
@@ -20,6 +21,7 @@ use Illuminate\View\View;
|
||||
class TemplateComposer
|
||||
{
|
||||
use CollectsActiveExtensionMeta;
|
||||
use CollectsCustomAssets;
|
||||
use CollectsExtensionAssets;
|
||||
use CollectsTemplateExternals;
|
||||
|
||||
@@ -95,12 +97,13 @@ class TemplateComposer
|
||||
$appConfig = [];
|
||||
}
|
||||
|
||||
// 템플릿의 외부 리소스 정보 수집
|
||||
$templateExternals = $this->collectTemplateExternals($activeTemplate);
|
||||
|
||||
// 확장 기능 캐시 버전 (브라우저 캐시 무효화용)
|
||||
$extensionCacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
|
||||
|
||||
// 템플릿의 외부 리소스 정보 수집
|
||||
// (자체 제공 `asset` 항목의 URL 을 만들 때 캐시 버전이 필요해 뒤로 옮겼다)
|
||||
$templateExternals = $this->collectTemplateExternals($activeTemplate, $extensionCacheVersion);
|
||||
|
||||
// 확장 프론트엔드 병합 번들 URL (상시 ON — 활성 에셋이 없으면 null)
|
||||
$bundleUrls = $this->buildExtensionBundleUrls($moduleAssets, $pluginAssets, $extensionCacheVersion);
|
||||
|
||||
@@ -120,6 +123,8 @@ class TemplateComposer
|
||||
$view->with('activePluginsMeta', $activePluginsMeta);
|
||||
$view->with('appConfig', $appConfig);
|
||||
$view->with('templateExternals', $templateExternals);
|
||||
$view->with('customAssets', $this->collectCustomAssets($activeTemplate));
|
||||
$view->with('customAssetsDisabled', $this->customAssetsDisabledByRequest());
|
||||
$view->with('trustedScriptHosts', $trustedScriptHosts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\View\Composers\Traits;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 사용자 추가 에셋(`custom/`) 수집 Trait
|
||||
*
|
||||
* 활성 확장의 `custom/` 자산을 모아 프론트로 넘긴다. 로드 자체는 프론트가 하며,
|
||||
* **확장 병합 번들 뒤**에 붙는다 — CSS 는 나중에 온 규칙이 이기므로, 운영자가 덧붙인
|
||||
* 스타일이 확장 스타일보다 뒤에 와야 재정의가 성립한다.
|
||||
*
|
||||
* 확장 간 순서는 모듈 → 플러그인 → 템플릿이다. 화면 외관의 최종 책임이 템플릿에 있어,
|
||||
* 템플릿 운영자의 재정의가 가장 뒤에 와야 한다.
|
||||
*
|
||||
* @property ModuleManagerInterface $moduleManager
|
||||
* @property PluginManagerInterface $pluginManager
|
||||
*/
|
||||
trait CollectsCustomAssets
|
||||
{
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/**
|
||||
* 활성 확장의 사용자 추가 에셋을 수집합니다.
|
||||
*
|
||||
* 비활성 확장은 제외한다 — 자산 서빙이 활성 확장만 응답하므로, 넣어 봐야 404 가
|
||||
* 될 항목을 페이지에 실을 이유가 없다.
|
||||
*
|
||||
* `?custom=off` 가 붙은 요청은 목록을 비운다 — 탈출구(D33). 운영자가 넣은 CSS 한
|
||||
* 줄이 관리자 화면을 조작 불능으로 만들면 그것을 고칠 화면에도 그 CSS 가 실려 있어
|
||||
* 스스로 갇힌다. 서버가 목록을 비우면 자산이 페이지에 **도달하지 않으므로**, 이미
|
||||
* 깨진 화면에서 자바스크립트가 돌기를 기대할 필요가 없다.
|
||||
*
|
||||
* @param string|null $templateIdentifier 활성 템플릿 식별자
|
||||
* @return array<int, array<string, mixed>> 서술자 목록 (로드 순서대로)
|
||||
*/
|
||||
private function collectCustomAssets(?string $templateIdentifier): array
|
||||
{
|
||||
if ($this->customAssetsDisabledByRequest()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$assets = $this->resolveCustomAssets($templateIdentifier);
|
||||
|
||||
// 변경을 감지해 버전이 올랐다면 방금 만든 URL 은 **옛 버전**을 가리킨다.
|
||||
// 그대로 내보내면 운영자가 파일을 고친 그 화면에서만 옛 CSS 가 보이고, 새로고침
|
||||
// 한 번을 더 해야 반영된다 — 원인을 알 수 없는 한 박자 지연으로만 나타난다.
|
||||
// 새 버전으로 다시 해석한다. 게시본은 아직 없으므로 URL 은 API 형태로 떨어지고,
|
||||
// 그 응답은 디스크의 최신 내용을 그대로 준다. 다음 요청부터 정적 경로가 된다.
|
||||
if ($this->syncCustomAssetCacheVersion($assets, $templateIdentifier)) {
|
||||
CustomAssets::flushCache();
|
||||
$assets = $this->resolveCustomAssets($templateIdentifier);
|
||||
}
|
||||
|
||||
return $assets;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 확장의 사용자 추가 에셋 서술자를 해석합니다.
|
||||
*
|
||||
* @param string|null $templateIdentifier 활성 템플릿 식별자
|
||||
* @return array<int, array<string, mixed>> 서술자 목록 (로드 순서대로)
|
||||
*/
|
||||
private function resolveCustomAssets(?string $templateIdentifier): array
|
||||
{
|
||||
$assets = [];
|
||||
|
||||
foreach ($this->activeExtensionIdentifiers('modules') as $identifier) {
|
||||
$assets = array_merge($assets, CustomAssets::forExtension('modules', $identifier));
|
||||
}
|
||||
|
||||
foreach ($this->activeExtensionIdentifiers('plugins') as $identifier) {
|
||||
$assets = array_merge($assets, CustomAssets::forExtension('plugins', $identifier));
|
||||
}
|
||||
|
||||
if (! empty($templateIdentifier)) {
|
||||
$assets = array_merge($assets, CustomAssets::forExtension('templates', $templateIdentifier));
|
||||
}
|
||||
|
||||
return $assets;
|
||||
}
|
||||
|
||||
/**
|
||||
* 운영자가 파일을 고쳤으면 확장 캐시 버전을 올립니다.
|
||||
*
|
||||
* custom 자산은 확장 자산과 **같은 메커니즘**으로 정적 게시되므로 갱신 축도 같아야
|
||||
* 한다. 그런데 확장 캐시 버전은 수명주기 이벤트에서만 오르고, 운영자가 FTP 로 파일
|
||||
* 하나를 바꾸는 것은 그 이벤트가 아니다. 그래서 파일 서명이 달라진 것을 여기서
|
||||
* 감지해 같은 단일 지점(`incrementExtensionCacheVersion`)을 호출한다 — 그 지점이
|
||||
* 재게시 예약까지 담당하므로 새로 만들 기계가 없다.
|
||||
*
|
||||
* 서명이 **저장된 적 없으면 올리지 않는다.** 캐시 스토어가 요청마다 비는 환경
|
||||
* (array 스토어 등)에서 "매번 달라짐" 으로 읽혀 버전이 무한히 오르고 재게시가
|
||||
* 끝없이 돌게 되기 때문이다. 첫 관측은 기록만 하고 다음 변화부터 반응한다.
|
||||
*
|
||||
* 버전을 올렸으면 `true` 를 돌려준다 — 호출자가 서술자를 다시 해석해야 한다.
|
||||
* 이미 만든 URL 은 옛 버전을 가리키기 때문이다.
|
||||
*
|
||||
* 서명은 **렌더 스코프별로** 따로 기억한다. 수집 대상이 모듈·플러그인(양쪽 동일)에
|
||||
* 더해 `resolveCustomAssets` 가 싣는 **그 렌더의 템플릿 하나**라, 관리자 렌더와
|
||||
* 사용자 렌더의 서명은 파일이 그대로여도 정상적으로 다르다. 기억할 자리가 하나면
|
||||
* 두 렌더가 번갈아 덮어쓰며 매번 "파일이 바뀌었다" 로 읽혀, 운영자가 아무것도
|
||||
* 건드리지 않았는데 페이지를 오갈 때마다 확장 캐시 버전이 오르고 전체 재게시가
|
||||
* 예약된다(모든 자산 URL 이 상시 변동 → 브라우저 캐시 무효). 예외도 화면 이상도
|
||||
* 없어 로그 외에는 드러나지 않는다.
|
||||
*
|
||||
* 스코프를 나누되 **키는 하나로 두고 값을 맵으로** 쓴다. `CustomAssetService` 가
|
||||
* 쓰기 뒤 이 키 하나를 `forget` 하는 것에 의존하므로(같은 키를 보는 두 소비자),
|
||||
* 키를 쪼개면 그 소비자가 일부만 지우게 되어 같은 결함군이 재생산된다.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $assets 수집된 서술자 목록
|
||||
* @param string|null $scope 렌더 스코프 (활성 템플릿 식별자)
|
||||
* @return bool 확장 캐시 버전을 올렸으면 true
|
||||
*/
|
||||
private function syncCustomAssetCacheVersion(array $assets, ?string $scope = null): bool
|
||||
{
|
||||
try {
|
||||
$parts = [];
|
||||
|
||||
foreach ($assets as $asset) {
|
||||
// 파일 출처만 본다 — 외부 URL·훅이 더한 항목은 파일 서명이 없다
|
||||
if (($asset['source'] ?? null) !== 'file') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts[] = ($asset['id'] ?? '').'@'.($asset['version'] ?? '');
|
||||
}
|
||||
|
||||
sort($parts, SORT_STRING);
|
||||
$signature = $parts === [] ? 'empty' : md5(implode('|', $parts));
|
||||
|
||||
$scopeKey = $scope ?? '';
|
||||
|
||||
$cache = app(CacheInterface::class);
|
||||
|
||||
// 구 배포본이 남긴 스칼라 값은 맵이 아니다 — 어느 스코프의 것인지 알 수 없으므로
|
||||
// 서명으로 쓰지 않고 미관측으로 취급한다(첫 관측은 기록만 하니 헛된 bump 가 없다).
|
||||
$storedMap = $cache->get(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
$storedMap = is_array($storedMap) ? $storedMap : [];
|
||||
|
||||
$stored = $storedMap[$scopeKey] ?? null;
|
||||
|
||||
if ($stored === $signature) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$storedMap[$scopeKey] = $signature;
|
||||
$cache->put(CustomAssets::SIGNATURE_CACHE_KEY, $storedMap);
|
||||
|
||||
if ($stored === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Log::info('사용자 추가 에셋 변경 감지 — 확장 캐시 버전을 올립니다.', [
|
||||
'scope' => $scopeKey,
|
||||
'previous' => $stored,
|
||||
'current' => $signature,
|
||||
]);
|
||||
|
||||
$this->incrementExtensionCacheVersion();
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
// 감지 실패가 화면을 막지 않는다 — 최악이라도 URL 이 한동안 옛 버전일 뿐이다
|
||||
Log::warning('사용자 추가 에셋 변경 감지 실패', ['error' => $e->getMessage()]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 이번 요청이 사용자 추가 에셋을 끄도록 요구했는지 판정합니다.
|
||||
*
|
||||
* 판정을 수집 **맨 앞**에 두는 것이 중요하다. 뒤에 두면 빈 목록이 변경 감지
|
||||
* (`syncCustomAssetCacheVersion`)에 도달해 "전부 사라짐" 으로 읽히고, 그 다음 정상
|
||||
* 요청이 다시 "전부 생김" 으로 읽혀 요청마다 확장 캐시 버전이 오르내린다.
|
||||
*
|
||||
* @return bool `?custom=off` 이면 true
|
||||
*/
|
||||
private function customAssetsDisabledByRequest(): bool
|
||||
{
|
||||
try {
|
||||
return request()->query('custom') === 'off';
|
||||
} catch (\Exception $e) {
|
||||
// 요청 컨텍스트가 없는 렌더(콘솔·SEO 사전 렌더 등)는 끄지 않는다
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 확장 식별자 목록을 돌려줍니다.
|
||||
*
|
||||
* @param string $extensionType `modules` | `plugins`
|
||||
* @return array<int, string> 식별자 목록
|
||||
*/
|
||||
private function activeExtensionIdentifiers(string $extensionType): array
|
||||
{
|
||||
try {
|
||||
$active = $extensionType === 'modules'
|
||||
? $this->moduleManager->getActiveModules()
|
||||
: $this->pluginManager->getActivePlugins();
|
||||
|
||||
return array_keys($active);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning("Failed to collect active {$extensionType} for custom assets: ".$e->getMessage());
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,10 +21,14 @@ trait CollectsTemplateExternals
|
||||
*
|
||||
* template.json의 externals 배열만 사용하며 legacy key fallback은 제공하지 않습니다.
|
||||
*
|
||||
* 항목이 `asset`(템플릿이 자체 제공하는 `dist/` 이하 경로)을 선언하면 식별자와
|
||||
* 캐시 버전으로 자산 URL 을 만든다 — 그래서 둘을 함께 받는다.
|
||||
*
|
||||
* @param string|null $templateIdentifier 템플릿 식별자
|
||||
* @param int|string|null $version 캐시 무효화 버전 (`asset` 항목의 `?v`)
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function collectTemplateExternals(?string $templateIdentifier): array
|
||||
private function collectTemplateExternals(?string $templateIdentifier, int|string|null $version = null): array
|
||||
{
|
||||
if (empty($templateIdentifier)) {
|
||||
return [];
|
||||
@@ -37,7 +41,7 @@ trait CollectsTemplateExternals
|
||||
return [];
|
||||
}
|
||||
|
||||
return TemplateExternals::normalize($template['externals']);
|
||||
return TemplateExternals::normalize($template['externals'], $templateIdentifier, $version);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('Failed to collect template externals: '.$e->getMessage());
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ 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\CollectsCustomAssets;
|
||||
use App\Http\View\Composers\Traits\CollectsExtensionAssets;
|
||||
use App\Http\View\Composers\Traits\CollectsTemplateExternals;
|
||||
use App\Services\ModuleSettingsService;
|
||||
@@ -25,6 +26,7 @@ use Illuminate\View\View;
|
||||
class UserTemplateComposer
|
||||
{
|
||||
use CollectsActiveExtensionMeta;
|
||||
use CollectsCustomAssets;
|
||||
use CollectsExtensionAssets;
|
||||
use CollectsTemplateExternals;
|
||||
|
||||
@@ -101,12 +103,13 @@ class UserTemplateComposer
|
||||
$appConfig = [];
|
||||
}
|
||||
|
||||
// 템플릿의 외부 리소스 정보 수집
|
||||
$templateExternals = $this->collectTemplateExternals($activeTemplate);
|
||||
|
||||
// 확장 기능 캐시 버전 (브라우저 캐시 무효화용)
|
||||
$extensionCacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
|
||||
|
||||
// 템플릿의 외부 리소스 정보 수집
|
||||
// (자체 제공 `asset` 항목의 URL 을 만들 때 캐시 버전이 필요해 뒤로 옮겼다)
|
||||
$templateExternals = $this->collectTemplateExternals($activeTemplate, $extensionCacheVersion);
|
||||
|
||||
// 확장 프론트엔드 병합 번들 URL (상시 ON — 활성 에셋이 없으면 null)
|
||||
$bundleUrls = $this->buildExtensionBundleUrls($moduleAssets, $pluginAssets, $extensionCacheVersion);
|
||||
|
||||
@@ -126,6 +129,8 @@ class UserTemplateComposer
|
||||
$view->with('activePluginsMeta', $activePluginsMeta);
|
||||
$view->with('appConfig', $appConfig);
|
||||
$view->with('templateExternals', $templateExternals);
|
||||
$view->with('customAssets', $this->collectCustomAssets($activeTemplate));
|
||||
$view->with('customAssetsDisabled', $this->customAssetsDisabledByRequest());
|
||||
$view->with('trustedScriptHosts', $trustedScriptHosts);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user