Files
Gnuboard7/app/Providers/AppServiceProvider.php
T
HeuJung 15cd4452bf feat(core): 정적 최적화 서버 대응 자산 URL 이중 모드
nginx 의 정규식 location 은 프리픽스 location 보다 먼저 매칭되므로,
`location ~* \.(js|css|json)$` 블록이 있는 서버에서는 확장자 붙은 동적
엔드포인트가 `try_files ... /index.php` 폴백이 실행될 기회 없이 404 가 된다.
aaPanel/CyberPanel/Plesk 기본 템플릿에 들어있어 드물지 않으며, 관리자 화면조차
뜨지 않아 "서버 설정을 고치세요" 안내가 순환 참조가 된다.

관례를 깬 쪽이 G7 이므로 해소 책임도 G7 에 두고, 두 형태를 모두 서빙한 뒤
환경에 따라 택일한다. 확장자 형태는 영구 유지한다 — 제거하면 URL 을 하드코딩한
서드파티 확장이 깨진다.

- 라우트: dualSuffix / dualSuffixSegment / dualAsset 매크로로 23개 엔드포인트와
 프로브를 이중 등록. 확장자 형태를 먼저 등록한다 — 확장자 없는 쪽이 더 느슨한
 패턴이라 순서가 뒤집히면 `.json` 요청까지 삼킨다
- URL 생성: 서버 App\Support\AssetUrl, 프론트 core/support/assetUrl.ts 로 집약.
 기본 모드에서 생성 결과는 치환 이전과 문자열까지 동일하다 (쿼리 순서 포함 —
 순서가 바뀌면 의미는 같아도 HTTP 캐시 키가 갈린다)
- 자가 복구: 부트스트랩 자산 로드 실패 시 확장자 없는 형태로 1회 단방향 전환.
 역방향 금지 + 기존 재시도 예산 공유로 무한 왕복을 막는다
- 감지·전환: 인스톨러 프로브(설치 시 확정) / 관리자 환경설정 일반 탭 /
 g7:asset-url-mode. 판정은 상태코드가 아니라 매직 토큰 + Content-Type 으로 한다.
 상태코드만 보면 "404 대신 200 + 에러 HTML" 환경에서 영원히 오판한다
- 봇은 JavaScript 를 실행하지 않아 자가 복구가 닿지 않으므로, 모드 변경 시
 SEO 프리렌더 캐시를 비워 재생성시킨다

가드: audit 룰 2종(dynamic-route-static-extension / asset-url-builder-required),
Playwright 6건(정적 블록 가로채기 시뮬레이션), 루프 방지 불변식 L1~L9 전수 red 증명.

부수 정리: 양 Composer 에 중복돼 있던 확장 에셋 수집 123줄을 트레이트로 통합하고,
자산 확장자 화이트리스트 누락(.map)과 경로 정규화 우회 가능성을 함께 교정.

sir.kr 커뮤니티의 hang 님께서 제보해주셨습니다.
2026-07-23 11:34:32 +09:00

184 lines
6.8 KiB
PHP

