Files
Gnuboard7/app/Console/Commands/Module/BuildModuleCommand.php
T
HeuJung 90f154ecc0 fix(security): 배포본 소스맵 노출 차단 + 관리자 설정 탭 지연로딩 + 동반 결함 수정
## 소스맵 노출 차단 (공개 이슈 )

배포본에 .map 이 포함돼 원본 TS/TSX 전문(sourcesContent, 한글 주석 포함)이
그대로 노출됐다. 생성·서빙·저장소 유입 3계층을 모두 막는다.

- 빌드 config 15곳(코어 3 + _bundled 12): sourcemap 하드코딩 제거.
 G7_BUILD_SOURCEMAP 판정식으로 교체 — 미설정(로컬 npm run build)이면 생성해
 개발 디버깅 경험을 보존하고, 0 이면 미생성.
- Build{Core,Module,Plugin,Template}Command: 죽어 있던 --production 플래그 복구.
 $productionMode 를 콘솔 문자열에만 쓰고 npm 프로세스에 env 를 넘기지 않아
 산출물이 개발 빌드와 동일했다. runNpmCommand 에 $env 를 추가해 주입
 (--watch 에는 미주입). Symfony Process 는 부모 환경에 병합하므로 PATH 유실 없음.
- Allowed{Module,Plugin}FileType / {Module,Plugin}Service::getMimeType:
 허용 확장자 map 제거 — 익명 200 서빙 차단(템플릿은 원래 미허용, 3종 정책 일치).
- ExtensionBundleService: CSS 번들의 /*# sourceMappingURL=... */ strip 추가.
 CSS 는 블록 주석이라 JS 의 //# 패턴으로는 검출되지 않던 구멍.
- 추적 .map 13개 삭제 + .gitignore 전역 *.map 규칙(경로 한정 시 새 확장에서 누락).

실측: 산출 JS 의 sourceMappingURL 13 → 0, 추적 .map 13 → 0,
확장 디렉토리 npm run build 는 여전히 map 생성(개발 경험 회귀 없음).

## 관리자 환경설정 탭 지연 로딩

코어/이커머스/게시판 환경설정 화면이 진입 즉시 전 탭의 데이터소스를 한꺼번에
호출했다. 각 데이터소스에 활성 탭 조건(if)을 걸어 해당 탭에서만 fetch 하도록
변경하고, 결제 플러그인 3종의 테스트모드 상태 조회도 주문설정 탭으로 한정.

## 동반 결함 수정 (무관 결함 — 재발 방지 목적으로 같은 세션 처리)

- 나이스페이먼츠: 체크아웃 캐시 프리페치가 라우트를 가리지 않아 플러그인 번들이
 로드되는 모든 페이지(홈/게시판/로그인)에서 주문서를 조회 → 비회원 매번 422.
 형제 플러그인(kginicis)의 기존 가드 패턴을 적용해 체크아웃 경로로 한정.
- admin smoke 8건: 대부분 구현이 아니라 테스트 결함이었다 — URL 오타(단수 board),
 존재하지 않는 권한키, 앱 로케일이 en 인데 한국어 라벨 로케이터, DataGrid 버튼을
 먼저 잡던 휴리스틱 로케이터. 레이아웃에는 sticky className / 안정 id 를 부여.
- PHPDoc ↔ Pint 충돌 3건: 설명 없는 @param 은 no_superfluous_phpdoc_tags 가
 삭제해 audit phpdoc-public-method 와 무한 충돌. 한국어 설명을 붙여 양쪽 충족
 (리스너 3종의 설명 누락 메서드도 전수 보강).
- Log::spy 500 3건: spy 가 Log::channel('activity') 를 null 로 만들고
 logActivity 가 null->info 로 \Error → 같은 줄 catch(\Exception) 은 못 잡아
 통과. 운영에선 채널이 항상 로거이므로 제품 무결 → 테스트에 activity 채널
 보존 헬퍼 추가.
- NhnKcpApiServiceTest 5건: 스텁이 Unix 바이너리만 만들어 Windows 분기
 (pp_cli_exe.exe)에서만 실패. #!/bin/sh 는 Windows 실행 불가 → 파일 내 기존
 컨벤션대로 skip 가드.

## 테스트

- 소스맵 범위 130 passed (신규: BuildCommandSourcemapEnv, NoSourcemapArtifacts,
 ExtensionBundleService CSS strip, Allowed*FileType 반전, 자산 서빙 거부)
