move_detect/server/public/index.php
유창욱 c3227c179c fix(security,edge,test): close the confirmed audit backlog; add the guards that prevent recurrence
감사에서 확정된 잔여 항목을 일괄 처리. 이전 커밋이 증상(스테일 번들)을 고쳤다면 이번에는
그것이 조용히 지나가게 만든 구조를 고친다.

보안
- CSP 도입. 인라인 2블록에 per-request nonce, unsafe-inline 없음. 빌드가 없다는 제약이
  nonce를 막지는 않는다. 보안 헤더를 .htaccess 단독에서 PHP로 옮겨 개발/납품이 같아진다.
- /logout에 CSRF. SameSite=Lax가 막아주지만, 사고 대응 중 운영자를 콘솔에서 튕겨내는 건
  이 제품에선 실제 가용성 공격이라 예외로 둘 이유가 없다.
- 잠긴 계정 423 → 401. 아무나 이름을 추측해 5회 실패로 잠근 뒤 423을 계정 실재 확인으로
  쓸 수 있었다. 잠금 사실은 감사 로그에 남고, 익명 호출자는 못 읽는다.

엣지
- 큐 flush에 회당 상한. 정전 복구 직후 2000건을 비우는 동안 감지가 멈추던 구간을 없앤다.
- 타이머 env 전수 검증. COOLDOWN_S=nan은 dedup을 무력화해 매 틱 발보시켰다.
- T2 프레임 스킵(INFER_EVERY). 스킵 틱은 프레임을 읽어 버퍼만 비우고 링버퍼에 넣지 않는다 —
  추론이 없으면 얼굴 박스도 없어 그대로 넣으면 증거 스냅샷에 미블러 얼굴이 실린다.
  T3(모션 게이트)는 의도적으로 미구현: 게이트가 틀리면 '움직이지 않는 쓰러진 작업자'에게
  추론이 안 돈다. 실영상 없이 임계값을 정할 수 없다.
- systemd 워치독(sd_notify) + 메모리 상한. Restart=always는 죽은 프로세스만 잡고
  '살아 있는데 멈춘' 상태는 못 잡는다. UVC 해상도·버퍼 고정(링버퍼 RSS가 웹캠 기본값에 좌우).

테스트 — 감사의 최대 갭
- PDO 통합 테스트가 pdo_sqlite 부재로 통째로 스킵되고 CI도 없어 사실상 한 번도 안 돌았다.
  `-d extension=pdo_sqlite`로 되살리고 리포트·히트맵·익스포트 집계 SQL을 최초로 실행한다.
- 얼굴 블러 테스트가 out is not None만 봤다 — blur()가 무동작이어도 통과. PIPA 대응의
  유일한 실행 가능한 증거였는데 아무것도 증명하지 못했다. 디테일 파괴를 단언하도록 교체.
- index.php 라우트 테이블 대조(프런트 호출 15개 교차검증), dist↔소스 패리티 테스트,
  CI 신설(스킵이 하나라도 있으면 실패).
- ArraySessionStore.regenerate()가 데이터를 지워 실제 session_regenerate_id(true)와
  달랐다. 더블이 실구현과 어긋난 자리 하나를 실제로 잡았다.

프런트
- 이벤트 목록 시그니처 재렌더 스킵 + 포커스 복원. aria-live 영역을 5초마다 통째로 다시
  만들어 스크린리더가 200행을 재낭독하고 키보드 포커스가 body로 날아갔다. 같은 패턴이
  device-tree.js에는 이미 있었다.
- 폴링 중첩 가드(느린 공유호스팅에서 응답 역전), 콜드스타트 실패 표시.

납품
- VERSION 신설, 두 산출물에 version/git_commit/built_at 스탬프. 스테일 번들의 SHA256SUMS는
  자기정합적이라 통과한다 — provenance 없이는 하류에서 탐지할 방법이 없다.
- deploy/README·env.example을 Hailo 단독 번들 실제와 일치(템플릿이 없는 ONNX를 가리켰다).
- 이벤트 보존 정책은 기본 0(영구). 산업안전 기록을 시스템이 임의로 지우지 않는다.

검증: pytest 251 / PHPUnit 162, 스킵 0. CSP nonce 결합은 실제 렌더 경로로 확인.
브라우저 실렌더는 MySQL이 필요해 이 환경에서 미수행.
2026-08-07 23:31:53 +09:00

142 lines
7.7 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, PdoActionRepository};
use App\Ingest\IngestController;
use App\Api\{ConfigController, HeartbeatController};
use App\Auth\{AuthController, CsrfController};
use App\Dashboard\{EventListController, EventDetailController, SnapshotProxy, ZoneConfigController,
DeviceStatusController, HeatmapController, FpStatsController, ReportController,
ExportController, ActionsController};
// 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);
$heatmap = new HeatmapController($events, $sess);
$fpStats = new FpStatsController($events, $sess);
$report = new ReportController($events, $sess);
$export = new ExportController($events, $snaps, $sess);
$actionsCtl = new ActionsController(new PdoActionRepository($pdo), $events, $sess);
$render = function (string $view): Response {
ob_start(); require APP_ROOT . '/src/View/' . $view . '.php';
// Security headers travel with the HTML response (not only the packaged .htaccess) so the
// CSP nonce the views just emitted is the one the browser is told to trust.
return Response::text((string)ob_get_clean(), 200, \App\Security\Csp::headers());
};
$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($q, $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('POST', '/events/{id}/false-positive', fn(Request $q, array $p) => $detail->falsePositive($q, $p));
$r->add('GET', '/api/zones/{camera}', fn(Request $q, array $p) => $zoneCtl->list($q, $p));
$r->add('GET', '/api/heatmap/{camera}', fn(Request $q, array $p) => $heatmap->json($q, $p));
$r->add('GET', '/api/fp-stats', fn(Request $q) => $fpStats->json($q));
$r->add('GET', '/api/report', fn(Request $q) => $report->json($q));
$r->add('GET', '/api/export/labels', fn(Request $q) => $export->labels($q));
$r->add('GET', '/api/actions', fn(Request $q) => $actionsCtl->json($q));
$r->add('POST', '/api/actions', fn(Request $q) => $actionsCtl->save($q));
// 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', '/report', fn() => $render('report'));
$r->add('GET', '/events/{id}/view', fn(Request $q, array $p) => $render('event_detail'));
$r->dispatch(Request::fromGlobals())->send();