Two independent adversarial reviews (codex CLI + a 6-dimension verification workflow) of the delivery-hardening branch surfaced ~40 findings; this closes the confirmed correctness/security/deploy blockers plus a codex re-review pass. edge: - geometry: track_displacement per-second threshold recalibrated (0.02->0.25, env-tunable via MOTION_THR, validated finite/positive); confidence-filter keypoints with a bbox-center fallback so hallucinated points don't fake motion - fall: low-confidence frames no longer cancel an active FALLING/FALLEN incident (freeze + reset recovery timer so recovery needs a fresh confident streak); baseline height only seeded from trusted frames - queue: PostClient.send() returns a tri-state SendResult; only definite 4xx count toward the poison drop cap, so a network outage (incl. 408/425/429/5xx) never deletes queued safety events; legacy rows persist their minted uuid - config: reject placeholder / http / short DEVICE_SECRET at startup - zones: warn+skip legacy pixel-space polygons that would silently match nothing cloud: - zone endpoints wired into P3-2b site-scope (cross-site read/write/delete closed) + role gate on list; catch narrowed so DB faults surface as 500 - snapshot purge keeps the DB row when unlink() fails (no untrackable PIPA orphan) - ingest dedup path re-stores missing snapshots (+ short-write guard); UNIQUE (event_id, content_hash) makes recovery idempotent under retry/race - event list cursor carries full-precision occurred_at (no float rounding at the page boundary); string keyset end-to-end - SiteScope '' fails closed (only NULL is global); dashboard fetches full page cap - runnable migration (site/event_uuid + backfill ordering + indexes); rate-limit reap fails open deploy: - offline bundle hashes EVERY file (fatal on missing/failed/injected; models in SBOM; arch in tarball name; REQUIRE_SIGNATURE option) - installer verifies before any mutation, Hailo arch preflight before install, atomic src swap, backend reconcile preserves a working operator choice - systemd DeviceAllow=char-dma_heap (the /dev/dma_heap/ dir form was inert) Verified: edge pytest 165 passed / 2 skipped; cloud phpunit 109 passed / 4 skipped; deploy scripts bash -n clean. Reviewed by codex twice (findings + fixes) with the second-pass findings folded in.
121 lines
6.1 KiB
PHP
121 lines
6.1 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};
|
|
|
|
// 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, $sess);
|
|
$detail = new EventDetailController($events, $snaps, $audit, $sess);
|
|
$proxy = new SnapshotProxy($snaps, $events, $sess);
|
|
$zoneCtl = new ZoneConfigController($zones, $devices, $audit, $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', '/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));
|
|
$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();
|