- 결제 3플러그인 505 passed / 0 failed (skipped 9 = Windows 전용 CLI, 사유 명시)
- 나이스페이먼츠 프론트 38 passed (가드 제거 시 red 실증 후 복원)
- E2E: production-sourcemap-exposure.spec.ts 6건 + 시나리오 매니페스트

버전: sirsoft-admin_basic 1.0.2 → 1.0.3, sirsoft-board 1.0.1 → 1.0.2
(각 manifest/package/lock/composer 동기화). 코어 7.0.4 는 미출시 누적.
2026-07-14 12:50:23 +09:00

406 lines
15 KiB
PHP

<?php
namespace App\Console\Commands\Module;
use App\Extension\ModuleManager;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Extension\Traits\GeneratesComponentManifest;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;
class BuildModuleCommand extends Command
{
use ClearsTemplateCaches;
use GeneratesComponentManifest;
/**
* The name and signature of the console command.
*/
protected $signature = 'module:build
{identifier? : 빌드할 모듈 식별자 (생략 시 --all 필요)}
{--all : 모든 모듈 빌드}
{--watch : 파일 변경 감시 모드}
{--production : 프로덕션 빌드}
{--active : 활성 디렉토리에서 빌드}';
/**
* The console command description.
*/
protected $description = '모듈의 프론트엔드 에셋을 빌드합니다 (기본: _bundled 디렉토리)';
/**
* 모듈 관리자
*/
public function __construct(
private ModuleManager $moduleManager
) {
parent::__construct();
}
/**
* Execute the console command.
*/
public function handle(): int
{
$identifier = $this->argument('identifier');
$buildAll = $this->option('all');
$watchMode = $this->option('watch');
$productionMode = $this->option('production');
if (! $identifier && ! $buildAll) {
$this->error('❌ 모듈 식별자를 지정하거나 --all 옵션을 사용하세요.');
$this->line('');
$this->line('사용법:');
$this->line(' php artisan module:build sirsoft-ecommerce');
$this->line(' php artisan module:build --all');
$this->line(' php artisan module:build sirsoft-ecommerce --watch');
$this->line(' php artisan module:build --all --production');
$this->line(' php artisan module:build sirsoft-ecommerce --active');
return Command::FAILURE;
}
try {
// 모듈 로드
$this->moduleManager->loadModules();
if ($buildAll) {
return $this->buildAllModules($productionMode);
}
return $this->buildModule($identifier, $watchMode, $productionMode);
} catch (\Exception $e) {
$this->error('❌ '.$e->getMessage());
Log::error('모듈 빌드 실패', [
'module' => $identifier ?? 'all',
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
/**
* 빌드 대상 경로를 결정합니다.
*
* 기본값: _bundled 디렉토리. --active 옵션 시 활성 디렉토리.
* --watch 모드에서는 활성 디렉토리를 사용합니다 (실시간 개발용).
*
* @param string $identifier 모듈 식별자
* @return array|null ['path' => string, 'source' => 'bundled'|'active'] 또는 null
*/
private function resolveBuildPath(string $identifier): ?array
{
$bundledPath = base_path("modules/_bundled/{$identifier}");
$activePath = base_path("modules/{$identifier}");
// --active 명시 → 활성 디렉토리
if ($this->option('active')) {
return is_dir($activePath)
? ['path' => $activePath, 'source' => 'active']
: null;
}
// --watch 모드 → 활성 디렉토리 (실시간 개발용)
if ($this->option('watch')) {
if (is_dir($activePath)) {
return ['path' => $activePath, 'source' => 'active'];
}
}
// 기본값: _bundled 우선
if (is_dir($bundledPath)) {
return ['path' => $bundledPath, 'source' => 'bundled'];
}
// _bundled에 없으면 활성 디렉토리 폴백
if (is_dir($activePath)) {
return ['path' => $activePath, 'source' => 'active'];
}
return null;
}
/**
* 단일 모듈 빌드
*
* @param string $identifier 모듈 식별자
* @param bool $watchMode 파일 감시 모드
* @param bool $productionMode 프로덕션 빌드
* @return int 명령 실행 결과 코드
*/
private function buildModule(string $identifier, bool $watchMode, bool $productionMode): int
{
// 경로 결정
$resolved = $this->resolveBuildPath($identifier);
if (! $resolved) {
$this->error("❌ 모듈을 찾을 수 없습니다: {$identifier}");
$this->line(' _bundled 및 활성 디렉토리 모두 존재하지 않습니다.');
return Command::FAILURE;
}
$buildPath = $resolved['path'];
$source = $resolved['source'];
// 소스 표시
$sourceLabel = $source === 'bundled' ? '_bundled' : '활성';
$this->info("📂 빌드 소스: {$sourceLabel} ({$buildPath})");
// package.json 존재 확인
$packageJsonPath = $buildPath.'/package.json';
if (! file_exists($packageJsonPath)) {
$this->error('❌ package.json 파일이 없습니다: '.$packageJsonPath);
$this->line(' 모듈 프론트엔드 구조를 먼저 생성하세요.');
return Command::FAILURE;
}
// 에셋 빌드 가능 여부 확인 (활성 모듈 인스턴스가 있는 경우)
$module = $this->moduleManager->getModule($identifier);
if ($module && ! $module->canBuild() && ! $module->hasAssets()) {
$this->warn('⚠️ 모듈에 빌드할 에셋이 없습니다: '.$identifier);
return Command::SUCCESS;
}
// node_modules 확인 및 설치
if (! is_dir($buildPath.'/node_modules')) {
$this->info('📦 의존성 설치 중...');
$installResult = $this->runNpmCommand(['npm', 'install'], $buildPath);
if ($installResult !== Command::SUCCESS) {
$this->error('❌ npm install 실패');
return Command::FAILURE;
}
}
// 빌드 명령 결정
$buildCommand = ['npm', 'run'];
if ($watchMode) {
$buildCommand[] = 'dev';
$this->info("👀 파일 감시 모드로 빌드 시작: {$identifier}");
$this->line(' Ctrl+C로 종료할 수 있습니다.');
} else {
$buildCommand[] = 'build';
$this->info("🔨 빌드 시작: {$identifier}".($productionMode ? ' (프로덕션)' : ''));
}
// 빌드 실행 (감시 모드에는 소스맵 억제를 주입하지 않는다 — 개발 중 디버깅 필요)
$result = $this->runNpmCommand(
$buildCommand,
$buildPath,
! $watchMode,
$watchMode ? [] : $this->buildEnv($productionMode)
);
if ($result === Command::SUCCESS && ! $watchMode) {
$this->info("✅ 빌드 완료: {$identifier}");
// 빌드 결과 파일 확인
$this->displayBuildResults($buildPath, $identifier);
// 편집기 컴포넌트 매니페스트(components.json) 생성
$manifestResult = $this->generateComponentManifest($buildPath, $identifier);
if ($manifestResult['written']) {
$this->line(" - components.json 생성됨 (컴포넌트 {$manifestResult['count']}개)");
} else {
$this->warn(' - components.json 생성 실패 (편집 모드 컨트롤 노출 제한)');
}
// 캐시 버전 증가 (브라우저 캐시 무효화)
$this->incrementExtensionCacheVersion();
$this->line(' - 캐시 버전 갱신됨');
// _bundled 빌드 시 활성 반영 안내
if ($source === 'bundled') {
$this->line('');
$this->info("💡 활성 디렉토리에 반영하려면: php artisan module:update {$identifier}");
}
}
return $result;
}
/**
* 빌드 결과 파일 정보를 출력합니다.
*
* @param string $buildPath 빌드된 경로
* @param string $identifier 모듈 식별자
*/
private function displayBuildResults(string $buildPath, string $identifier): void
{
// 활성 모듈 인스턴스가 있으면 getBuiltAssetPaths 활용
$module = $this->moduleManager->getModule($identifier);
if ($module) {
$builtPaths = $module->getBuiltAssetPaths();
if (! empty($builtPaths['js'])) {
$jsPath = $buildPath.'/'.$builtPaths['js'];
if (file_exists($jsPath)) {
$this->line(' - JS: '.$builtPaths['js'].' ('.number_format(filesize($jsPath) / 1024, 2).' KB)');
}
}
if (! empty($builtPaths['css'])) {
$cssPath = $buildPath.'/'.$builtPaths['css'];
if (file_exists($cssPath)) {
$this->line(' - CSS: '.$builtPaths['css'].' ('.number_format(filesize($cssPath) / 1024, 2).' KB)');
}
}
return;
}
// 활성 인스턴스 없으면 manifest에서 직접 확인
$manifestPath = $buildPath.'/module.json';
if (file_exists($manifestPath)) {
$manifest = json_decode(file_get_contents($manifestPath), true);
$assets = $manifest['assets'] ?? [];
if (! empty($assets['js']['output'])) {
$jsPath = $buildPath.'/'.$assets['js']['output'];
if (file_exists($jsPath)) {
$this->line(' - JS: '.$assets['js']['output'].' ('.number_format(filesize($jsPath) / 1024, 2).' KB)');
}
}
if (! empty($assets['css']['output'])) {
$cssPath = $buildPath.'/'.$assets['css']['output'];
if (file_exists($cssPath)) {
$this->line(' - CSS: '.$assets['css']['output'].' ('.number_format(filesize($cssPath) / 1024, 2).' KB)');
}
}
}
}
/**
* 모든 모듈 빌드
*
* @param bool $productionMode 프로덕션 빌드
* @return int 명령 실행 결과 코드
*/
private function buildAllModules(bool $productionMode): int
{
$buildTargets = [];
if ($this->option('active')) {
// --active: 활성 디렉토리만 대상
$activeModules = $this->moduleManager->getAllModules();
foreach ($activeModules as $identifier => $module) {
$activePath = base_path("modules/{$identifier}");
if (file_exists($activePath.'/package.json')
&& ($module->canBuild() || $module->hasAssets())) {
$buildTargets[$identifier] = true;
}
}
} else {
// 기본값: _bundled 디렉토리 스캔
$bundledModules = $this->moduleManager->getBundledModules();
foreach ($bundledModules as $identifier => $metadata) {
$bundledPath = $metadata['source_path'];
if (file_exists($bundledPath.'/package.json')) {
$assets = $metadata['assets'] ?? [];
if (! empty($assets['js']['entry']) || ! empty($assets['css']['entry']) || ! empty($assets)) {
$buildTargets[$identifier] = true;
}
}
}
}
if (empty($buildTargets)) {
$this->warn('⚠️ 빌드할 모듈이 없습니다.');
return Command::SUCCESS;
}
$sourceLabel = $this->option('active') ? '활성' : '_bundled';
$this->info("🔨 모든 모듈 빌드 시작 ({$sourceLabel})".($productionMode ? ' (프로덕션)' : ''));
$this->line(' 대상 모듈: '.implode(', ', array_keys($buildTargets)));
$this->line('');
$successCount = 0;
$failCount = 0;
foreach ($buildTargets as $identifier => $value) {
$this->line(" [{$identifier}]");
$result = $this->buildModule($identifier, false, $productionMode);
if ($result === Command::SUCCESS) {
$successCount++;
} else {
$failCount++;
}
$this->line('');
}
$this->info("📊 빌드 결과: 성공 {$successCount}개, 실패 {$failCount}개");
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
}
/**
* 빌드 프로세스에 주입할 환경변수를 구성합니다.
*
* 프로덕션 빌드에서는 소스맵을 생성하지 않습니다. 배포 산출물에 원본 코드가
* 포함되는 것을 막기 위함이며, 각 vite config 가 이 값을 읽습니다.
*
* @param bool $productionMode 프로덕션 빌드 여부
* @return array<string, string> Process 에 주입할 환경변수
*/
private function buildEnv(bool $productionMode): array
{
return $productionMode ? ['G7_BUILD_SOURCEMAP' => '0'] : [];
}
/**
* npm 명령 실행
*
* @param array $command 실행할 명령
* @param string $cwd 작업 디렉토리
* @param bool $waitForCompletion 완료 대기 여부
* @param array<string, string> $env 추가로 주입할 환경변수 (부모 환경에 병합됨)
* @return int 명령 실행 결과 코드
*/
private function runNpmCommand(array $command, string $cwd, bool $waitForCompletion = true, array $env = []): int
{
// Windows 환경에서는 cmd /c 사용
if (PHP_OS_FAMILY === 'Windows') {
$command = array_merge(['cmd', '/c'], $command);
}
$process = new Process($command);
$process->setWorkingDirectory($cwd);
// Symfony Process 는 지정한 env 를 부모 환경에 병합하므로(PATH 등 유지) 추가분만 넘긴다.
if ($env !== []) {
$process->setEnv($env);
}
$process->setTimeout(null); // 타임아웃 없음
if ($waitForCompletion) {
$process->run(function ($type, $buffer) {
$this->output->write($buffer);
});
return $process->isSuccessful() ? Command::SUCCESS : Command::FAILURE;
}
// 감시 모드: 인터럽트까지 실행
$process->start(function ($type, $buffer) {
$this->output->write($buffer);
});
// 프로세스가 실행 중인 동안 대기
while ($process->isRunning()) {
usleep(100000); // 100ms
}
return Command::SUCCESS;
}
}