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:
+171
-144
@@ -21,6 +21,7 @@ use App\Enums\PermissionType;
|
||||
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
|
||||
use App\Extension\Helpers\DependencyEnricher;
|
||||
use App\Extension\Helpers\ExtensionBackupHelper;
|
||||
use App\Extension\Helpers\ExtensionInstallRollbackHelper;
|
||||
use App\Extension\Helpers\ExtensionMenuSyncHelper;
|
||||
use App\Extension\Helpers\ExtensionPendingHelper;
|
||||
use App\Extension\Helpers\ExtensionRoleSyncHelper;
|
||||
@@ -372,168 +373,186 @@ class ModuleManager implements ModuleManagerInterface
|
||||
|
||||
// _pending 또는 _bundled에서 활성 디렉토리로 복사 (미설치 모듈 설치 시)
|
||||
// force=true 시 활성 디렉토리가 있어도 원본으로 덮어씀 (불완전 설치 복구)
|
||||
$rollbackActivePath = $this->modulesPath.DIRECTORY_SEPARATOR.$moduleName;
|
||||
// 검증은 로드된 확장 인스턴스를 요구해 복사보다 뒤에 온다. 그래서 검증이 실패하면
|
||||
// 방금 만든 활성 디렉토리가 고아로 남는다 — DB 행이 없어 목록에도 뜨지 않고 오류도
|
||||
// 남지 않은 채 디스크만 점유한다. 이번 호출이 만든 것이면 되돌린다.
|
||||
$rollbackDirExisted = File::isDirectory($rollbackActivePath);
|
||||
|
||||
$onProgress?->__invoke('copy', '파일 복사 중...');
|
||||
$this->copyFromPendingOrBundled($moduleName, $onProgress, $force);
|
||||
|
||||
// 모듈이 활성 디렉토리에 있지 않으면 로드 시도
|
||||
$module = $this->getModule($moduleName);
|
||||
if (! $module) {
|
||||
// 복사 후 재로드 시도
|
||||
$this->reloadModule($moduleName);
|
||||
$module = $this->getModule($moduleName);
|
||||
}
|
||||
|
||||
if (! $module) {
|
||||
throw new \Exception(__('modules.not_found', ['module' => $moduleName]));
|
||||
}
|
||||
|
||||
// 그누보드7 코어 버전 호환성 검증
|
||||
CoreVersionChecker::validateExtension(
|
||||
$module->getRequiredCoreVersion(),
|
||||
$module->getIdentifier(),
|
||||
'module'
|
||||
);
|
||||
|
||||
// 의존성 확인 (트랜잭션 외부에서 먼저 검증)
|
||||
$onProgress?->__invoke('validate', '검증 중...');
|
||||
$this->checkDependencies($module);
|
||||
|
||||
// 권한 구조 검증 (계층형 구조 필수)
|
||||
$this->validatePermissionStructure($module, 'module');
|
||||
|
||||
// 언어 파일 경로 검증 (src/lang 경로 필수)
|
||||
$this->validateTranslationPath($module, 'module');
|
||||
|
||||
// SEO 변수명 중복 검증
|
||||
$this->validateSeoVariables($module, 'module');
|
||||
|
||||
// 모듈 설치 실행
|
||||
$module->clearLifecycleFailureReason();
|
||||
$result = $module->install();
|
||||
|
||||
if (! $result) {
|
||||
$failureReason = $module->getLifecycleFailureReason() ?? __('modules.errors.unknown_error');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Phase 1: 마이그레이션 실행 (DDL - 트랜잭션 외부)
|
||||
// MySQL에서 CREATE TABLE 등 DDL 문은 암시적 커밋을 유발하므로 트랜잭션 외부에서 실행
|
||||
$onProgress?->__invoke('migration', '마이그레이션 실행 중...');
|
||||
$this->runMigrations($module);
|
||||
|
||||
// Phase 2: 데이터 작업 (DML - 트랜잭션 내부)
|
||||
$onProgress?->__invoke('db', 'DB 등록 중...');
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
// 모듈이 활성 디렉토리에 있지 않으면 로드 시도
|
||||
$module = $this->getModule($moduleName);
|
||||
if (! $module) {
|
||||
// 복사 후 재로드 시도
|
||||
$this->reloadModule($moduleName);
|
||||
$module = $this->getModule($moduleName);
|
||||
}
|
||||
|
||||
// GitHub에서 최신 버전 정보 가져오기
|
||||
$latestVersion = $this->fetchLatestVersion($module);
|
||||
$updateAvailable = $latestVersion ? version_compare($latestVersion, $module->getVersion(), '>') : false;
|
||||
if (! $module) {
|
||||
throw new \Exception(__('modules.not_found', ['module' => $moduleName]));
|
||||
}
|
||||
|
||||
// 다국어 name, description 처리 (역호환성 지원)
|
||||
$name = $this->convertToMultilingual($module->getName());
|
||||
$description = $this->convertToMultilingual($module->getDescription());
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
|
||||
$manifest = HookManager::applyFilters(
|
||||
"module.{$module->getIdentifier()}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
|
||||
// 데이터베이스에 모듈 정보 저장
|
||||
$this->moduleRepository->updateOrCreate(
|
||||
['identifier' => $module->getIdentifier()],
|
||||
[
|
||||
'vendor' => $module->getVendor(),
|
||||
'name' => $name,
|
||||
'version' => $module->getVersion(),
|
||||
'latest_version' => $latestVersion,
|
||||
'description' => $description,
|
||||
'github_url' => $module->getGithubUrl(),
|
||||
'github_changelog_url' => $this->buildChangelogUrl($module->getGithubUrl()),
|
||||
'update_available' => $updateAvailable,
|
||||
'metadata' => $module->getMetadata(),
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
'vendor_mode' => $resolvedVendorMode->value,
|
||||
'config' => $module->getConfig(),
|
||||
'created_by' => Auth::id(),
|
||||
'updated_by' => Auth::id(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]
|
||||
// 그누보드7 코어 버전 호환성 검증
|
||||
CoreVersionChecker::validateExtension(
|
||||
$module->getRequiredCoreVersion(),
|
||||
$module->getIdentifier(),
|
||||
'module'
|
||||
);
|
||||
|
||||
// Role 자동 생성
|
||||
$this->createModuleRoles($module);
|
||||
// 의존성 확인 (트랜잭션 외부에서 먼저 검증)
|
||||
$onProgress?->__invoke('validate', '검증 중...');
|
||||
$this->checkDependencies($module);
|
||||
|
||||
// 권한 자동 생성
|
||||
$this->createModulePermissions($module);
|
||||
// 권한 구조 검증 (계층형 구조 필수)
|
||||
$this->validatePermissionStructure($module, 'module');
|
||||
|
||||
// 권한-Role 연결
|
||||
$this->assignPermissionsToRoles($module);
|
||||
// 언어 파일 경로 검증 (src/lang 경로 필수)
|
||||
$this->validateTranslationPath($module, 'module');
|
||||
|
||||
// 관리자 메뉴 자동 생성
|
||||
$this->createModuleMenus($module);
|
||||
// SEO 변수명 중복 검증
|
||||
$this->validateSeoVariables($module, 'module');
|
||||
|
||||
// IDV 정책 자동 동기화 (identity_policies 테이블)
|
||||
$this->syncModuleIdentityPolicies($module);
|
||||
// 모듈 설치 실행
|
||||
$module->clearLifecycleFailureReason();
|
||||
$result = $module->install();
|
||||
|
||||
// IDV 메시지 정의/템플릿 자동 동기화 (identity_message_definitions / identity_message_templates)
|
||||
$this->syncModuleIdentityMessages($module);
|
||||
if (! $result) {
|
||||
$failureReason = $module->getLifecycleFailureReason() ?? __('modules.errors.unknown_error');
|
||||
|
||||
// 알림 정의/템플릿 자동 동기화 (notification_definitions / notification_templates)
|
||||
$this->syncModuleNotificationDefinitions($module);
|
||||
return false;
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
// Phase 1: 마이그레이션 실행 (DDL - 트랜잭션 외부)
|
||||
// MySQL에서 CREATE TABLE 등 DDL 문은 암시적 커밋을 유발하므로 트랜잭션 외부에서 실행
|
||||
$onProgress?->__invoke('migration', '마이그레이션 실행 중...');
|
||||
$this->runMigrations($module);
|
||||
|
||||
// Phase 2: 데이터 작업 (DML - 트랜잭션 내부)
|
||||
$onProgress?->__invoke('db', 'DB 등록 중...');
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
// GitHub에서 최신 버전 정보 가져오기
|
||||
$latestVersion = $this->fetchLatestVersion($module);
|
||||
$updateAvailable = $latestVersion ? version_compare($latestVersion, $module->getVersion(), '>') : false;
|
||||
|
||||
// 다국어 name, description 처리 (역호환성 지원)
|
||||
$name = $this->convertToMultilingual($module->getName());
|
||||
$description = $this->convertToMultilingual($module->getDescription());
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
|
||||
$manifest = HookManager::applyFilters(
|
||||
"module.{$module->getIdentifier()}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
|
||||
// 데이터베이스에 모듈 정보 저장
|
||||
$this->moduleRepository->updateOrCreate(
|
||||
['identifier' => $module->getIdentifier()],
|
||||
[
|
||||
'vendor' => $module->getVendor(),
|
||||
'name' => $name,
|
||||
'version' => $module->getVersion(),
|
||||
'latest_version' => $latestVersion,
|
||||
'description' => $description,
|
||||
'github_url' => $module->getGithubUrl(),
|
||||
'github_changelog_url' => $this->buildChangelogUrl($module->getGithubUrl()),
|
||||
'update_available' => $updateAvailable,
|
||||
'metadata' => $module->getMetadata(),
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
'vendor_mode' => $resolvedVendorMode->value,
|
||||
'config' => $module->getConfig(),
|
||||
'created_by' => Auth::id(),
|
||||
'updated_by' => Auth::id(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]
|
||||
);
|
||||
|
||||
// Role 자동 생성
|
||||
$this->createModuleRoles($module);
|
||||
|
||||
// 권한 자동 생성
|
||||
$this->createModulePermissions($module);
|
||||
|
||||
// 권한-Role 연결
|
||||
$this->assignPermissionsToRoles($module);
|
||||
|
||||
// 관리자 메뉴 자동 생성
|
||||
$this->createModuleMenus($module);
|
||||
|
||||
// IDV 정책 자동 동기화 (identity_policies 테이블)
|
||||
$this->syncModuleIdentityPolicies($module);
|
||||
|
||||
// IDV 메시지 정의/템플릿 자동 동기화 (identity_message_definitions / identity_message_templates)
|
||||
$this->syncModuleIdentityMessages($module);
|
||||
|
||||
// 알림 정의/템플릿 자동 동기화 (notification_definitions / notification_templates)
|
||||
$this->syncModuleNotificationDefinitions($module);
|
||||
|
||||
DB::commit();
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// Phase 3: 시더 실행 (트랜잭션 외부)
|
||||
// 시더 내부에서 별도 트랜잭션을 사용할 수 있으므로 외부에서 실행
|
||||
$onProgress?->__invoke('seed', '시더 실행 중...');
|
||||
$this->runModuleSeeders($module);
|
||||
|
||||
// Phase 4: 기본 설정 파일 생성
|
||||
$onProgress?->__invoke('settings', '환경설정 초기화 중...');
|
||||
$this->initializeModuleSettings($module);
|
||||
|
||||
// Phase 4.5: Composer 의존성 설치 (외부 패키지가 있는 경우에만)
|
||||
// _pending에서 이미 설치한 경우 스킵 (vendor/가 활성 디렉토리에 복사됨)
|
||||
if (! $composerDoneInPending) {
|
||||
$onProgress?->__invoke('composer', 'Composer 의존성 설치 중...');
|
||||
if (! app()->environment('testing')
|
||||
&& $this->extensionManager->hasComposerDependencies('modules', $moduleName)) {
|
||||
$composerResult = $this->extensionManager->runComposerInstall('modules', $moduleName);
|
||||
if (! $composerResult) {
|
||||
Log::warning('모듈 Composer 의존성 설치 실패', ['module' => $moduleName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 5: 오토로드 병합 실행 (트랜잭션 외부)
|
||||
$onProgress?->__invoke('autoload', '오토로드 갱신 중...');
|
||||
$this->extensionManager->updateComposerAutoload();
|
||||
|
||||
// 모듈 상태 캐시 무효화
|
||||
self::invalidateModuleStatusCache();
|
||||
|
||||
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
|
||||
$this->incrementExtensionCacheVersion();
|
||||
RouteCacheHelper::rebuild();
|
||||
|
||||
// 확장 미들웨어 인덱스 무효화 — 새 모듈의 미들웨어 선언이 즉시 게이트에 반영.
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
|
||||
// 훅 발행: 모듈 설치 완료
|
||||
HookManager::doAction('core.modules.installed', $moduleName);
|
||||
|
||||
return true;
|
||||
} catch (\Throwable $e) {
|
||||
ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
|
||||
$rollbackActivePath,
|
||||
$rollbackDirExisted,
|
||||
$moduleName,
|
||||
'module',
|
||||
);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// Phase 3: 시더 실행 (트랜잭션 외부)
|
||||
// 시더 내부에서 별도 트랜잭션을 사용할 수 있으므로 외부에서 실행
|
||||
$onProgress?->__invoke('seed', '시더 실행 중...');
|
||||
$this->runModuleSeeders($module);
|
||||
|
||||
// Phase 4: 기본 설정 파일 생성
|
||||
$onProgress?->__invoke('settings', '환경설정 초기화 중...');
|
||||
$this->initializeModuleSettings($module);
|
||||
|
||||
// Phase 4.5: Composer 의존성 설치 (외부 패키지가 있는 경우에만)
|
||||
// _pending에서 이미 설치한 경우 스킵 (vendor/가 활성 디렉토리에 복사됨)
|
||||
if (! $composerDoneInPending) {
|
||||
$onProgress?->__invoke('composer', 'Composer 의존성 설치 중...');
|
||||
if (! app()->environment('testing')
|
||||
&& $this->extensionManager->hasComposerDependencies('modules', $moduleName)) {
|
||||
$composerResult = $this->extensionManager->runComposerInstall('modules', $moduleName);
|
||||
if (! $composerResult) {
|
||||
Log::warning('모듈 Composer 의존성 설치 실패', ['module' => $moduleName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 5: 오토로드 병합 실행 (트랜잭션 외부)
|
||||
$onProgress?->__invoke('autoload', '오토로드 갱신 중...');
|
||||
$this->extensionManager->updateComposerAutoload();
|
||||
|
||||
// 모듈 상태 캐시 무효화
|
||||
self::invalidateModuleStatusCache();
|
||||
|
||||
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
|
||||
$this->incrementExtensionCacheVersion();
|
||||
RouteCacheHelper::rebuild();
|
||||
|
||||
// 확장 미들웨어 인덱스 무효화 — 새 모듈의 미들웨어 선언이 즉시 게이트에 반영.
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
|
||||
// 훅 발행: 모듈 설치 완료
|
||||
HookManager::doAction('core.modules.installed', $moduleName);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -905,6 +924,9 @@ class ModuleManager implements ModuleManagerInterface
|
||||
* @param bool $deleteData 모듈 데이터(테이블) 삭제 여부
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @param string|null $failureReason 실패 시 사유가 담기는 out 파라미터 (성공 시 null)
|
||||
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
|
||||
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터.
|
||||
* 운영자에게 "지웠지만 사본은 여기 있다" 를 알리기 위한 것이므로 호출부가 노출해야 한다.
|
||||
* @return bool 제거 성공 여부
|
||||
*
|
||||
* @throws \Exception 모듈을 찾을 수 없을 때
|
||||
@@ -914,8 +936,10 @@ class ModuleManager implements ModuleManagerInterface
|
||||
bool $deleteData = false,
|
||||
?\Closure $onProgress = null,
|
||||
?string &$failureReason = null,
|
||||
?array &$preservedBackups = null,
|
||||
): bool {
|
||||
$failureReason = null;
|
||||
$preservedBackups = [];
|
||||
|
||||
// 상태 가드: 진행 중 상태 체크
|
||||
$existingRecord = $this->moduleRepository->findByIdentifier($moduleName);
|
||||
@@ -1045,7 +1069,10 @@ class ModuleManager implements ModuleManagerInterface
|
||||
|
||||
// 활성 모듈 디렉토리 전체 삭제 (_pending/_bundled에 원본 보존되므로 재설치 가능)
|
||||
$onProgress?->__invoke('files', '파일 삭제 중...');
|
||||
ExtensionPendingHelper::deleteExtensionDirectory($this->modulesPath, $module->getIdentifier());
|
||||
$preservedBackups = ExtensionPendingHelper::deleteExtensionDirectory(
|
||||
$this->modulesPath,
|
||||
$module->getIdentifier()
|
||||
);
|
||||
|
||||
// 메모리에서 모듈 제거
|
||||
unset($this->modules[$module->getIdentifier()]);
|
||||
|
||||
Reference in New Issue
Block a user