https://github.com/gnuboard/g7/issues/128 (제보자 glitter-gim) 과 그 부수의무 전수조사에서 확정한 결함군을 닫는다. ## 디버그 라우트 게이트 (F1~F5) 게이트가 핸들러 안에 흩어져 있어 8개 라우트 중 3개에만 붙어 있었다. 빠진 쪽에 `File::cleanDirectory(storage/debug-dump)` 를 수행하는 `DELETE clear` 가 있었고, production·APP_DEBUG=false 에서도 미인증 200 으로 덤프 전체가 지워졌다. GET 4종은 User SPA catch-all 이 등록 순서상 앞서 가려 주고 있었을 뿐이라, 보호를 우연에 맡긴 구조였다. 게이트를 `bootstrap/app.php` 의 devtools 래퍼 한 곳(`debug.gate` 그룹 미들웨어)으로 올린다. 새 라우트는 자동으로 덮이고, 부착 지점이 하나라 훼손이 곧바로 드러난다. `withRouting(channels:)` 인자가 함께 등록하던 게이트 없는 `/broadcasting/auth` 는 제거하고, 채널 정의 로드만 `BroadcastServiceProvider` 로 옮겨 웹소켓 킬스위치 우회로를 없앤다. catch-all 제외 패턴에는 예약 프리픽스를 전수 추가했다. ## 확장 자산 CSS 상대 참조 (범위 추가 — 결정) `asset_url_mode=extensionless` 에서 자산 URL 이 쿼리 형태가 되면 브라우저의 기준 디렉토리가 `/api/{타입}/assets/` 로 잡혀, CSS 안의 `url('./woff2/f.woff2')` 가 존재하지 않는 주소가 된다. 사용자 템플릿 웹폰트 1건과 관리자 템플릿 국기 아이콘 약 500건이 이 상태였다. 병합 CSS 번들은 더 나빴다 — 상대 참조를 가진 확장을 번들에서 통째로 제외하고 있었는데, 번들 URL 이 내려오면 프론트는 개별 로딩을 아예 타지 않으므로 제외는 곧 그 확장 스타일이 하나도 적용되지 않음을 뜻했다. 둘 다 서빙 시점에 절대 자산 URL 로 치환한다. 최종 URL 은 런타임 모드와 캐시 버전이 정하므로 빌드 시점에는 알 수 없고, 동봉 자산은 제3자 산출물이라 원본을 손대면 상류 갱신마다 재작업이 된다. 개별 서빙 3경로와 병합 번들이 같은 해석 규칙을 공유한다 — 갈라지면 한쪽만 고쳐진 채 남는다. 이 결함군은 공통적으로 예외도 서버 로그 흔적도 남기지 않는다. 열린 엔드포인트가 정상 응답하는 것, 404 로 글꼴이 기본 서체가 되는 것이 유일한 증상이다. ## 회귀 잠금 되돌림 red 를 모집단 전원에 대해 실측했다 — 그룹 미들웨어 제거, 개별 게이트 재주입, `channels:` 복원, catch-all 예외 제거, 컨트롤러 3원의 `fileResponse` 회귀, 번들 치환 제거가 각각 어느 테스트를 red 로 만드는지 확인하고 원상 복구했다. 게이트 부착 축은 행위 테스트로 대체할 수 없다 — 가려진 라우트는 행위상 "막힌 것" 과 구분되지 않으므로, `gatherMiddleware` 를 직접 보는 등록 계약 테스트를 둔다. 치환 배선도 같은 이유로 라우트 이름 규약에서 모집단을 도출하는 계약 검사를 둔다(손으로 적은 목록은 네 번째 경로가 생기는 순간 조용히 낡는다).
391 lines
17 KiB
PHP
391 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\Public;
|
|
|
|
use App\Contracts\Extension\CacheInterface;
|
|
use App\Enums\ExtensionStatus;
|
|
use App\Extension\Helpers\EditorSpecAssembler;
|
|
use App\Extension\Traits\ClearsTemplateCaches;
|
|
use App\Http\Controllers\Api\Base\PublicBaseController;
|
|
use App\Http\Controllers\Concerns\ServesRewritableCssAssets;
|
|
use App\Http\Requests\Public\Template\ServeTemplateAssetRequest;
|
|
use App\Models\TemplateLayoutAttachment;
|
|
use App\Services\TemplateLayoutAttachmentService;
|
|
use App\Services\TemplateService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
/**
|
|
* 공개 템플릿 API 컨트롤러
|
|
*/
|
|
class PublicTemplateController extends PublicBaseController
|
|
{
|
|
use ClearsTemplateCaches;
|
|
use ServesRewritableCssAssets;
|
|
|
|
public function __construct(
|
|
private TemplateService $templateService,
|
|
private TemplateLayoutAttachmentService $layoutAttachmentService,
|
|
) {
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* 템플릿 라우트 정보 조회 (활성화된 모듈의 routes 포함)
|
|
*
|
|
* @param string $identifier 템플릿 식별자 (vendor-name 형식)
|
|
* @return JsonResponse|Response 라우트 정보 응답 (`?v` 명시 + If-None-Match 일치 시 304)
|
|
*/
|
|
public function getRoutes(string $identifier): JsonResponse|Response
|
|
{
|
|
// API 사용량 기록
|
|
$this->logApiUsage('templates.routes', ['identifier' => $identifier]);
|
|
|
|
// 캐시 버전을 키에 포함하여 모듈/플러그인 변경 시 캐시 무효화.
|
|
// `?v` 생략 시 현재 버전으로 폴백 — 리터럴 0 폴백은 워밍/무효화 어느 경로에도
|
|
// 걸리지 않는 `.v0` 영구 사각 키를 만든다 (#588). `(int)` 캐스트로 키 위생 겸용.
|
|
$rawVersion = request()->query('v');
|
|
$cacheVersion = $rawVersion !== null ? (int) $rawVersion : self::getExtensionCacheVersion();
|
|
|
|
// 확장 업데이트 중에는 활성 디렉토리가 잠시 비어 그 모듈의 라우트가 통째로 빠진다.
|
|
// 그 순간의 응답을 버전 키에 캐시하면 업데이트가 끝난 뒤에도 캐시가 만료될 때까지
|
|
// 해당 모듈의 모든 화면이 404 로 남는다 — 버전은 이미 올라간 뒤라 스스로 회복되지 않는다.
|
|
// 따라서 열화 스냅샷은 그대로 응답하되 캐시에 남기지 않는다.
|
|
$buildRoutes = function () use ($identifier) {
|
|
$result = $this->templateService->getRoutesDataWithModules($identifier);
|
|
|
|
if (! $result['success']) {
|
|
return ['error' => $result['error']];
|
|
}
|
|
|
|
return ['success' => true, 'data' => $result['data']];
|
|
};
|
|
|
|
$cacheKey = "template.routes.{$identifier}.v{$cacheVersion}";
|
|
$cache = app(CacheInterface::class);
|
|
$routesData = $cache->get($cacheKey);
|
|
|
|
if ($routesData === null) {
|
|
$routesData = $buildRoutes();
|
|
|
|
if ($this->templateService->lastRouteMergeWasDegraded()) {
|
|
Log::warning('라우트 병합이 열화 상태여서 캐시하지 않습니다 (확장 업데이트 진행 중 추정)', [
|
|
'template' => $identifier,
|
|
'cache_version' => $cacheVersion,
|
|
]);
|
|
} else {
|
|
$cache->put($cacheKey, $routesData, 3600);
|
|
}
|
|
}
|
|
|
|
// 에러 응답 처리
|
|
if (isset($routesData['error'])) {
|
|
return match ($routesData['error']) {
|
|
'template_not_found' => $this->notFound(
|
|
__('templates.errors.not_found', ['template' => $identifier])
|
|
),
|
|
'routes_not_found' => $this->notFound(
|
|
__('templates.errors.routes_not_found')
|
|
),
|
|
'invalid_json' => $this->error(
|
|
__('templates.errors.invalid_json'),
|
|
500
|
|
),
|
|
default => $this->error(__('templates.errors.unknown_error'), 500),
|
|
};
|
|
}
|
|
|
|
// data 키 누락 시 기본 구조 반환 (캐시 오류 방어)
|
|
if (! isset($routesData['data'])) {
|
|
return $this->error(__('templates.errors.invalid_cache_data'), 500);
|
|
}
|
|
|
|
// 버전 키드 URL(`?v` 명시)은 bump 시 URL 자체가 바뀌므로 조건부 공개 캐시가 안전하다.
|
|
// 무버전 요청(핸드셰이크 폴백 등)은 종전대로 캐시 헤더 없이 신선 응답 (#122 작업 D).
|
|
// 열화 스냅샷은 공개 캐시 금지 — 서버측 캐시 회피(#493)와 동일 규율로, 같은 `?v`
|
|
// URL 에 public max-age 가 붙으면 브라우저/CDN 이 열화 응답을 1시간 박제한다
|
|
// (버전은 이미 올라간 뒤라 스스로 회복되지 않음. 정적 게시의 열화 제외와 대칭).
|
|
if ($rawVersion !== null && ! $this->templateService->lastRouteMergeWasDegraded()) {
|
|
return $this->successWithCache('templates.messages.routes_retrieved', $routesData['data'], 3600);
|
|
}
|
|
|
|
return $this->success(
|
|
__('templates.messages.routes_retrieved'),
|
|
$routesData['data']
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 템플릿 정적 파일 서빙
|
|
*
|
|
* @param ServeTemplateAssetRequest $request 요청 (FormRequest 검증, 파일 경로 `path` 포함)
|
|
* @param string $identifier 템플릿 식별자
|
|
* @return BinaryFileResponse|JsonResponse|Response 파일 응답 또는 에러
|
|
*/
|
|
public function serveAsset(ServeTemplateAssetRequest $request, string $identifier): BinaryFileResponse|JsonResponse|Response
|
|
{
|
|
// 파일 경로는 FormRequest 에서 받는다 — 확장자 모드는 `{path}` 라우트 세그먼트,
|
|
// 확장자 없는 모드는 `?file=` 쿼리로 오며 prepareForValidation() 이 이를 흡수한다.
|
|
$path = (string) $request->validated('path');
|
|
|
|
// FormRequest에서 이미 보안 검증 완료
|
|
// API 사용량 기록
|
|
$this->logApiUsage('templates.assets', ['identifier' => $identifier, 'path' => $path]);
|
|
|
|
// Service에서 파일 경로 조회 (검증은 FormRequest에서 완료됨)
|
|
$result = $this->templateService->getAssetFilePath($identifier, $path);
|
|
|
|
// 에러 처리
|
|
if (! $result['success']) {
|
|
return match ($result['error']) {
|
|
'template_not_found' => $this->notFound(__('templates.errors.not_found', ['template' => $identifier])),
|
|
'file_not_found' => $this->notFound(__('templates.errors.file_not_found')),
|
|
'file_type_not_allowed' => $this->forbidden(__('templates.errors.file_type_not_allowed')),
|
|
default => $this->error(__('templates.errors.unknown_error'), 500),
|
|
};
|
|
}
|
|
|
|
// 파일 반환 (ETag 및 환경별 캐싱 헤더 포함).
|
|
// CSS 는 안의 상대 참조를 절대 자산 URL 로 치환해 내보낸다 — 확장자 없는 모드에서
|
|
// 상대 해석이 어긋나 글꼴·아이콘이 404 가 되기 때문이다.
|
|
return $this->rewritableAssetResponse(
|
|
$result['filePath'],
|
|
$result['mimeType'],
|
|
'templates',
|
|
$identifier,
|
|
$path,
|
|
31536000
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 컴포넌트 정의 파일 서빙
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @return JsonResponse|Response 컴포넌트 정의 응답 (If-None-Match 일치 시 304)
|
|
*/
|
|
public function serveComponents(string $identifier): JsonResponse|Response
|
|
{
|
|
// API 사용량 기록
|
|
$this->logApiUsage('templates.components', ['identifier' => $identifier]);
|
|
|
|
// Service에서 파일 경로 조회 및 검증
|
|
$result = $this->templateService->getComponentsFilePath($identifier);
|
|
|
|
// 에러 처리
|
|
if (! $result['success']) {
|
|
return match ($result['error']) {
|
|
'template_not_found' => $this->notFound(__('templates.errors.not_found', ['template' => $identifier])),
|
|
'components_not_found' => $this->notFound(__('templates.errors.components_not_found')),
|
|
default => $this->error(__('templates.errors.unknown_error'), 500),
|
|
};
|
|
}
|
|
|
|
// JSON 파싱 및 반환
|
|
$components = json_decode(file_get_contents($result['componentsPath']), true);
|
|
|
|
return $this->cachedJsonResponse($components, 3600);
|
|
}
|
|
|
|
/**
|
|
* 템플릿 설정 파일 서빙 (template.json)
|
|
*
|
|
* error_config 등 템플릿 메타데이터를 프론트엔드에 제공합니다.
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @return JsonResponse 템플릿 설정 응답
|
|
*/
|
|
public function serveConfig(string $identifier): JsonResponse
|
|
{
|
|
// API 사용량 기록
|
|
$this->logApiUsage('templates.config', ['identifier' => $identifier]);
|
|
|
|
// 캐싱된 응답 반환 (1시간 유효)
|
|
$configData = $this->cached(
|
|
"template.config.{$identifier}",
|
|
function () use ($identifier) {
|
|
// 템플릿 존재 확인
|
|
$template = $this->templateService->findByIdentifier($identifier);
|
|
if (! $template || $template->status !== ExtensionStatus::Active->value) {
|
|
return ['error' => 'template_not_found'];
|
|
}
|
|
|
|
// template.json 파일 경로
|
|
$configPath = base_path("templates/{$identifier}/template.json");
|
|
|
|
if (! file_exists($configPath)) {
|
|
return ['error' => 'config_not_found'];
|
|
}
|
|
|
|
$content = file_get_contents($configPath);
|
|
$data = json_decode($content, true);
|
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
return ['error' => 'invalid_json'];
|
|
}
|
|
|
|
return ['success' => true, 'data' => $data];
|
|
},
|
|
3600
|
|
);
|
|
|
|
// 에러 응답 처리
|
|
if (isset($configData['error'])) {
|
|
return match ($configData['error']) {
|
|
'template_not_found' => $this->notFound(
|
|
__('templates.errors.not_found', ['template' => $identifier])
|
|
),
|
|
'config_not_found' => $this->notFound(
|
|
__('templates.errors.template_json_not_found')
|
|
),
|
|
'invalid_json' => $this->error(
|
|
__('templates.errors.invalid_json'),
|
|
500
|
|
),
|
|
default => $this->error(__('templates.errors.unknown_error'), 500),
|
|
};
|
|
}
|
|
|
|
// 캐시 버전을 응답에 포함하여 프론트엔드가 API 호출 시 사용하도록 함
|
|
$responseData = $configData['data'];
|
|
$responseData['cache_version'] = self::getExtensionCacheVersion();
|
|
|
|
return $this->success(
|
|
__('templates.messages.config_retrieved'),
|
|
$responseData
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 템플릿 다국어 파일 서빙 (활성화된 모듈의 다국어 데이터 포함)
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @param string $locale 로케일 (ko, en 등)
|
|
* @return JsonResponse|Response 다국어 데이터 응답 (If-None-Match 일치 시 304)
|
|
*/
|
|
public function serveLanguage(string $identifier, string $locale): JsonResponse|Response
|
|
{
|
|
// API 사용량 기록
|
|
$this->logApiUsage('templates.language', [
|
|
'identifier' => $identifier,
|
|
'locale' => $locale,
|
|
]);
|
|
|
|
// 캐시 버전을 키에 포함하여 모듈/플러그인 변경 시 캐시 무효화.
|
|
// `?v` 생략 시 현재 버전으로 폴백 (getRoutes 와 동일 — `.v0` 사각 키 방지)
|
|
$rawVersion = request()->query('v');
|
|
$cacheVersion = $rawVersion !== null ? (int) $rawVersion : self::getExtensionCacheVersion();
|
|
|
|
// 캐싱된 응답 반환 (1시간 유효)
|
|
$languageData = $this->cached(
|
|
"template.language.{$identifier}.{$locale}.v{$cacheVersion}",
|
|
function () use ($identifier, $locale) {
|
|
// Service에서 템플릿 + 모듈 다국어 데이터 병합 조회
|
|
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
|
|
|
// 에러 처리
|
|
if (! $result['success']) {
|
|
return ['error' => $result['error']];
|
|
}
|
|
|
|
return ['success' => true, 'data' => $result['data']];
|
|
},
|
|
3600
|
|
);
|
|
|
|
// 에러 응답 처리
|
|
if (isset($languageData['error'])) {
|
|
return match ($languageData['error']) {
|
|
'template_not_found' => $this->notFound(
|
|
__('templates.errors.not_found', ['template' => $identifier])
|
|
),
|
|
'locale_not_supported' => $this->notFound(
|
|
__('templates.errors.locale_not_supported', [
|
|
'template' => $identifier,
|
|
'locale' => $locale,
|
|
])
|
|
),
|
|
'file_not_found' => $this->notFound(
|
|
__('templates.errors.language_file_not_found', ['locale' => $locale])
|
|
),
|
|
'invalid_json' => $this->error(
|
|
__('templates.errors.invalid_json'),
|
|
500
|
|
),
|
|
default => $this->error(__('templates.errors.unknown_error'), 500),
|
|
};
|
|
}
|
|
|
|
// 성공 응답 (JSON 데이터 직접 반환, 래핑 없음)
|
|
return $this->cachedJsonResponse($languageData['data'], 3600);
|
|
}
|
|
|
|
/**
|
|
* 편집기 스펙 조회 — 템플릿 editor-spec.json 파일 반환
|
|
*
|
|
* Phase 3 S5a-1 에서 `nesting` 블록이 추가되었다. 본 엔드포인트는
|
|
* 활성 디렉토리 → _bundled 폴백 순으로 editor-spec.json 을 읽어 반환한다.
|
|
* 파일 미존재 시 spec=null 로 폴백 (편집기는 spec 미제공 안내).
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @return JsonResponse 편집기 스펙 응답
|
|
*/
|
|
public function serveEditorSpec(string $identifier): JsonResponse
|
|
{
|
|
$this->logApiUsage('templates.editor_spec', ['identifier' => $identifier]);
|
|
|
|
// 분할 editor-spec.json 은 manifest + `$include` 블록으로 구성된다.
|
|
// 활성 디렉토리만 기준으로 합본한 단일 spec 을 반환한다(_bundled 폴백 없음).
|
|
// 합본 결과는 분할 전 단일 파일과 동일 형태(프론트엔드 로더 무영향).
|
|
// 미분할 파일은 원본 반환(하위 호환), 미존재 시 null.
|
|
$spec = EditorSpecAssembler::assemble(
|
|
base_path("templates/{$identifier}/editor-spec.json")
|
|
);
|
|
|
|
$message = $spec === null
|
|
? __('templates.messages.editor_spec_empty')
|
|
: __('templates.messages.editor_spec_retrieved');
|
|
|
|
return $this->success(
|
|
$message,
|
|
[
|
|
'identifier' => $identifier,
|
|
'spec' => $spec,
|
|
]
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 레이아웃 첨부 이미지 파일 서빙.
|
|
*
|
|
* 발행된 배경 이미지는 일반 사이트 방문자에게도 로드되어야 하므로 인증 불필요한
|
|
* 공개 엔드포인트로 둔다. 첨부는 비공개 `attachments` 디스크에 저장되므로 직접
|
|
* 공개 URL 이 없어, 본 라우트가 파일을 캐싱 헤더와 함께 인라인 스트림한다.
|
|
* 첨부가 경로의 템플릿 소속이 아니거나 파일이 없으면 404.
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @param TemplateLayoutAttachment $attachment 라우트 모델 바인딩된 첨부
|
|
* @return StreamedResponse|Response|JsonResponse 파일 응답 또는 404
|
|
*/
|
|
public function serveFile(string $identifier, TemplateLayoutAttachment $attachment): StreamedResponse|Response|JsonResponse
|
|
{
|
|
$serveInfo = $this->layoutAttachmentService->getServableResponse($identifier, $attachment);
|
|
|
|
if ($serveInfo === null) {
|
|
return $this->notFound('templates.layout_attachments.errors.not_found');
|
|
}
|
|
|
|
// 이미지/일반 파일 모두 캐싱 헤더와 함께 인라인 응답 (레이아웃 캐시 TTL, 기본 24시간).
|
|
// PublicAttachmentController 의 이미지 서빙과 동일한 streamedFileResponse(ETag/Cache-Control) 사용
|
|
// — 행 disk 를 따르는 스토리지 스트림이라 S3 등 원격 디스크 행에서도 성립한다 (#99).
|
|
return $this->streamedFileResponse(
|
|
$serveInfo['response'],
|
|
$serveInfo['etag_source'],
|
|
(int) g7_core_settings('cache.layout_ttl', 86400)
|
|
);
|
|
}
|
|
}
|