asset hash 새로고침 추가

This commit is contained in:
seo
2026-07-08 03:27:26 +09:00
parent fb1f4f5ce6
commit 16cdd9ffc9
4 changed files with 180 additions and 1 deletions
+3 -1
View File
@@ -18,6 +18,7 @@ Seoul은 서버에 흩어진 웹 서비스들을 한 화면에서 찾기 위한
## 주요 진입점
- `index.php`: 바로가기 대시보드
- `asset-version.php`: 대시보드 파일 묶음의 현재 hash를 내려주는 JSON 엔드포인트
- `manifest.webmanifest`: PWA manifest
- `sw.js`: service worker
@@ -28,6 +29,8 @@ Seoul은 서버에 흩어진 웹 서비스들을 한 화면에서 찾기 위한
- `sw.js`: 대시보드 캐시와 PWA 동작
- `assets/`: 아이콘과 정적 자산
`asset-version.php``car/`를 제외한 Seoul 대시보드의 PHP/JS/CSS/manifest/icon 파일을 읽어 크기, 수정 시각, sha256 hash를 묶은 버전을 만듭니다. `assets/asset-reload.js`는 열린 화면에서 이 값을 확인하고, 달라지면 Cache Storage를 비운 뒤 현재 화면을 다시 엽니다.
## 입력 소스
- `/etc/nginx/nginx.conf`
@@ -65,4 +68,3 @@ Seoul은 서버에 흩어진 웹 서비스들을 한 화면에서 찾기 위한
- nginx 설정 변경 후 목록에 의도한 서비스만 노출되는지 확인합니다.
- 민감하거나 내부 전용 host가 목록에 나오지 않도록 제외 규칙을 유지합니다.
- Car 서비스 명세는 별도 문서와 저장소에서 관리합니다.
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$service = 'seoul';
$root = __DIR__;
$scanRoots = [
'.' => ['php', 'js', 'css', 'webmanifest', 'svg', 'png', 'ico'],
];
$excludePrefixes = ['car/'];
function collect_asset_files(string $root, array $scanRoots, array $excludePrefixes): array
{
$files = [];
$rootPath = realpath($root);
if (!$rootPath) {
return $files;
}
foreach ($scanRoots as $relativeRoot => $extensions) {
$base = realpath($rootPath . DIRECTORY_SEPARATOR . $relativeRoot);
if (!$base || strpos($base, $rootPath) !== 0) {
continue;
}
$allowed = array_fill_keys(array_map('strtolower', $extensions), true);
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if (!$file instanceof SplFileInfo || !$file->isFile()) {
continue;
}
$path = $file->getRealPath();
if (!$path || strpos($path, $rootPath . DIRECTORY_SEPARATOR) !== 0) {
continue;
}
$relativePath = str_replace(DIRECTORY_SEPARATOR, '/', ltrim(str_replace($rootPath, '', $path), DIRECTORY_SEPARATOR));
foreach ($excludePrefixes as $prefix) {
if (strpos($relativePath, $prefix) === 0) {
continue 2;
}
}
$extension = strtolower($file->getExtension());
if (isset($allowed[$extension])) {
$files[] = $path;
}
}
}
sort($files, SORT_STRING);
return array_values(array_unique($files));
}
clearstatcache();
$rootPath = realpath($root);
$fingerprints = [];
foreach (collect_asset_files($root, $scanRoots, $excludePrefixes) as $fullPath) {
$relativePath = ltrim(str_replace($rootPath ?: $root, '', $fullPath), DIRECTORY_SEPARATOR);
$fileHash = is_readable($fullPath) ? (hash_file('sha256', $fullPath) ?: 'hash-failed') : 'unreadable';
$fingerprints[] = implode('|', [
str_replace(DIRECTORY_SEPARATOR, '/', $relativePath),
(string)filesize($fullPath),
(string)filemtime($fullPath),
$fileHash,
]);
}
echo json_encode([
'result' => 'ok',
'service' => $service,
'version' => hash('sha256', implode("\n", $fingerprints)),
'count' => count($fingerprints),
'generatedAt' => time(),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+93
View File
@@ -0,0 +1,93 @@
(function () {
'use strict';
var script = document.currentScript || (function () {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1] || null;
})();
var service = script && script.dataset ? script.dataset.service : '';
var endpoint = script && script.dataset && script.dataset.endpoint
? script.dataset.endpoint
: new URL('../asset-version.php', script ? script.src : window.location.href).toString();
var interval = script && script.dataset && script.dataset.interval ? Number(script.dataset.interval) : 30000;
if (!service || window.__assetReloadStarted) return;
window.__assetReloadStarted = true;
interval = Math.max(15000, Number.isFinite(interval) ? interval : 30000);
var storageKey = 'assetVersion:' + service;
var reloadKey = 'assetReload:' + service;
var running = false;
function addQuery(url, key, value) {
var parsed = new URL(url, window.location.href);
parsed.searchParams.set(key, value);
return parsed.toString();
}
function deleteCaches() {
if (!window.caches || !window.caches.keys) return Promise.resolve();
return window.caches.keys().then(function (keys) {
return Promise.all(keys.map(function (key) {
return window.caches.delete(key);
}));
}).catch(function () {});
}
function reloadWith(version) {
var token = version.slice(0, 12);
var marker = token + ':' + Math.floor(Date.now() / 10000);
if (sessionStorage.getItem(reloadKey) === marker) return;
sessionStorage.setItem(reloadKey, marker);
deleteCaches().then(function () {
window.location.replace(addQuery(window.location.href, 'assetReload', token));
});
}
function check(force) {
if (running || (!force && document.hidden)) return;
running = true;
fetch(addQuery(endpoint, '_', String(Date.now())), {
cache: 'no-store',
credentials: 'same-origin',
headers: {
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
}
}).then(function (response) {
if (!response.ok) throw new Error('asset version request failed');
return response.json();
}).then(function (data) {
if (!data || data.result !== 'ok' || !data.version) return;
var previous = localStorage.getItem(storageKey);
localStorage.setItem(storageKey, data.version);
if (previous && previous !== data.version) {
reloadWith(data.version);
}
}).catch(function () {}).finally(function () {
running = false;
});
}
window.addEventListener('pageshow', function () {
check(true);
});
window.addEventListener('focus', function () {
check(true);
});
document.addEventListener('visibilitychange', function () {
if (!document.hidden) check(true);
});
setInterval(function () {
check(false);
}, interval);
check(true);
})();
+1
View File
@@ -318,6 +318,7 @@ ksort($items, SORT_NATURAL);
<link rel="icon" href="assets/icon-192.png" type="image/png" sizes="192x192">
<link rel="apple-touch-icon" href="assets/apple-touch-icon.png">
<link rel="manifest" href="manifest.webmanifest">
<script src="assets/asset-reload.js" data-service="seoul" defer></script>
<script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script>
<style>
* {