v7.0.0-beta.5 release

This commit is contained in:
HeuJung committed 2026-05-12 17:58:34 +09:00
1 parent 1db039ff34
commit eb467aca79
159 files changed
+7599 -218

No files matched your search

+153 -18
View File
@@ -661,9 +661,12 @@ class CoreUpdateCommand extends Command
private function spawnUpgradeStepsProcess(string $fromVersion, string $toVersion, bool $force, \Closure $log): bool
{
if (! function_exists('proc_open')) {
$log('proc_open 비활성 — spawn 스킵, in-process fallback 진행');
return false;
return $this->failSpawnWithMode(
'proc_open 비활성',
$log,
$fromVersion,
$toVersion,
);
}
$phpBinary = config('process.php_binary', PHP_BINARY);
@@ -708,17 +711,21 @@ class CoreUpdateCommand extends Command
$process = proc_open($commandLine, $descriptors, $pipes, base_path(), $env);
if (! is_resource($process)) {
$log('spawn 실패 — proc_open 자원 생성 실패');
return false;
return $this->failSpawnWithMode(
'proc_open 자원 생성 실패',
$log,
$fromVersion,
$toVersion,
);
}
fclose($pipes[0]);
// stdout 실시간 전달 — 상위 콘솔에서 진행 상황 확인 가능
// 단, [HANDOFF] 접두사 라인은 상위 콘솔로 노출하지 않고 페이로드만 보관한다
// (exit=UpgradeHandoffException::EXIT_CODE 감지 시 UpgradeHandoffException 재구성용).
// 단, [HANDOFF] / [STEPS_EXECUTED] 접두사 라인은 상위 콘솔로 노출하지 않고
// 페이로드만 보관한다 (각각 UpgradeHandoffException 재구성 / silent skip 가드용).
$handoffPayload = null;
$stepsExecuted = null;
while (! feof($pipes[1])) {
$line = fgets($pipes[1]);
if ($line !== false) {
@@ -730,19 +737,30 @@ class CoreUpdateCommand extends Command
if (str_starts_with($trimmed, '[HANDOFF] ')) {
$json = substr($trimmed, strlen('[HANDOFF] '));
$decoded = json_decode($json, true);
// resumeCommand 는 null 허용 (자식이 null 로 전달한 경우 부모가
// CoreUpdateCommand catch 분기에서 from/to 기반으로 자동 생성)
if (is_array($decoded)
&& array_key_exists('afterVersion', $decoded)
&& array_key_exists('reason', $decoded)
&& array_key_exists('resumeCommand', $decoded)
) {
// 페이로드 값 검증 — array_key_exists 만으로는 비정상 입력(빈 문자열·
// shell metacharacter·과도 길이) 이 통과한다. resumeCommand 는 null
// 허용 (자식이 null 로 전달한 경우 부모가 from/to 기반 자동 생성).
if ($this->isValidHandoffPayload($decoded)) {
$handoffPayload = $decoded;
$log('[spawn] 핸드오프 신호 수신: after='.$decoded['afterVersion']);
continue;
}
// 구조가 깨진 핸드오프 라인 — 정상 출력으로 간주해 그대로 전달
// 구조/값이 깨진 핸드오프 라인 — 정상 출력으로 간주해 그대로 전달
if (is_array($decoded)) {
$log('[spawn] 핸드오프 페이로드 검증 실패 — 정상 출력으로 처리: '.json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
}
if (str_starts_with($trimmed, '[STEPS_EXECUTED] ')) {
$json = substr($trimmed, strlen('[STEPS_EXECUTED] '));
$decoded = json_decode($json, true);
if (is_array($decoded) && isset($decoded['count']) && is_int($decoded['count']) && $decoded['count'] >= 0) {
$stepsExecuted = $decoded['count'];
$log('[spawn] 실행된 step 수: '.$stepsExecuted);
continue;
}
}
$this->line($trimmed);
@@ -768,16 +786,133 @@ class CoreUpdateCommand extends Command
}
if ($exitCode === 0) {
$log('spawn 완료 (exit=0)');
// silent skip 가드 — 자식이 [STEPS_EXECUTED] 신호를 발행하지 않거나, step 0건
// 실행한 채 exit=0 으로 종료한 경우. 이전 버전 자식 (beta.5 이전 디스크) 또는
// 자식이 비정상 종료 직전 silent skip 한 상태로 추정. fail-fast 모드 가드 적용.
if ($stepsExecuted === null) {
return $this->failSpawnWithMode(
'spawn 자식이 [STEPS_EXECUTED] 신호 미발행 — 이전 버전 자식 또는 silent skip 의심',
$log,
$fromVersion,
$toVersion,
);
}
if ($stepsExecuted === 0 && version_compare($fromVersion, $toVersion, '<')) {
return $this->failSpawnWithMode(
sprintf('spawn 자식 exit=0 이지만 step 0건 실행 — 의도된 동작이 아님 (from=%s to=%s)', $fromVersion, $toVersion),
$log,
$fromVersion,
$toVersion,
);
}
$log("spawn 완료 (exit=0, steps={$stepsExecuted})");
return true;
}
$log("spawn 비정상 종료 (exit={$exitCode}) — fallback 진행");
return $this->failSpawnWithMode(
"spawn 비정상 종료 (exit={$exitCode})",
$log,
$fromVersion,
$toVersion,
);
}
/**
* spawn 자식 프로세스 실패 시 `app.update.spawn_failure_mode` 에 따라 분기합니다.
*
* - 'abort' (기본): `UpgradeHandoffException` 을 throw 하여 부모의 in-process
* fallback 진입을 차단. 부모 catch 블록이 cleanup 후 운영자에게
* `core:execute-upgrade-steps` 수동 명령을 안내한다.
* - 'fallback' (호환): 기존 동작 — log 한 줄 남기고 false 반환. 호출자가
* in-process fallback 으로 진행. 부모 메모리 stale 시 fatal 위험.
*
* @param string $reason 실패 사유 (로그/안내 메시지에 포함)
* @param \Closure $log 로그 엔트리 수집 콜백
* @param string $fromVersion 업그레이드 시작 버전 (handoff afterVersion / resumeCommand 구성)
* @param string $toVersion 업그레이드 대상 버전 (resumeCommand 구성)
* @return false fallback 모드일 때만 반환. abort 모드는 throw 후 미반환.
*
* @throws UpgradeHandoffException mode=abort 일 때
*/
private function failSpawnWithMode(string $reason, \Closure $log, string $fromVersion, string $toVersion): bool
{
$mode = config('app.update.spawn_failure_mode', 'fallback');
if ($mode === 'abort') {
$resumeCommand = sprintf(
'php artisan core:execute-upgrade-steps --from=%s --to=%s --force',
$fromVersion,
$toVersion,
);
$log("spawn 자식 실패 — {$reason}. fail-fast 모드 abort.");
throw new UpgradeHandoffException(
afterVersion: $fromVersion,
reason: "spawn 자식 실패 — {$reason}. fail-fast 모드. 수동 재개로 진행하세요.",
resumeCommand: $resumeCommand,
);
}
$log("{$reason} — in-process fallback 진행 (stale 메모리 위험)");
return false;
}
/**
* [HANDOFF] 페이로드의 값을 검증합니다.
*
* spawn 자식의 stdout 을 부모가 그대로 신뢰하면 (a) 빈 afterVersion 으로 Step 11
* fromVersion 해석 혼란, (b) shell injection 문자열이 운영자 안내에 노출, (c) 과도한
* reason 길이로 로그 폭증 위험. 본 메서드는 다음 4가지 키/값을 동시에 검증한다:
*
* - `afterVersion`: 정규식 `/^\d+\.\d+\.\d+/` 매치 + 비어있지 않음
* - `reason`: string + 길이 < 500
* - `resumeCommand`: null 허용. string 일 때 길이 < 1000 + shell metacharacter(`;&|`$()<>`) 부재
*
* @param mixed $payload json_decode 결과
*/
private function isValidHandoffPayload($payload): bool
{
if (! is_array($payload)) {
return false;
}
foreach (['afterVersion', 'reason', 'resumeCommand'] as $key) {
if (! array_key_exists($key, $payload)) {
return false;
}
}
$afterVersion = $payload['afterVersion'];
if (! is_string($afterVersion) || $afterVersion === '' || ! preg_match('/^\d+\.\d+\.\d+/', $afterVersion)) {
return false;
}
$reason = $payload['reason'];
if (! is_string($reason) || strlen($reason) >= 500) {
return false;
}
$resumeCommand = $payload['resumeCommand'];
if ($resumeCommand !== null) {
if (! is_string($resumeCommand)) {
return false;
}
if (strlen($resumeCommand) >= 1000) {
return false;
}
if (preg_match('/[;&|`$()<>]/', $resumeCommand)) {
return false;
}
}
return true;
}
/**
* 업데이트 로그를 파일로 저장합니다.
*
@@ -78,7 +78,7 @@ class ExecuteUpgradeStepsCommand extends Command
$service->ensureWritableDirectories(
$writablePaths,
function (string $level, string $msg): void {
// 콘솔 + upgrade 로그 채널 동시 출력 — PO 가 단일 파일(upgrade.log)에서
// 콘솔 + upgrade 로그 채널 동시 출력 — 운영자가 단일 파일(upgrade.log)에서
// spawn 자식의 권한 정상화 진행을 추적할 수 있도록 양쪽 모두 누적.
$this->{$level === 'warning' ? 'warn' : 'info'}($msg);
\Illuminate\Support\Facades\Log::channel('upgrade')->$level('[spawn] '.$msg);
@@ -91,11 +91,16 @@ class ExecuteUpgradeStepsCommand extends Command
]);
}
$stepsExecuted = 0;
try {
$service->runUpgradeSteps(
$from,
$to,
fn (string $version) => $this->info("upgrade step 실행: {$version}"),
function (string $version) use (&$stepsExecuted): void {
$this->info("upgrade step 실행: {$version}");
$stepsExecuted++;
},
$force,
);
} catch (UpgradeHandoffException $e) {
@@ -134,6 +139,16 @@ class ExecuteUpgradeStepsCommand extends Command
return self::FAILURE;
}
// 부모 (CoreUpdateCommand::spawnUpgradeStepsProcess) 가 silent skip 가드용으로 파싱하는
// 명시 종료 신호. [HANDOFF] 와 동일 구조의 라인 프로토콜. 정상 종료 (handoff 미발생) 경로
// 에서만 발행되며, 부모는 exit=0 인데 본 라인이 부재하면 mode=abort 시 throw,
// mode=fallback 시 in-process 진행 (`spawn_failure_mode`).
$this->line('[STEPS_EXECUTED] '.json_encode([
'count' => $stepsExecuted,
'fromVersion' => $from,
'toVersion' => $to,
], JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
}
}
@@ -66,6 +66,17 @@ interface IdentityPolicyRepositoryInterface
*/
public function deleteByKey(string $key): bool;
/**
* 정책 모델을 영속화합니다 (Eloquent save 위임).
*
* upsert/updateByKey 가 다루지 않는 부분 갱신 경로 (예: user_overrides 부분 복원) 에서 사용합니다.
* Service 가 모델 객체에 직접 변경을 적용한 뒤 본 메서드로 저장 — Service-Repository 경유 패턴 유지.
*
* @param IdentityPolicy $policy 영속화할 모델
* @return bool 저장 성공 여부
*/
public function save(IdentityPolicy $policy): bool;
/**
* source_type+source_identifier 에 속하지 않은 stale 정책을 제거합니다.
*
+136
View File
@@ -0,0 +1,136 @@
<?php
namespace App\Extension;
use App\Contracts\Extension\UpgradeStepInterface;
use App\Extension\Upgrade\DataMigration;
use App\Extension\Upgrade\DataSnapshot;
use ReflectionClass;
/**
* 버전별 데이터 스냅샷 규약을 따르는 업그레이드 스텝 기본 클래스.
*
* 7.0.0-beta.5 부터 신규 업그레이드 스텝은 본 추상 클래스를 상속해야 한다.
* runUpgradeSteps 가 인스턴스 검증 직후 상속 여부를 확인하고 미상속 시 fatal.
*
* 격리 원칙 ("각 스텝별 동작 100% 동일 보장"):
* - 카탈로그 시드는 data/{version}/*.delta.json 으로 동결
* - Applier 는 data/{version}/appliers/ 안에 버전 namespace 로 동결
* - 변환 / 단발성 핫픽스는 data/{version}/migrations/ 안에 버전 namespace 로 동결
* - 스텝 파일 자체는 본 추상 클래스를 상속한 빈 껍데기 (모든 비즈니스 로직은 data/ 로 위임)
*
* 사용 예:
*
* class Upgrade_7_0_0_beta_5 extends AbstractUpgradeStep
* {
* // 모든 default 사용 — data/7.0.0-beta.5/ 의 manifest/appliers/migrations 가 SSoT
* }
*
* 상세: docs/extension/upgrade-step-guide.md §12
*/
abstract class AbstractUpgradeStep implements UpgradeStepInterface
{
/**
* data/{currentStep}/manifest.json 을 로드 + Applier 동적 로드.
*
* 카탈로그 변동이 없는 스텝은 manifest 파일 없이 자동 빈 스냅샷 반환.
*/
protected function dataSnapshot(UpgradeContext $context): DataSnapshot
{
return DataSnapshot::fromManifest($this->dataDir($context), $context);
}
/**
* data/{currentStep}/migrations/*.php 를 require_once + 버전 namespace 의 DataMigration
* 구현체를 인스턴스화하여 배열로 반환. 디렉토리 부재 시 빈 배열.
*
* 파일명은 정렬용 prefix (예: `01_RecoverActiveExtensionDirs.php`, `02_...php`) 를 허용한다.
* prefix 는 정규식 `^\d{2,}_` 로 클래스명 매핑 시 제거되며, 클래스명 자체는 prefix 없이
* 선언한다 (PHP 식별자 제약). 파일 정렬 결과가 실행 순서 — 명시적 순서가 필요하면 prefix 사용.
*
* @return array<int, DataMigration>
*/
protected function dataMigrations(UpgradeContext $context): array
{
$dir = $this->dataDir($context).'/migrations';
if (! is_dir($dir)) {
return [];
}
$files = glob($dir.'/*.php') ?: [];
sort($files);
$migrations = [];
$namespace = DataSnapshot::versionedNamespace($context, $dir).'\\Migrations';
foreach ($files as $file) {
require_once $file;
$baseName = basename($file, '.php');
$className = preg_replace('/^\d{2,}_/', '', $baseName);
$fqcn = $namespace.'\\'.$className;
if (class_exists($fqcn) && is_subclass_of($fqcn, DataMigration::class)) {
$migrations[] = new $fqcn;
}
}
return $migrations;
}
/**
* 카탈로그/변환 외 프레임워크 레벨 부수 작업 (선택).
*
* 본 PR 의 beta.5 재작성에서는 사용 안 함 — 모든 비즈니스 로직은 data/ 로 격리.
* 미래에 *모든 버전 공통* 인 부수 작업이 필요하면 override.
*
* default: no-op.
*/
protected function postRun(UpgradeContext $context): void {}
/**
* 업그레이드 스텝 실행 — 순서: dataSnapshot → dataMigrations → postRun.
*
* 본 메서드는 final — 하위 클래스가 순서 무력화 못 함.
*/
final public function run(UpgradeContext $context): void
{
$snapshot = $this->dataSnapshot($context);
if ($snapshot->appliers !== []) {
$context->logger->info(sprintf(
'[%s] DataSnapshot 적용 — Applier %d개',
$context->currentStep,
count($snapshot->appliers),
));
}
$snapshot->apply($context);
$migrations = $this->dataMigrations($context);
if ($migrations !== []) {
$context->logger->info(sprintf(
'[%s] DataMigration 실행 — %d개',
$context->currentStep,
count($migrations),
));
}
foreach ($migrations as $migration) {
$context->logger->info(sprintf(
'[%s] migration: %s',
$context->currentStep,
$migration->name(),
));
$migration->run($context);
}
$this->postRun($context);
}
/**
* data/{currentStep}/ 절대 경로 계산. 스텝 파일 위치 기반 — 코어/확장 무관.
*/
protected function dataDir(UpgradeContext $context): string
{
$stepFile = (new ReflectionClass($this))->getFileName();
return dirname($stepFile).'/data/'.$context->currentStep;
}
}
+5
View File
@@ -927,6 +927,11 @@ PHP;
$env['COMPOSER_HOME'] = $composerHome;
$env['HOME'] = $composerHome;
// root/super user 환경 + 비대화형 컨텍스트에서 composer interactive 경고로 인한
// 비정상 종료를 차단 (Synology DSM 등 PHP-FPM root 실행 환경 대응)
$env['COMPOSER_ALLOW_SUPERUSER'] = '1';
$env['COMPOSER_NO_INTERACTION'] = '1';
// Windows: TEMP 디렉토리가 없거나 쓰기 불가능하면 storage/temp 사용
if (PHP_OS_FAMILY === 'Windows') {
if (! isset($env['TEMP']) || ! is_dir($env['TEMP']) || ! is_writable($env['TEMP'])) {
@@ -0,0 +1,128 @@
<?php
namespace App\Extension\Helpers;
use App\Contracts\Extension\UpgradeStepInterface;
use App\Extension\AbstractUpgradeStep;
/**
* 확장(모듈/플러그인) 업그레이드 스텝의 AbstractUpgradeStep 상속 의무 가드.
*
* 코어 7.0.0-beta.5 에서 도입된 "버전별 데이터 스냅샷 규약" (AbstractUpgradeStep 의무) 을
* 확장 측에 동일 수준으로 적용한다.
*
* 의무 시작 버전 결정 규칙:
* - 확장의 manifest g7_version 제약이 7.0.0-beta.5 미만의 코어를 허용한다면 legacy
* (가드 미발동) — 그 확장은 본 인프라가 없던 코어를 인지하는 작성본이라 호환 보장.
* - 제약 최소 버전이 7.0.0-beta.5 이상이면 확장이 본 인프라를 인지함 → 그 확장의 현재
* working version 부터 step 작성 시 AbstractUpgradeStep 상속 의무.
*
* 즉 확장 작성자가 g7_version 을 7.0.0-beta.5 이상으로 상향하는 시점이 본 규약의 자동
* 적용 첫 버전이 된다.
*
* 상세: docs/extension/upgrade-step-guide.md §13
*/
class ExtensionUpgradeGuardHelper
{
/**
* AbstractUpgradeStep 의무가 도입된 코어 버전.
*/
public const ABSTRACT_INTRODUCED_AT = '7.0.0-beta.5';
/**
* 확장의 AbstractUpgradeStep 의무 시작 버전을 계산합니다.
*
* @param string|null $g7VersionConstraint manifest 의 g7_version (예: ">=7.0.0-beta.5")
* @param string $extensionWorkingVersion manifest 의 version (예: "1.0.0-beta.5")
* @return string|null 의무 시작 버전 또는 null (가드 미발동 — legacy)
*/
public static function resolveSinceVersion(
?string $g7VersionConstraint,
string $extensionWorkingVersion,
): ?string {
if ($g7VersionConstraint === null || trim($g7VersionConstraint) === '') {
return null;
}
$minVersion = self::extractMinimumVersion($g7VersionConstraint);
if ($minVersion === null) {
return null;
}
if (version_compare($minVersion, self::ABSTRACT_INTRODUCED_AT, '<')) {
return null;
}
return $extensionWorkingVersion;
}
/**
* 확장 step 이 본 가드를 통과하는지 검증합니다.
*
* stepVersion < sinceVersion 인 step (확장 버전 이전의 legacy step) 은 미발동.
* stepVersion >= sinceVersion 인 step 이 AbstractUpgradeStep 미상속이면 fatal.
*
* @param string $stepVersion 실행 중인 step 의 버전
* @param string $sinceVersion 의무 시작 버전 (resolveSinceVersion 결과; null 아님)
* @param UpgradeStepInterface $step step 인스턴스
* @param string $extensionType 확장 타입 ("module" / "plugin")
* @param string $extensionIdentifier 확장 식별자
*
* @throws \RuntimeException stepVersion >= sinceVersion 인데 AbstractUpgradeStep 미상속 시
*/
public static function assertAbstractInheritance(
string $stepVersion,
string $sinceVersion,
UpgradeStepInterface $step,
string $extensionType,
string $extensionIdentifier,
): void {
if (version_compare($stepVersion, $sinceVersion, '<')) {
return;
}
if ($step instanceof AbstractUpgradeStep) {
return;
}
throw new \RuntimeException(sprintf(
'Extension %s "%s" upgrade step %s must extend App\\Extension\\AbstractUpgradeStep '
.'(required from %s; introduced in core %s).',
$extensionType,
$extensionIdentifier,
$stepVersion,
$sinceVersion,
self::ABSTRACT_INTRODUCED_AT,
));
}
/**
* Semantic Versioning 제약 문자열에서 최소 버전을 추출합니다.
*
* 지원 형식:
* - ">=X.Y.Z[-suffix]" / ">X.Y.Z" / "X.Y.Z"
* - "^X.Y.Z" / "~X.Y.Z"
* - "A|B" (OR) — 첫 후보 기준
*
* 파싱 실패 시 null 반환 (보수적으로 가드 미발동).
*/
private static function extractMinimumVersion(string $constraint): ?string
{
$constraint = trim($constraint);
$pipeIdx = strpos($constraint, '|');
if ($pipeIdx !== false) {
$constraint = trim(substr($constraint, 0, $pipeIdx));
}
if (preg_match(
'/^(?:>=|>|\^|~|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[\-\.][a-zA-Z0-9\.\-]+)?)/',
$constraint,
$m,
)) {
return $m[1];
}
return null;
}
}
+61 -1
View File
@@ -49,6 +49,17 @@ class FilePermissionHelper
$destPath = $destination.DIRECTORY_SEPARATOR.$itemName;
// symlink 자체 보존: target 추적 없이 동일 symlink 재생성.
// SplFileInfo::isDir() 가 symlink 를 추적하므로 검사 순서가 isDir() 보다 먼저여야 한다.
// 미적용 시 `public/storage` 등 symlink 가 target 디렉토리 내용으로 복사되어 백업/복원 양쪽에서 손상.
if ($item->isLink()) {
if (static::copySymlink($item->getPathname(), $destPath)) {
continue;
}
// 복원 실패 (Windows SeCreateSymbolicLink 권한 부족 등) — 일반 복사로 fall-through.
// 운영자가 추후 `php artisan storage:link` 수동 실행으로 회복 가능.
}
if ($item->isDir()) {
static::copyDirectory($item->getPathname(), $destPath, $onProgress, $excludes, $itemRelativePath, $removeOrphans);
} else {
@@ -62,6 +73,50 @@ class FilePermissionHelper
}
}
/**
* symlink 자체를 보존 복사합니다 (target 미추적).
*
* 기존 dest 가 symlink 또는 파일이면 unlink, 디렉토리면 deleteDirectory 후 symlink 재생성.
* readlink / symlink 실패 시 false 반환 — 호출자가 일반 복사로 fall-through.
*
* Windows 환경에서 PHP `symlink()` 는 `SeCreateSymbolicLink` 권한이 필요하며 일반 사용자는
* 권한이 없을 가능성이 높다. 실패 시 warning 로그 후 false 반환하여 호출자가 일반 복사로
* fall-through 하도록 한다. 운영자는 업그레이드 후 `php artisan storage:link` 등 수동
* 명령으로 symlink 를 회복할 수 있다.
*
* @param string $source 소스 symlink 경로
* @param string $destination 대상 symlink 경로
* @return bool symlink 복원 성공 여부 (false 면 호출자가 일반 복사로 폴백)
*/
protected static function copySymlink(string $source, string $destination): bool
{
$target = @readlink($source);
if ($target === false) {
Log::warning('copySymlink: readlink 실패 — 일반 복사로 폴백', ['source' => $source]);
return false;
}
// 기존 dest 정리 — symlink/파일 은 unlink, 디렉토리는 deleteDirectory
if (is_link($destination) || is_file($destination)) {
@unlink($destination);
} elseif (is_dir($destination)) {
File::deleteDirectory($destination);
}
if (! @symlink($target, $destination)) {
Log::warning('copySymlink: symlink 생성 실패 — 일반 복사로 폴백', [
'source' => $source,
'destination' => $destination,
'target' => $target,
]);
return false;
}
return true;
}
/**
* 소스에 없고 대상에만 있는 파일/디렉토리를 삭제합니다.
*
@@ -90,7 +145,12 @@ class FilePermissionHelper
// 소스에 존재하지 않는 항목만 삭제
if (! File::exists($srcPath) && ! File::isDirectory($srcPath)) {
if ($destItem->isDir()) {
// symlink 는 항상 unlink — File::deleteDirectory 는 is_dir() 추적 검사 후
// 재귀 삭제하므로 symlink-to-dir 인 경우 target 의 모든 파일을 삭제하는 사고
// 발생 가능. is_link() 가 isDir() 보다 먼저 평가되어야 한다.
if (is_link($destItem->getPathname())) {
@unlink($destItem->getPathname());
} elseif ($destItem->isDir()) {
File::deleteDirectory($destItem->getPathname());
} else {
File::delete($destItem->getPathname());
@@ -190,6 +190,7 @@ class IdentityVerificationManager
* 특정 purpose 에 사용할 프로바이더를 해석합니다.
*
* 해석 순서:
* 0. 명시 $providerId 가 등록 + supportsPurpose 통과 → 사용 (호출자 명시 우선)
* 1. `settings.identity.purpose_providers.{purpose}` 에 명시적 지정 + 해당 프로바이더가 purpose 지원 → 사용
* 2. 기본 프로바이더가 purpose 지원 → 사용
* 3. 등록된 프로바이더 중 purpose 지원하는 첫 번째 → 사용
@@ -198,13 +199,21 @@ class IdentityVerificationManager
* 정책의 provider_id 가 우선되므로 (IdentityPolicyService::resolveRenderHint 참조), 본 메서드는
* 정책에 provider_id 가 명시되지 않은 경우의 fallback 으로 사용됩니다.
*
* $providerId 가 등록되지 않았거나 purpose 미지원이면 silent fallback (1~4 단계 진행).
* 운영자가 정책에 명시한 provider 가 비활성화/미설치된 상태에서도 가입 흐름이 중단되지 않도록 한다.
*
* @param string $purpose IDV 목적 (signup, password_reset, sensitive_action 등)
* @param string|null $providerId 호출자 명시 provider id (Mode A controller 요청 / Mode B 정책)
* @return IdentityVerificationInterface 해석된 provider
*/
public function resolveForPurpose(string $purpose): IdentityVerificationInterface
public function resolveForPurpose(string $purpose, ?string $providerId = null): IdentityVerificationInterface
{
$providers = $this->all();
if ($providerId !== null && $providerId !== '' && isset($providers[$providerId]) && $providers[$providerId]->supportsPurpose($purpose)) {
return $providers[$providerId];
}
$explicitId = (string) config("settings.identity.purpose_providers.{$purpose}", '');
if ($explicitId !== '' && isset($providers[$explicitId]) && $providers[$explicitId]->supportsPurpose($purpose)) {
return $providers[$explicitId];
+18 -3
View File
@@ -24,6 +24,7 @@ use App\Extension\Helpers\ExtensionMenuSyncHelper;
use App\Extension\Helpers\ExtensionPendingHelper;
use App\Extension\Helpers\ExtensionRoleSyncHelper;
use App\Extension\Helpers\ExtensionStatusGuard;
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
use App\Extension\Helpers\GithubHelper;
use App\Providers\CoreServiceProvider;
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
@@ -772,7 +773,7 @@ class ModuleManager implements ModuleManagerInterface
// 모듈 상태 캐시 무효화
self::invalidateModuleStatusCache();
// PO #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
// 요구사항 #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
HookManager::doAction('core.modules.after_deactivate', $module->getIdentifier());
}
@@ -867,7 +868,7 @@ class ModuleManager implements ModuleManagerInterface
if ($result) {
// 권한·메뉴·역할은 $deleteData=true 시에만 삭제.
// false 시 보존하여 재설치 시 기존 역할 할당/커스터마이징이 복원 가능하도록 한다.
// PO 정책: "동적 권한/메뉴는 '데이터도 함께 삭제' 옵션 체크 시에만 삭제"
// 운영 정책: "동적 권한/메뉴는 '데이터도 함께 삭제' 옵션 체크 시에만 삭제"
if ($deleteData) {
$this->removeModulePermissionsAndMenus($module);
@@ -4044,6 +4045,20 @@ class ModuleManager implements ModuleManagerInterface
$stepContext->logger->info("Upgrading {$module->getIdentifier()} step {$stepVersion}...");
if ($step instanceof UpgradeStepInterface) {
$sinceVersion = ExtensionUpgradeGuardHelper::resolveSinceVersion(
$module->getRequiredCoreVersion(),
$module->getVersion(),
);
if ($sinceVersion !== null) {
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
(string) $stepVersion,
$sinceVersion,
$step,
'module',
$module->getIdentifier(),
);
}
$step->run($stepContext);
} elseif (is_callable($step)) {
$step($stepContext);
@@ -4457,7 +4472,7 @@ class ModuleManager implements ModuleManagerInterface
/**
* --force 시 업데이트 소스를 결정합니다.
*
* PO 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* 운영 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* (일반 업데이트의 GitHub 우선과 반대 — 개발자가 로컬 번들로 되돌리려는 의도 존중)
*
* 우선순위:
+19 -4
View File
@@ -27,6 +27,7 @@ use App\Extension\Helpers\IdentityMessageSyncHelper;
use App\Extension\Helpers\IdentityPolicySyncHelper;
use App\Extension\Helpers\NotificationSyncHelper;
use App\Extension\Helpers\ExtensionStatusGuard;
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
use App\Extension\Helpers\GithubHelper;
use App\Providers\CoreServiceProvider;
use App\Extension\Vendor\Exceptions\VendorInstallException;
@@ -756,7 +757,7 @@ class PluginManager implements PluginManagerInterface
// 플러그인 상태 캐시 무효화
self::invalidatePluginStatusCache();
// PO #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
// 요구사항 #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
HookManager::doAction('core.plugins.after_deactivate', $plugin->getIdentifier());
}
@@ -887,7 +888,7 @@ class PluginManager implements PluginManagerInterface
if ($result) {
// 권한/역할은 $deleteData=true 시에만 삭제.
// PO 정책: "동적 권한은 '데이터도 함께 삭제' 옵션 체크 시에만 삭제"
// 운영 정책: "동적 권한은 '데이터도 함께 삭제' 옵션 체크 시에만 삭제"
if ($deleteData) {
$this->removePluginPermissions($plugin);
@@ -4208,7 +4209,7 @@ class PluginManager implements PluginManagerInterface
if (empty($filteredSteps)) {
return;
}
}
// 버전순 정렬
uksort($filteredSteps, 'version_compare');
@@ -4226,6 +4227,20 @@ class PluginManager implements PluginManagerInterface
$stepContext->logger->info("Upgrading {$plugin->getIdentifier()} step {$stepVersion}...");
if ($step instanceof UpgradeStepInterface) {
$sinceVersion = ExtensionUpgradeGuardHelper::resolveSinceVersion(
$plugin->getRequiredCoreVersion(),
$plugin->getVersion(),
);
if ($sinceVersion !== null) {
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
(string) $stepVersion,
$sinceVersion,
$step,
'plugin',
$plugin->getIdentifier(),
);
}
$step->run($stepContext);
} elseif (is_callable($step)) {
$step($stepContext);
@@ -4637,7 +4652,7 @@ class PluginManager implements PluginManagerInterface
/**
* --force 시 업데이트 소스를 결정합니다.
*
* PO 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* 운영 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* (일반 업데이트의 GitHub 우선과 반대 — 개발자가 로컬 번들로 되돌리려는 의도 존중)
*
* 우선순위:
+2 -2
View File
@@ -672,7 +672,7 @@ class TemplateManager implements TemplateManagerInterface
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
// PO #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
// 요구사항 #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
HookManager::doAction('core.templates.after_deactivate', $templateName);
Log::info(__('templates.messages.template_deactivated'), [
@@ -3116,7 +3116,7 @@ class TemplateManager implements TemplateManagerInterface
/**
* --force 시 업데이트 소스를 결정합니다.
*
* PO 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* 운영 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* (일반 업데이트의 GitHub 우선과 반대 — 개발자가 로컬 번들로 되돌리려는 의도 존중)
*
* 우선순위:
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Extension\Upgrade;
use App\Extension\UpgradeContext;
/**
* 카탈로그 JSON 으로 표현 불가한 imperative 변환 / 단발성 핫픽스 단위.
*
* 각 버전이 자기 시점의 변환 로직을 본 인터페이스 구현체로
* `upgrades/data/{version}/migrations/*.php` 에 작성한다.
*
* 적용 대상:
* - 컬럼 의미 변경 / 데이터 변환 (예: dot-path 변환)
* - 카탈로그 rename 의 충돌 경로 (Applier 가 처리하지 못하는 분기)
* - 단발성 파일시스템 핫픽스 (활성 디렉토리 복구, symlink 복구 등)
* - 그 버전 고유의 DB 보정 로직
*
* 구현 의무 (Applier 와 동일):
* - **idempotent**: 두 번 실행되어도 동일 결과
* - **V-1 안전**: 로컬 헬퍼 + `Illuminate\Support\Facades\*` 만 사용
* - **버전 격리**: 다른 버전 namespace 참조 금지
*
* 인스턴스화: `new {Migration}()` (인자 없음).
*
* 상세: docs/extension/upgrade-step-guide.md §12
*/
interface DataMigration
{
/**
* 마이그레이션 식별자 (로그용).
*
* @return string 사람이 읽을 수 있는 짧은 식별자 (예: "IdentityPermissionPivotMerge")
*/
public function name(): string;
/**
* 변환 / 핫픽스 적용. idempotent 의무.
*
* @param UpgradeContext $context 업그레이드 컨텍스트 (로거, 현재 스텝 버전 등)
* @return void
*
* @throws \Throwable 적용 실패 시 — runUpgradeSteps 가 상위에서 백업 복원 처리
*/
public function run(UpgradeContext $context): void;
}
+222
View File
@@ -0,0 +1,222 @@
<?php
namespace App\Extension\Upgrade;
use App\Extension\UpgradeContext;
use RuntimeException;
/**
* 한 업그레이드 스텝이 적용할 카탈로그 delta 의 모음.
*
* `data/{version}/manifest.json` 을 읽어 각 kind 의 delta JSON 과 그에 대응하는
* 버전 namespace 의 Applier 를 동적 로드 + 인스턴스화하여 `SnapshotApplier` 배열로 보유.
*
* 사용:
* $snapshot = DataSnapshot::fromManifest($dataDir, $context);
* $snapshot->apply($context);
*
* 상세: docs/extension/upgrade-step-guide.md §12
*/
final class DataSnapshot
{
/** @var array<int, SnapshotApplier> */
public readonly array $appliers;
/**
* @param array<int, SnapshotApplier> $appliers
*/
public function __construct(array $appliers)
{
$this->appliers = $appliers;
}
/**
* 빈 스냅샷 (카탈로그 변동이 없는 스텝용).
*
* @return self 빈 Applier 배열을 보유한 DataSnapshot
*/
public static function empty(): self
{
return new self([]);
}
/**
* data/{version}/manifest.json 을 로드하여 DataSnapshot 인스턴스 생성.
*
* manifest 부재 시 빈 스냅샷 반환 (V-1 호환 — 디렉토리 없어도 동작).
*
* @param string $dataDir upgrades/data/{version} 절대 경로
* @param UpgradeContext $context 현재 스텝 버전 정보 (namespace 계산용)
* @return self manifest 의 kind 별로 Applier 를 로드한 DataSnapshot
*
* @throws RuntimeException manifest JSON 파싱 실패 / Applier 클래스 부재 시
*/
public static function fromManifest(string $dataDir, UpgradeContext $context): self
{
$manifestPath = $dataDir.'/manifest.json';
if (! is_file($manifestPath)) {
return self::empty();
}
$manifest = json_decode(
file_get_contents($manifestPath),
true,
flags: JSON_THROW_ON_ERROR,
);
$appliers = [];
foreach ($manifest['files'] ?? [] as $entry) {
$kind = $entry['kind'] ?? null;
$file = $entry['file'] ?? null;
if (! is_string($kind) || ! is_string($file)) {
throw new RuntimeException(
"Invalid manifest entry in {$manifestPath}: kind/file required"
);
}
$applierClass = $entry['applier_class'] ?? self::kindToClassName($kind);
$appliers[] = self::makeApplier(
applierClass: $applierClass,
kind: $kind,
dataDir: $dataDir,
jsonPath: $dataDir.'/'.$file,
context: $context,
);
}
return new self($appliers);
}
/**
* 보유한 모든 Applier 를 순차 실행.
*
* @param UpgradeContext $context 업그레이드 컨텍스트 (로거, 현재 스텝 버전 등)
*/
public function apply(UpgradeContext $context): void
{
foreach ($this->appliers as $applier) {
$applier->apply($context);
}
}
/**
* 버전 namespace 의 Applier 클래스를 require_once + 인스턴스화.
*
* 예: kind="permissions", context->currentStep="7.0.0-beta.5"
* → 클래스 "App\Upgrades\Data\V7_0_0_beta_5\Appliers\PermissionsApplier"
* → 파일 "{dataDir}/appliers/PermissionsApplier.php"
*
* @throws RuntimeException Applier 파일/클래스 부재 또는 인터페이스 미구현 시
*/
private static function makeApplier(
string $applierClass,
string $kind,
string $dataDir,
string $jsonPath,
UpgradeContext $context,
): SnapshotApplier {
$applierFile = $dataDir.'/appliers/'.$applierClass.'.php';
if (! is_file($applierFile)) {
throw new RuntimeException(sprintf(
'Applier file not found: %s (kind=%s)',
$applierFile,
$kind,
));
}
require_once $applierFile;
$fqcn = self::versionedNamespace($context, $dataDir).'\\Appliers\\'.$applierClass;
if (! class_exists($fqcn)) {
throw new RuntimeException(sprintf(
'Applier class not declared in expected namespace: %s (file=%s)',
$fqcn,
$applierFile,
));
}
if (! is_subclass_of($fqcn, SnapshotApplier::class)) {
throw new RuntimeException(sprintf(
'Applier class must implement SnapshotApplier: %s',
$fqcn,
));
}
return new $fqcn($jsonPath);
}
/**
* 현재 스텝 버전의 namespace prefix 계산.
*
* 코어:
* "7.0.0-beta.5" → "App\Upgrades\Data\V7_0_0_beta_5"
* 번들/외부 모듈:
* path 가 `.../modules/.../upgrades/data/{ver}/` → "App\Upgrades\Data\Ext\Modules\{StudlyIdentifier}\V{token}"
* 번들/외부 플러그인:
* path 가 `.../plugins/.../upgrades/data/{ver}/` → "App\Upgrades\Data\Ext\Plugins\{StudlyIdentifier}\V{token}"
*
* 확장 식별자 segment 가 namespace 에 포함되어 두 다른 확장의 같은 step 버전 + 같은
* 클래스명 이 *별개* FQCN 으로 격리된다. 이로써 PHP compile-time fatal
* ("Cannot declare class ... because the name is already in use") 회귀가 차단된다.
*
* sourceLocation 미지정 시 코어 namespace 로 폴백 (기존 동작 보존).
*
* @param UpgradeContext $context 현재 스텝 버전 정보 보유
* @param string|null $sourceLocation step 파일 또는 dataDir 의 절대 경로 (코어/확장 분기 결정)
* @return string PSR-4 호환 namespace prefix (Applier/Migration 으로 이어짐)
*/
public static function versionedNamespace(UpgradeContext $context, ?string $sourceLocation = null): string
{
$token = 'V'.str_replace(['.', '-'], '_', $context->currentStep);
$base = 'App\\Upgrades\\Data';
if ($sourceLocation !== null) {
$normalized = str_replace('\\', '/', $sourceLocation);
if (preg_match(
'#(?:^|/)(modules|plugins)(?:/_bundled)?/([^/]+)/upgrades(?:/data)?/#',
$normalized,
$match,
)) {
$type = $match[1] === 'modules' ? 'Modules' : 'Plugins';
$identifier = self::studlyIdentifier($match[2]);
return "{$base}\\Ext\\{$type}\\{$identifier}\\{$token}";
}
}
return "{$base}\\{$token}";
}
/**
* 확장 식별자(`sirsoft-ecommerce` 등) 를 PHP namespace-safe StudlyCase 로 변환.
*
* "sirsoft-ecommerce" → "SirsoftEcommerce"
* "vendor_module_v2" → "VendorModuleV2"
*/
private static function studlyIdentifier(string $identifier): string
{
$parts = preg_split('/[-_]+/', $identifier) ?: [$identifier];
$studly = '';
foreach ($parts as $part) {
if ($part === '') {
continue;
}
$studly .= ucfirst($part);
}
return $studly !== '' ? $studly : 'Anonymous';
}
/**
* snake_case kind → StudlyCase Applier 클래스명.
*
* permissions → PermissionsApplier
* role_permissions → RolePermissionsApplier
* notification_definitions → NotificationDefinitionsApplier
*/
private static function kindToClassName(string $kind): string
{
$studly = str_replace(' ', '', ucwords(str_replace('_', ' ', $kind)));
return $studly.'Applier';
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Extension\Upgrade;
use App\Extension\UpgradeContext;
/**
* 카탈로그 delta JSON 한 파일을 DB 에 idempotent 하게 적용하는 단위.
*
* 각 버전이 자기가 사용하는 kind 별로 본 인터페이스 구현체를
* `upgrades/data/{version}/appliers/{Kind}Applier.php` 에 작성한다.
*
* 구현 의무:
* - **raw JSON 만 read**: 시더 클래스(`Database\Seeders\*`) 호출 금지
* - **idempotent**: `Schema::hasColumn` / `where->exists()` 가드 동반
* - **V-1 안전**: 로컬 SQL/Eloquent 만 사용, `app(*Service|*Manager|*Repository::class)` 금지
* - **버전 격리**: 다른 버전 namespace 의 클래스 참조 금지
*
* 인스턴스화: `new {Kind}Applier($absoluteJsonPath)`.
* 생성자는 delta JSON 파일의 절대 경로를 받아 `apply()` 시 read 한다.
*
* 상세: docs/extension/upgrade-step-guide.md §12
*/
interface SnapshotApplier
{
/**
* delta JSON 을 read 하여 DB 에 적용.
*
* @param UpgradeContext $context 업그레이드 컨텍스트 (로거, 현재 스텝 버전 등)
* @return void
*
* @throws \Throwable 적용 실패 시 — runUpgradeSteps 가 상위에서 백업 복원 처리
*/
public function apply(UpgradeContext $context): void;
}
+41 -1
View File
@@ -24,6 +24,8 @@ class EnvironmentDetector
/**
* proc_open() 함수 사용 가능 여부.
*
* @return bool proc_open 호출 가능 여부 (disable_functions 차단 시 false)
*/
public function hasProcOpen(): bool
{
@@ -38,6 +40,8 @@ class EnvironmentDetector
/**
* shell_exec() 함수 사용 가능 여부.
*
* @return bool shell_exec 호출 가능 여부 (disable_functions 차단 시 false)
*/
public function hasShellExec(): bool
{
@@ -52,6 +56,8 @@ class EnvironmentDetector
/**
* ZipArchive 클래스 사용 가능 여부.
*
* @return bool ext-zip 활성화 여부
*/
public function hasZipArchive(): bool
{
@@ -63,6 +69,9 @@ class EnvironmentDetector
*
* 우선순위: hint → config(process.composer_binary) → $_ENV['COMPOSER_BINARY']
* → PATH 검색 → composer.phar
*
* @param string|null $hint 바이너리 경로 힌트 (null 이면 config/ENV/PATH 순으로 자동 탐색)
* @return string|null 발견된 composer 바이너리 경로. 없으면 null
*/
public function findComposerBinary(?string $hint = null): ?string
{
@@ -108,6 +117,9 @@ class EnvironmentDetector
* composer 실행 가능 여부 종합 판단.
*
* proc_open 사용 가능 + composer 바이너리 발견 + `composer --version` 종료 코드 0.
*
* @param string|null $hint composer 바이너리 경로 힌트 (캐시 우회용)
* @return bool composer 가 현재 환경에서 실행 가능한지 여부
*/
public function canExecuteComposer(?string $hint = null): bool
{
@@ -135,7 +147,7 @@ class EnvironmentDetector
],
$pipes,
null,
null,
self::buildComposerEnv(),
['bypass_shell' => true]
);
@@ -163,6 +175,9 @@ class EnvironmentDetector
/**
* 지정 경로에 쓰기 가능한지 확인.
*
* @param string $targetPath vendor 디렉토리 경로 (존재하지 않아도 부모 디렉토리 쓰기 권한 검사)
* @return bool 부모 디렉토리가 존재하고 쓰기 가능한지 여부
*/
public function canWriteVendor(string $targetPath): bool
{
@@ -174,6 +189,7 @@ class EnvironmentDetector
/**
* 인스톨러 Step 2 요구사항 체크용 종합 리포트.
*
* @param string|null $hint composer 바이너리 경로 힌트 (캐시 우회용)
* @return array{
* proc_open: bool,
* shell_exec: bool,
@@ -210,6 +226,30 @@ class EnvironmentDetector
$this->cachedComposerBinary = null;
}
/**
* proc_open() 5번째 인자용 composer 환경변수 배열을 구성합니다.
*
* root/super user 환경 + 비대화형(웹) 컨텍스트에서 composer 가 interactive
* 경고를 출력하며 비정상 종료하는 문제를 차단합니다.
*
* 현재 프로세스의 환경변수(getenv() + $_ENV)에 두 composer 전용 변수를 마지막에
* 덮어쓰기 — 외부에서 0 으로 설정되어 있어도 강제로 1.
*
* @return array<string, string>
*/
public static function buildComposerEnv(): array
{
$current = getenv();
if (! is_array($current)) {
$current = [];
}
return array_merge($current, $_ENV, [
'COMPOSER_ALLOW_SUPERUSER' => '1',
'COMPOSER_NO_INTERACTION' => '1',
]);
}
/**
* composer 실행 명령 문자열 구성.
*
+11 -2
View File
@@ -68,6 +68,8 @@ class VendorBundler
*
* 러너는 `fn (string $stagingDir): void` 형식이며, 주어진 스테이징 디렉토리에
* vendor/ 구조를 직접 생성해야 합니다.
*
* @param \Closure|null $runner 대체 러너 (null 이면 기본 composer install 사용)
*/
public function setComposerInstallRunner(?\Closure $runner): void
{
@@ -78,6 +80,9 @@ class VendorBundler
* 코어(루트) vendor/를 번들링합니다.
*
* 코어는 소스 = 출력 경로가 base_path() 로 동일합니다.
*
* @param bool $force manifest 해시 일치 여부와 무관하게 강제 재빌드
* @return VendorBundleResult 번들 생성 결과 (zip 경로, manifest 경로, 패키지 수 등)
*/
public function buildForCore(bool $force = false): VendorBundleResult
{
@@ -98,7 +103,10 @@ class VendorBundler
* 이유: _bundled 는 Git 추적 소스 디렉토리로 vendor/ 를 두지 않는 것이 원칙.
* 활성 디렉토리는 설치 시 composer install 이 실행되어 실제 패키지가 설치된 상태.
*
* @param string $type 'module' | 'plugin'
* @param string $type 확장 타입 ('module' 또는 'plugin')
* @param string $identifier 확장 식별자 (vendor-name 형식, 예: 'sirsoft-ecommerce')
* @param bool $force manifest 해시 일치 여부와 무관하게 강제 재빌드
* @return VendorBundleResult 번들 생성 결과 (활성 디렉토리 부재 시 skipped=true)
*/
public function buildForExtension(string $type, string $identifier, bool $force = false): VendorBundleResult
{
@@ -156,6 +164,7 @@ class VendorBundler
*
* @param string $sourcePath composer.json/lock 을 읽을 경로 (활성 디렉토리)
* @param string|null $outputPath 번들 출력 경로 (null 이면 sourcePath 와 동일 — 코어 케이스)
* @return bool 번들이 stale 한지 여부 (해시 불일치 또는 manifest 부재). 외부 의존성이 없으면 항상 false
*/
public function isStale(string $sourcePath, ?string $outputPath = null): bool
{
@@ -391,7 +400,7 @@ class VendorBundler
2 => ['pipe', 'w'],
];
$process = @proc_open($command, $descriptors, $pipes, $stagingDir);
$process = @proc_open($command, $descriptors, $pipes, $stagingDir, EnvironmentDetector::buildComposerEnv());
if (! is_resource($process)) {
throw new VendorInstallException(
@@ -242,7 +242,7 @@ class LanguagePackController extends AdminBaseController
}
/**
* 여러 언어팩을 일괄 활성화합니다 (PO #7 reactivate 모달 → "활성화" 버튼).
* 여러 언어팩을 일괄 활성화합니다 (요구사항 #7 reactivate 모달 → "활성화" 버튼).
*
* @param \App\Http\Requests\LanguagePack\BulkActivateRequest $request 요청
* @return JsonResponse 결과 (succeeded/failed 분리)
@@ -252,7 +252,7 @@ class ModuleController extends AdminBaseController
if ($result['success']) {
$moduleInfo = $result['module_info'] ?? null;
// PO #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함 (PO #8: 빈 배열이면 모달 표시 안 함)
// 요구사항 #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함 (요구사항 #8: 빈 배열이면 모달 표시 안 함)
$pendingLanguagePacks = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class)
->getPendingForReactivation('module', $moduleName);
@@ -241,7 +241,7 @@ class PluginController extends AdminBaseController
if ($result['success']) {
$pluginInfo = $result['plugin_info'] ?? null;
// PO #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함
// 요구사항 #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함
$pendingLanguagePacks = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class)
->getPendingForReactivation('plugin', $pluginName);
@@ -214,7 +214,7 @@ class TemplateController extends AdminBaseController
if ($result['success']) {
$templateInfo = $result['template_info'] ?? null;
// PO #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함
// 요구사항 #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함
$pendingLanguagePacks = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class)
->getPendingForReactivation('template', $templateName);
@@ -57,6 +57,11 @@ class IdentityVerificationController extends PublicBaseController
return $this->error('identity.errors.missing_target', 422);
}
$providerId = $validated['provider_id'] ?? null;
if (is_string($providerId) && $providerId === '') {
$providerId = null;
}
$challenge = $this->service->start(
purpose: (string) $validated['purpose'],
target: $target,
@@ -66,6 +71,7 @@ class IdentityVerificationController extends PublicBaseController
'origin_type' => \App\Enums\IdentityOriginType::Api->value,
'origin_identifier' => '/api/identity/challenges',
],
providerId: $providerId,
);
return $this->success(
@@ -2,12 +2,13 @@
namespace App\Http\Requests\LanguagePack;
use App\Extension\HookManager;
use App\Models\LanguagePack;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/**
* 언어팩 일괄 활성화 요청 (PO #7 reactivate 모달 → "활성화" 버튼).
* 언어팩 일괄 활성화 요청 (요구사항 #7 reactivate 모달 → "활성화" 버튼).
*
* 호스트 확장 재활성화 시 cascade 비활성화됐던 언어팩 ID 배열을 받아
* Service 의 bulkActivate() 로 위임합니다.
@@ -31,9 +32,12 @@ class BulkActivateRequest extends FormRequest
*/
public function rules(): array
{
return [
$rules = [
'ids' => ['required', 'array', 'min:1'],
'ids.*' => ['required', 'integer', Rule::exists(LanguagePack::class, 'id')],
];
// 모듈/플러그인이 validation rules를 동적으로 추가할 수 있도록 훅 제공
return HookManager::applyFilters('core.language_packs.bulk_activate_validation_rules', $rules, $this);
}
}
@@ -24,9 +24,9 @@ class PolicyCollection extends BaseApiCollection
protected function abilityMap(): array
{
return [
'can_create' => 'core.admin.identity.policies.manage',
'can_update' => 'core.admin.identity.policies.manage',
'can_delete' => 'core.admin.identity.policies.manage',
'can_create' => 'core.admin.identity.policies.update',
'can_update' => 'core.admin.identity.policies.update',
'can_delete' => 'core.admin.identity.policies.update',
];
}
@@ -20,8 +20,8 @@ class PolicyResource extends BaseApiResource
public function abilityMap(): array
{
return [
'can_update' => 'core.admin.identity.policies.manage',
'can_delete' => 'core.admin.identity.policies.manage',
'can_update' => 'core.admin.identity.policies.update',
'can_delete' => 'core.admin.identity.policies.update',
];
}
@@ -49,8 +49,7 @@ class PolicyResource extends BaseApiResource
'applies_to' => $this->applies_to,
'fail_mode' => $this->fail_mode,
'user_overrides' => $this->user_overrides ?? [],
'created_at' => $this->created_at?->toIso8601String(),
'updated_at' => $this->updated_at?->toIso8601String(),
...$this->formatTimestamps(),
...$this->resourceMeta($request),
];
}
@@ -14,6 +14,21 @@ use Illuminate\Http\Request;
*/
class ProviderResource extends BaseApiResource
{
/**
* Resource 수준 abilities 매핑.
*
* 프로바이더는 관리자 UI 의 S1c 서브섹션에서 설정값을 편집할 수 있으며,
* 편집 권한은 `core.admin.identity.providers.update` 로 분리되어 있다.
*
* @return array<string, string>
*/
public function abilityMap(): array
{
return [
'can_update' => 'core.admin.identity.providers.update',
];
}
/**
* 리소스를 배열로 변환합니다.
*
@@ -76,6 +76,7 @@ class InitiateIdentityChallengeAfterRegister implements HookListenerInterface
'origin_identifier' => 'core.auth.after_register',
'origin_policy_key' => $policy->key,
],
providerId: $policy->provider_id,
);
} catch (\Throwable $e) {
Log::warning('[IDV] signup_after_create challenge 발행 실패', [
+7
View File
@@ -32,6 +32,9 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string|null $license
* @property array<string, string>|null $description
* @property string $status
* @property string|null $deactivated_reason
* @property \Illuminate\Support\Carbon|null $deactivated_at
* @property string|null $incompatible_required_version
* @property bool $is_protected
* @property array<string, mixed> $manifest
* @property string|null $source_type
@@ -86,6 +89,9 @@ class LanguagePack extends Model
'license',
'description',
'status',
'deactivated_reason',
'deactivated_at',
'incompatible_required_version',
'is_protected',
'manifest',
'source_type',
@@ -109,6 +115,7 @@ class LanguagePack extends Model
'target_version_mismatch' => 'boolean',
'installed_at' => 'datetime',
'activated_at' => 'datetime',
'deactivated_at' => 'datetime',
];
}
@@ -338,7 +338,7 @@ class LanguagePackServiceProvider extends ServiceProvider
$registrar->cleanupForExtension('template', (string) $identifier);
});
// PO #6: 호스트 확장 비활성화 시 종속 언어팩 cascade 비활성화
// 요구사항 #6: 호스트 확장 비활성화 시 종속 언어팩 cascade 비활성화
HookManager::addAction('core.modules.after_deactivate', function ($identifier) use ($registrar) {
$registrar->deactivateForExtension('module', (string) $identifier);
});
@@ -120,6 +120,17 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
return $model ? (bool) $model->delete() : false;
}
/**
* 정책 모델을 영속화합니다 (Eloquent save 위임).
*
* @param IdentityPolicy $policy 영속화할 모델
* @return bool 저장 성공 여부
*/
public function save(IdentityPolicy $policy): bool
{
return (bool) $policy->save();
}
/**
* 특정 소스의 정책 개수를 반환합니다.
*
+2 -2
View File
@@ -283,7 +283,7 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
$pack->license = $manifest['license'] ?? null;
$pack->description = is_array($manifest['description'] ?? null) ? $manifest['description'] : null;
$pack->status = \App\Enums\LanguagePackStatus::Uninstalled->value;
$pack->is_protected = false; // lang-packs/_bundled/ 패키지는 사용자가 install/uninstall 자유 (PO #3)
$pack->is_protected = false; // lang-packs/_bundled/ 패키지는 사용자가 install/uninstall 자유 (요구사항 #3)
$pack->manifest = $manifest;
$pack->source_type = \App\Enums\LanguagePackSourceType::Bundled->value;
$pack->source_url = $bundledIdentifier;
@@ -298,7 +298,7 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
* 코어/번들 확장의 lang/{ko,en}/ 디렉토리로부터 가상 보호 LanguagePack 인스턴스를 합성합니다.
*
* `built_in` 가상 행은 DB 행이 없는 상태로 항상 active+protected 표시되며, 사용자가
* install/uninstall/activate/deactivate 할 수 없습니다 (PO #1, #2).
* install/uninstall/activate/deactivate 할 수 없습니다 (요구사항 #1, #2).
*
* @param string $scope 스코프 (core/module/plugin/template)
* @param string|null $targetIdentifier 대상 확장 식별자 (core 일 때 null)
+69 -3
View File
@@ -6,6 +6,7 @@ use App\Contracts\Extension\UpgradeStepInterface;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Exceptions\CoreUpdateOperationException;
use App\Exceptions\UpgradeHandoffException;
use App\Extension\CoreVersionChecker;
use App\Extension\Helpers\ChangelogParser;
use App\Extension\Helpers\CoreBackupHelper;
@@ -15,6 +16,7 @@ use App\Extension\Helpers\ExtensionRoleSyncHelper;
use App\Extension\Helpers\FilePermissionHelper;
use App\Extension\Helpers\GithubHelper;
use App\Extension\UpgradeContext;
use App\Extension\Vendor\EnvironmentDetector;
use App\Extension\Vendor\VendorInstallContext;
use App\Extension\Vendor\VendorInstallResult;
use App\Extension\Vendor\VendorMode;
@@ -976,7 +978,11 @@ class CoreUpdateService
$onProgress?->__invoke('apply', $name.' (auto)');
if (File::isDirectory($absPath)) {
FilePermissionHelper::copyDirectory($absPath, $dest, $onProgress, $excludes, removeOrphans: true);
// 자동 발견 폴백은 destination orphan 정리 책임이 없다.
// 부모 프로세스의 stale targets 누락을 메우는 안전망이므로,
// base 의 활성 서브디렉토리(예: templates/sirsoft-basic) 가 source 에 없다고
// 해서 삭제하면 사용자 데이터 영구 손실 위험. orphan 처리는 정상 targets 분기만 수행.
FilePermissionHelper::copyDirectory($absPath, $dest, $onProgress, $excludes, removeOrphans: false);
} else {
File::ensureDirectoryExists(dirname($dest));
FilePermissionHelper::copyFile($absPath, $dest);
@@ -993,7 +999,12 @@ class CoreUpdateService
}
/**
* 정규화된 path 가 이미 처리된 상위 path 의 하위 항목인지 검사합니다.
* 정규화된 path 가 이미 처리된 상위/하위 path 와 관계가 있는지 검사합니다.
*
* 양방향 검사:
* - 방향 1 — path 가 applied 의 자식: applied=['templates'], path='templates/sub' (자식 중복 복사 방지)
* - 방향 2 — path 가 applied 의 부모: applied=['templates/_bundled'], path='templates'
* (부모 통째로 복사 시 활성 서브디렉토리 orphan 판정 회피)
*
* @param array<string, bool> $applied
*/
@@ -1008,6 +1019,13 @@ class CoreUpdateService
}
}
$prefix = $path.'/';
foreach ($applied as $appliedPath => $_) {
if (str_starts_with((string) $appliedPath, $prefix)) {
return true;
}
}
return false;
}
@@ -1207,7 +1225,7 @@ class CoreUpdateService
2 => ['pipe', 'w'],
];
$process = proc_open($command, $descriptors, $pipes, $workingDir);
$process = proc_open($command, $descriptors, $pipes, $workingDir, EnvironmentDetector::buildComposerEnv());
if (! is_resource($process)) {
throw new CoreUpdateOperationException('settings.core_update.composer_failed');
@@ -1536,6 +1554,39 @@ class CoreUpdateService
*/
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null, bool $force = false): void
{
// 부모 in-process fallback 진입 시 stale 메모리 가드.
//
// 현재 메모리의 `config('app.version')` 이 toVersion 보다 낮으면 부모는 stale 코드를
// 보유한 채 step 을 실행 중. upgrade step 안에서 신규 메서드 호출 시 fatal 위험
// (이슈 #28 의 발현 메커니즘). `spawn_failure_mode` 와 연동하여 abort/fallback 분기.
//
// spawn 자식 (ExecuteUpgradeStepsCommand) 의 경우 spawn env 의 APP_VERSION=toVersion
// 이 적용된 채 새 프로세스에서 부팅되므로 memoryVersion === toVersion → 가드 미발동.
$memoryVersion = (string) config('app.version', $fromVersion);
if (version_compare($memoryVersion, $toVersion, '<')) {
$mode = config('app.update.spawn_failure_mode', 'fallback');
$message = sprintf(
'[core-update] runUpgradeSteps 부모 메모리 stale 감지 — memory=%s, target=%s, mode=%s',
$memoryVersion,
$toVersion,
$mode,
);
if ($mode === 'abort') {
throw new UpgradeHandoffException(
afterVersion: $fromVersion,
reason: $message.' — fail-fast 모드. 수동 재개로 진행하세요.',
resumeCommand: sprintf(
'php artisan core:execute-upgrade-steps --from=%s --to=%s --force',
$fromVersion,
$toVersion,
),
);
}
Log::warning($message.' — fallback 모드. upgrade step 안에서 신규 메서드 호출 시 fatal 가능.');
}
$upgradesPath = base_path('upgrades');
if (! File::isDirectory($upgradesPath)) {
@@ -1575,6 +1626,21 @@ class CoreUpdateService
if (class_exists($className)) {
$instance = new $className;
if ($instance instanceof UpgradeStepInterface) {
// 7.0.0-beta.5 부터 신규 업그레이드 스텝은 AbstractUpgradeStep 상속 의무.
// "각 스텝별 동작 100% 동일 보장" invariant 를 위해 카탈로그/변환/핫픽스를
// upgrades/data/{version}/ 의 버전 namespace 아래로 격리하도록 강제한다.
//
// 미상속 시점에 즉시 throw → core:update 전체 중단 → 상위 백업 복원.
// 상세: docs/extension/upgrade-step-guide.md §12
if (version_compare($version, '7.0.0-beta.5', '>=')
&& ! $instance instanceof \App\Extension\AbstractUpgradeStep) {
throw new CoreUpdateOperationException(sprintf(
'Upgrade step %s must extend App\\Extension\\AbstractUpgradeStep '
.'(introduced in 7.0.0-beta.5). See docs/extension/upgrade-step-guide.md §12.',
$version,
));
}
$steps[$version] = $instance;
}
}
+6 -2
View File
@@ -268,7 +268,7 @@ class IdentityPolicyService
// HasUserOverrides trait 의 auto-record 우회 — 이 저장은 운영자 수정이 아니라
// 기본값 복원이므로 trackable 필드가 변경되어도 user_overrides 에 재추가되면 안 됨.
return $this->withUserOverridesBypass(fn () => $policy->save());
return $this->withUserOverridesBypass(fn () => $this->policyRepository->save($policy));
}
/**
@@ -480,6 +480,10 @@ class IdentityPolicyService
* 정책의 provider 가 제공하는 렌더 힌트를 반환합니다.
* provider_id 가 명시되어 있으면 우선 사용, 미명시 시 purpose 기반 fallback.
*
* fallback 분기에서도 정책의 provider_id 를 Manager 의 0번 우선순위로 전달한다.
* 정책에 지정된 provider 가 비활성/언인스톨된 순간 Manager 가 같은 우선순위 체인으로
* 일관 처리하도록 정합화 — IdentityVerificationService::start 와 동일 패턴.
*
* @param IdentityPolicy $policy 대상 정책
* @return string|null Provider 의 렌더 힌트 (UI 분기용) 또는 null
*/
@@ -491,7 +495,7 @@ class IdentityPolicyService
return $this->manager->get($providerId)->getRenderHint();
}
return $this->manager->resolveForPurpose($policy->purpose)->getRenderHint();
return $this->manager->resolveForPurpose($policy->purpose, $providerId)->getRenderHint();
} catch (\Throwable) {
return null;
}
+11 -3
View File
@@ -38,14 +38,22 @@ class IdentityVerificationService
/**
* Challenge 를 시작합니다.
*
* $providerId 가 주어지면 Manager 의 0번째 우선순위로 사용된다 (IdentityVerificationManager::resolveForPurpose).
* 미등록/미지원이면 silent fallback (기존 우선순위 체인 진행).
*
* @param string $purpose signup|password_reset|self_update|sensitive_action|플러그인 등록값
* @param User|array<string, mixed> $target 로그인 사용자(User) 또는 ['email' => '...'] 배열
* @param array<string, mixed> $context origin_type / origin_identifier / origin_policy_key / ip_address / user_agent
* @param string|null $providerId Mode A controller 요청 또는 Mode B 정책의 명시 provider id
* @return VerificationChallenge 발행된 challenge DTO
*/
public function start(string $purpose, User|array $target, array $context = []): VerificationChallenge
{
$provider = $this->manager->resolveForPurpose($purpose);
public function start(
string $purpose,
User|array $target,
array $context = [],
?string $providerId = null,
): VerificationChallenge {
$provider = $this->manager->resolveForPurpose($purpose, $providerId);
$context['purpose'] = $purpose;
@@ -132,7 +132,7 @@ class LanguagePackBundledRegistrar
}
/**
* 호스트 확장 비활성화 시 해당 확장에 종속된 언어팩을 cascade 비활성화합니다 (PO #6).
* 호스트 확장 비활성화 시 해당 확장에 종속된 언어팩을 cascade 비활성화합니다 (요구사항 #6).
*
* 비활성화된 active 팩 ID 목록을 cache 에 stash 하여, 재활성화 시 §6 모달이
* 표시할 후보로 사용됩니다.
@@ -191,10 +191,10 @@ class LanguagePackBundledRegistrar
}
/**
* 호스트 확장 재활성화 시 모달에 표시할 pending 언어팩 목록을 반환합니다 (PO #7).
* 호스트 확장 재활성화 시 모달에 표시할 pending 언어팩 목록을 반환합니다 (요구사항 #7).
*
* stash 된 ID 중 현재도 DB 에 존재하고 inactive 상태인 팩만 필터링합니다.
* 빈 배열을 반환하면 프론트엔드는 모달을 띄우지 않습니다 (PO #8).
* 빈 배열을 반환하면 프론트엔드는 모달을 띄우지 않습니다 (요구사항 #8).
*
* @param string $scope 스코프
* @param string $targetIdentifier 대상 확장 식별자
+8 -8
View File
@@ -165,7 +165,7 @@ class LanguagePackService
/**
* 코어/번들 확장의 `lang/{ko,en}/` 디렉토리를 자동 스캔하여 가상 보호 LanguagePack
* 인스턴스 컬렉션을 반환합니다 (PO #1, #2).
* 인스턴스 컬렉션을 반환합니다 (요구사항 #1, #2).
*
* 스캔 대상:
* - 코어: lang/{ko,en}/
@@ -351,7 +351,7 @@ class LanguagePackService
return false;
}
if (array_key_exists('target_identifier', $filters) && $filters['target_identifier'] !== null) {
// 개별 확장 언어팩 관리 화면 — 그 확장에 해당되는 행만 노출 (PO 정정).
// 개별 확장 언어팩 관리 화면 — 그 확장에 해당되는 행만 노출 (정정 사항).
// 코어 보호 팩은 환경설정 > 언어팩 관리(필터 없음) 화면에서만 노출됨.
if ($pack->target_identifier !== $filters['target_identifier']) {
return false;
@@ -848,7 +848,7 @@ class LanguagePackService
return $pack;
}
// PO #5: activate 시점에도 의존성/버전 호환성 검사 (이전: install 시점만)
// 요구사항 #5: activate 시점에도 의존성/버전 호환성 검사 (이전: install 시점만)
$this->assertDependencies($pack->manifest ?? []);
$this->assertTargetExtensionExists($pack->manifest ?? []);
@@ -884,7 +884,7 @@ class LanguagePackService
}
/**
* 여러 언어팩을 일괄 활성화합니다 (PO #7 reactivate 모달 → "활성화" 버튼).
* 여러 언어팩을 일괄 활성화합니다 (요구사항 #7 reactivate 모달 → "활성화" 버튼).
*
* 각 ID 에 대해 activate() 를 호출하며, 실패한 항목은 reason 과 함께 응답에 포함합니다.
* 의존성 검사는 activate() 내부에서 자동 수행됩니다 (§4).
@@ -931,7 +931,7 @@ class LanguagePackService
return $pack;
}
// PO #6: 호스트 확장 cascade 컨텍스트에서는 protected 가드 우회
// 요구사항 #6: 호스트 확장 cascade 컨텍스트에서는 protected 가드 우회
if ($pack->isProtected() && ! $cascadeFromHost) {
throw new LanguagePackOperationException('language_packs.errors.protected_pack');
}
@@ -1322,7 +1322,7 @@ class LanguagePackService
*/
public function checkUpdates(?string $identifier = null): array
{
// PO #4: 모듈 패턴 — 모든 source_type 점검 (GitHub 1순위, 실패 시 bundled 폴백)
// 요구사항 #4: 모듈 패턴 — 모든 source_type 점검 (GitHub 1순위, 실패 시 bundled 폴백)
$packs = $identifier
? collect([$this->repository->findByIdentifier($identifier)])->filter()
: $this->repository->paginate([], 1000)->getCollection();
@@ -1435,7 +1435,7 @@ class LanguagePackService
}
/**
* 번들 manifest 로부터 최신 버전을 조회합니다 (PO #4 폴백 경로).
* 번들 manifest 로부터 최신 버전을 조회합니다 (요구사항 #4 폴백 경로).
*
* @param LanguagePack $pack 대상 언어팩
* @return string|null 최신 버전 문자열 또는 null
@@ -1538,7 +1538,7 @@ class LanguagePackService
*/
public function performUpdate(LanguagePack $pack, bool $force = false): LanguagePack
{
// PO #4: bundled 도 update 가능. force=true 시 bundled 1순위, 그 외 GitHub 1순위 + bundled 폴백
// 요구사항 #4: bundled 도 update 가능. force=true 시 bundled 1순위, 그 외 GitHub 1순위 + bundled 폴백
$githubUrl = $this->resolveGithubUrl($pack);
if (! $githubUrl && ! $this->hasBundledManifest($pack->identifier)) {
throw new LanguagePackOperationException('language_packs.errors.update_no_source');