move_detect/server/public/index.php
유창욱 bf5255e9eb feat(dashboard): device-status panel + event-list rework, hardened
- Device-status panel (DeviceStatusController): site-scoped liveness over stored
  heartbeat telemetry. Fix config_drift false-positive by storing NULL until the
  device actually reports a version (was firing "설정 미적용" on every device).
- Zone save rejects a blank/unknown device_id (DeviceRepository::exists) so a zone
  is never persisted against a device that will never fetch it.
- Snapshot proxy sends immutable private cache headers, ending the 5s-poll
  re-download of every thumbnail (a Cafe24 traffic-cap hazard).
- Event list: paged-in acknowledgements stick; honesty affordances for the paging
  gap, a stale device poll, and a filtered camera aging out; logout wired for
  every page via the shared layout.
2026-07-25 19:20:42 +09:00

126 lines
6.5 KiB
PHP

<?php
declare(strict_types=1);
// The app root — the directory holding config.php, src/, vendor/ and storage/ — is found by
// walking up from this file rather than hardcoded as '/..'. Its depth genuinely varies:
// one level up when the docroot is the app's own directory, but two when the app is mounted
// in a subdirectory of a www/ that already serves another site, since nothing secret may live
// under a docroot that other site also serves. On shared hosting the private files are kept
// together in a single APP_PRIVATE_DIR beside www/, so that name is probed at every level.
//
// Two deliberate choices guard against binding to the CO-HOSTED site's files:
// * the container is probed BEFORE the bare directory, so our own root always wins;
// * all three markers must be present. config.php + vendor/ alone are ordinary names in any
// PHP project sharing this account — src/Config.php is specific to this app.
const APP_PRIVATE_DIR = 'move_detect_app';
(static function (): void {
$isAppRoot = static fn (string $d): bool =>
is_file($d . '/config.php')
&& is_file($d . '/vendor/autoload.php')
&& is_file($d . '/src/Config.php');
for ($dir = dirname(__DIR__), $i = 0; $i < 4; $i++) {
foreach ([$dir . '/' . APP_PRIVATE_DIR, $dir] as $candidate) {
if ($isAppRoot($candidate)) {
define('APP_ROOT', $candidate);
return;
}
}
if (dirname($dir) === $dir) break; // filesystem root; dirname() would spin here
$dir = dirname($dir);
}
http_response_code(500);
exit('config.php / vendor/autoload.php / src/Config.php not found above ' . __DIR__);
})();
require APP_ROOT . '/vendor/autoload.php';
use App\Config;
use App\Http\{Request, Router, Response};
use App\Db\Database;
use App\Auth\PhpSessionStore;
use App\Repository\Pdo\{PdoDeviceRepository, PdoNonceRepository, PdoRateLimiterRepository,
PdoEventRepository, PdoSnapshotRepository, PdoUserRepository, PdoZoneRepository,
PdoThresholdRepository, PdoAuditRepository};
use App\Ingest\IngestController;
use App\Api\{ConfigController, HeartbeatController};
use App\Auth\{AuthController, CsrfController};
use App\Dashboard\{EventListController, EventDetailController, SnapshotProxy, ZoneConfigController,
DeviceStatusController};
// Never leak internals to the client. Cafe24 shared hosting often ships display_errors=On, so
// an uncaught PDOException would otherwise render the DSN + db_user in a raw 500. Turn it off
// and convert any uncaught Throwable into a generic 500 that is logged, not shown. (A .user.ini
// in the docroot backstops this for errors raised before this file even parses.)
ini_set('display_errors', '0');
ini_set('log_errors', '1');
set_exception_handler(static function (\Throwable $e): void {
error_log('move-detect: ' . $e);
if (!headers_sent()) {
http_response_code(500);
header('Content-Type: application/json');
}
echo '{"error":"internal"}';
});
// The URL prefix this app is mounted under: '' at the web root, '/move_detect' in a
// subdirectory. Server-derived (SCRIPT_NAME), never client input. Views and the JS bundles
// prefix every link/fetch with it; without it they'd address the other site sharing www/.
define('APP_BASE', Request::baseFrom((string)($_SERVER['SCRIPT_NAME'] ?? '')));
$cfg = Config::fromArray(require APP_ROOT . '/config.php');
$pdo = Database::connect($cfg);
// Scope the session cookie to the mount, so a co-hosted site under the same www/ is never
// sent this app's session id.
$sess = new PhpSessionStore(APP_BASE . '/');
$now = time();
$devices = new PdoDeviceRepository($pdo);
$nonces = new PdoNonceRepository($pdo);
$rate = new PdoRateLimiterRepository($pdo);
$events = new PdoEventRepository($pdo);
$snaps = new PdoSnapshotRepository($pdo, $cfg->snapshotDir());
$users = new PdoUserRepository($pdo);
$zones = new PdoZoneRepository($pdo);
$thr = new PdoThresholdRepository($pdo);
$audit = new PdoAuditRepository($pdo);
$ingest = new IngestController($cfg, $devices, $nonces, $rate, $events, $snaps);
$config = new ConfigController($devices, $zones, $thr, $nonces, $cfg, $rate);
$heartbeat = new HeartbeatController($cfg, $devices, $nonces, $rate);
$auth = new AuthController($users, $audit, $rate);
$csrfCtl = new CsrfController();
$list = new EventListController($events, $snaps, $sess);
$detail = new EventDetailController($events, $snaps, $audit, $sess);
$proxy = new SnapshotProxy($snaps, $events, $sess);
$zoneCtl = new ZoneConfigController($zones, $devices, $audit, $sess, $snaps);
$deviceStatus = new DeviceStatusController($devices, $sess);
$render = function (string $view): Response {
ob_start(); require APP_ROOT . '/src/View/' . $view . '.php';
return Response::text((string)ob_get_clean());
};
$r = new Router();
$r->add('POST', '/api/events', fn(Request $q) => $ingest->handle($q, $now, (string)($_SERVER['REMOTE_ADDR'] ?? '')));
$r->add('POST', '/api/heartbeat', fn(Request $q) => $heartbeat->post($q, $now, (string)($_SERVER['REMOTE_ADDR'] ?? '')));
$r->add('GET', '/api/config', fn(Request $q) => $config->get($q, $now, (string)($_SERVER['REMOTE_ADDR'] ?? '')));
$r->add('GET', '/api/csrf', fn(Request $q) => $csrfCtl->token($q, $sess));
$r->add('POST', '/login', fn(Request $q) => $auth->login($q, $sess, $now, (string)($_SERVER['REMOTE_ADDR'] ?? '')));
$r->add('POST', '/logout', fn(Request $q) => $auth->logout($sess));
$r->add('GET', '/api/events', fn(Request $q) => $list->json($q));
$r->add('GET', '/api/devices', fn(Request $q) => $deviceStatus->json($q, $now));
$r->add('GET', '/events/{id}', fn(Request $q, array $p) => $detail->show($q, $p));
$r->add('POST', '/events/{id}/ack', fn(Request $q, array $p) => $detail->acknowledge($q, $p));
$r->add('GET', '/api/zones/{camera}', fn(Request $q, array $p) => $zoneCtl->list($q, $p));
// Background frame for the zone editor: the newest snapshot this camera produced.
$r->add('GET', '/api/cameras/{camera}/latest-snapshot', fn(Request $q, array $p) => $zoneCtl->latestSnapshot($q, $p));
$r->add('POST', '/api/zones', fn(Request $q) => $zoneCtl->save($q));
$r->add('POST', '/api/zones/{id}/delete', fn(Request $q, array $p) => $zoneCtl->delete($q, $p));
$r->add('GET', '/snap/{uuid}', fn(Request $q, array $p) => $proxy->serve($q, $p));
$r->add('GET', '/', fn() => $render('events'));
$r->add('GET', '/login', fn() => $render('login'));
$r->add('GET', '/zones', fn() => $render('zones'));
$r->add('GET', '/events/{id}/view', fn(Request $q, array $p) => $render('event_detail'));
$r->dispatch(Request::fromGlobals())->send();