<?php
namespace App\Providers;
use App\Contracts\Extension\HookManagerInterface;
use App\Contracts\Extension\ModuleManagerInterface;
use App\Contracts\Extension\PluginManagerInterface;
use App\Contracts\Notifications\ChannelReadinessCheckerInterface;
use App\Extension\HookManager;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Http\View\Composers\TemplateComposer;
use App\Http\View\Composers\UserTemplateComposer;
use App\Listeners\ExtensionCompatibilityAlertListener;
use App\Notifications\NotificationChannelManager;
use App\Services\ChannelReadinessService;
use App\Services\GeoIpService;
use App\Support\Routing\DualExtensionRoute;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;
use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Laravel\Boost\BoostServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// 자산 URL 이중 모드 Route 매크로 (dualSuffix / dualAsset).
// boot() 가 아니라 register() 에서 등록하는 이유: 라우트 파일은 프레임워크의
// 라우팅 부트스트랩(boot 단계)에서 로드되므로, 프로바이더 간 boot 순서에
// 의존하면 매크로 미정의 시점에 라우트가 로드될 수 있다. 모든 프로바이더의
// register() 는 어떤 boot() 보다 먼저 실행되므로 여기가 유일하게 안전한 지점이다.
DualExtensionRoute::register();
// NOTE: Faker 부재 시 FakerShim 대체는 app/Support/SampleData/bootstrap.php 에서 처리
// (composer autoload.files 진입점 — vendor/autoload.php 로드 직후 실행되어
// Laravel 의 fake() 헬퍼 정의 시점에 \Faker\Factory 가 이미 alias 되어 있음)
// 알림 발송 공통 디스패처 — 채널 독립 발송 + 발송 전후 G7 훅 실행
$this->app->singleton(
ChannelManager::class,
fn ($app) => new NotificationChannelManager($app)
);
// 채널 Readiness 검증 — 미설정 채널 발송 사전 차단
$this->app->singleton(
ChannelReadinessCheckerInterface::class,
ChannelReadinessService::class
);
// TODO: TemplateManagerInterface 바인딩을 추가해야 함
// PluginManagerInterface 바인딩
$this->app->bind(
PluginManagerInterface::class,
PluginManager::class
);
// ModuleManagerInterface 바인딩
$this->app->bind(
ModuleManagerInterface::class,
ModuleManager::class
);
// HookManagerInterface 바인딩
$this->app->bind(
HookManagerInterface::class,
HookManager::class
);
// GeoIpService 싱글톤 등록
$this->app->singleton(GeoIpService::class);
// Laravel Boost (개발 전용 - dont-discover 대상, 클래스 존재 시에만 등록)
if (class_exists(BoostServiceProvider::class)) {
$this->app->register(BoostServiceProvider::class);
}
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Schema::defaultStringLength(191);
// View Composer 등록
View::composer('admin', TemplateComposer::class);
View::composer('app', UserTemplateComposer::class);
// 확장 호환성 알림 리스너 등록
$this->registerExtensionCompatibilityAlertListener();
// SQL 쿼리 로그 설정
$this->configureSqlQueryLogging();
// 로그인 라우트 per-IP 백업 throttle — 보안 환경설정의 per-account 잠금과 2중 방어.
// 존재하지 않는 계정에 대한 brute-force / 동일 IP 의 다른 계정 시도까지 차단.
$this->configureLoginRateLimiter();
}
/**
* 로그인 엔드포인트(`/api/auth/login`, `/api/auth/admin/login`) 의 per-IP RateLimiter 를 등록합니다.
*
* 보안 환경설정 `security.max_login_attempts` 에 비례하여 분당 허용량을 산출하되
* 최소 30 회/분 을 보장 (정상 사용자 오타/타이핑 실수에 대비). 설정 조회 실패 시
* 기본값 60 회/분 으로 폴백 — 부팅 안전성 (마이그레이션 전 진입) 확보.
*/
private function configureLoginRateLimiter(): void
{
RateLimiter::for('auth-login', function (Request $request) {
try {
$perAccount = (int) g7_core_settings('security.max_login_attempts', 5);
$maxPerMinute = max(30, $perAccount * 6);
} catch (\Throwable $e) {
$maxPerMinute = 60;
}
return Limit::perMinute($maxPerMinute)->by($request->ip());
});
}
/**
* 확장 호환성 알림 리스너를 등록합니다.
*
* 코어 버전 호환성 문제로 자동 비활성화된 확장에 대한
* 알림을 관리자 대시보드에 표시하기 위한 훅 리스너입니다.
*/
private function registerExtensionCompatibilityAlertListener(): void
{
$listener = new ExtensionCompatibilityAlertListener;
$subscribedHooks = ExtensionCompatibilityAlertListener::getSubscribedHooks();
foreach ($subscribedHooks as $hookName => $config) {
$method = $config['method'] ?? 'handle';
$priority = $config['priority'] ?? 10;
$type = $config['type'] ?? 'action';
if ($type === 'filter') {
HookManager::addFilter($hookName, [$listener, $method], $priority);
} else {
HookManager::addAction($hookName, [$listener, $method], $priority);
}
}
}
/**
* SQL 쿼리 로깅을 설정합니다.
*
* 환경설정에서 sql_query_log가 활성화된 경우
* 모든 SQL 쿼리를 storage/logs/query.log에 기록합니다.
*/
private function configureSqlQueryLogging(): void
{
if (! config('g7.sql_query_log', false)) {
return;
}
DB::listen(function (QueryExecuted $query) {
$sql = $query->sql;
$bindings = $query->bindings;
$time = $query->time;
// 바인딩 값을 SQL에 삽입하여 완전한 쿼리 생성
foreach ($bindings as $binding) {
$value = is_numeric($binding) ? $binding : "'{$binding}'";
$sql = preg_replace('/\?/', (string) $value, $sql, 1);
}
Log::channel('query')->info("Query ({$time}ms): {$sql}");
});
}
}