From 469bae40379b37dd0833f2f8d482dc4327683fa3 Mon Sep 17 00:00:00 2001 From: seo Date: Wed, 8 Jul 2026 03:27:26 +0900 Subject: [PATCH] =?UTF-8?q?asset=20hash=20=EC=83=88=EB=A1=9C=EA=B3=A0?= =?UTF-8?q?=EC=B9=A8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++ public/asset-version.php | 76 ++++++++++++++++++++++++++++ public/assets/asset-reload.js | 93 +++++++++++++++++++++++++++++++++++ public/index.php | 1 + 4 files changed, 174 insertions(+) create mode 100644 public/asset-version.php create mode 100644 public/assets/asset-reload.js diff --git a/README.md b/README.md index 8bdf1a1..736bd23 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ Control은 라즈베리파이/리눅스 호스트의 팬과 시스템 상태를 - `public/index.php`: 로그인과 관리 화면 - `public/api.php`: 상태 조회와 조작 API +- `public/asset-version.php`: 화면과 API 파일 묶음의 현재 hash를 내려주는 JSON 엔드포인트 +- `public/assets/asset-reload.js`: 열린 브라우저에서 파일 묶음 hash가 달라졌는지 확인하고 새로 여는 스크립트 - `public/assets/app.js`: 대시보드 렌더링, WebSocket, 차트, 조작 이벤트 - `public/assets/wakelock.js`: Screen Wake Lock API 제어 - `config/config.php`: DB, 인증, CSRF, shell 실행 공통 함수 @@ -58,6 +60,8 @@ Control은 라즈베리파이/리눅스 호스트의 팬과 시스템 상태를 - `bin/wifi_observe.php`: 5G WiFi 연결 시간 보정을 위한 시스템단 관측 CLI - `systemd/control-wifi-observe.*`: WiFi 관측 CLI를 주기적으로 실행하는 systemd unit 예시 +`asset-version.php`는 `public`의 PHP/JS/CSS/manifest/icon 파일과 `config`의 PHP 파일을 읽어 크기, 수정 시각, sha256 hash를 묶은 버전을 만듭니다. `asset-reload.js`는 화면 복귀, 포커스 복귀, 30초 간격으로 이 값을 다시 확인하고, 값이 달라지면 브라우저 Cache Storage를 비운 뒤 현재 화면을 다시 엽니다. + ## 데이터/저장소 - `control_state`: 팬 모드와 PWM 상태 diff --git a/public/asset-version.php b/public/asset-version.php new file mode 100644 index 0000000..c067eb9 --- /dev/null +++ b/public/asset-version.php @@ -0,0 +1,76 @@ + ['php', 'js', 'css', 'json', 'webmanifest', 'svg', 'png', 'ico'], + 'config' => ['php'], +]; + +function collect_asset_files(string $root, array $scanRoots): 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 . DIRECTORY_SEPARATOR) !== 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; + } + + $extension = strtolower($file->getExtension()); + if (!isset($allowed[$extension])) { + continue; + } + + $path = $file->getRealPath(); + if ($path && strpos($path, $rootPath . DIRECTORY_SEPARATOR) === 0) { + $files[] = $path; + } + } + } + + sort($files, SORT_STRING); + return array_values(array_unique($files)); +} + +clearstatcache(); +$rootPath = realpath($root); +$fingerprints = []; + +foreach (collect_asset_files($root, $scanRoots) 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); diff --git a/public/assets/asset-reload.js b/public/assets/asset-reload.js new file mode 100644 index 0000000..1b291bb --- /dev/null +++ b/public/assets/asset-reload.js @@ -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); +})(); diff --git a/public/index.php b/public/index.php index 51f9ee1..44c7ee0 100644 --- a/public/index.php +++ b/public/index.php @@ -76,6 +76,7 @@ $loggedIn = signed_in(); +