Commit graph

36 commits

Author SHA1 Message Date
유창욱
9a0ff1fc5e feat(cloud): cursor pagination for the event list (P4-5)
The event list was hard-capped at the newest 100 with no way to reach
older events. Adds keyset pagination:

- EventRepository::page(limit, severity, beforeTs, beforeId) on both the
  PDO and in-memory implementations, ordered (occurred_at DESC,
  event_id DESC). The cursor is the last row's (occurred_at, event_id),
  so pages stay stable as new events arrive at the head — no overlap, no
  skips. occurred_at is bound as a string in SQL to keep DECIMAL
  precision.
- EventListController reads `limit` (default 50, capped 200) and `cursor`
  ("occurred_at:event_id", malformed input ignored) and returns
  `next_cursor` only on a full page. recent() is retained for existing
  callers; the response gains next_cursor additively.

The live-tail dashboard keeps consuming page 1; a history-browse UI can
build on the same cursor. Test: testListPaginatesWithCursor.

phpunit: 89 passing (4 skipped: PDO-backed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 10:05:52 +09:00
유창욱
d0ba621b42 fix(cloud): verify login CSRF + zone ownership 400 not 500 (P4-8, P4-6)
P4-8: AuthController::login now verifies the CSRF token the login form
already emits (Csrf::check over session vs posted field), returning 403
before the user lookup. Closes a login-CSRF / session-fixation hole where
a forged cross-site POST could silently log a victim into an attacker's
account. Tests seed the session+body token; adds
testLoginRejectsMissingOrWrongCsrf.

P4-6: ZoneConfigController::save wraps the repository write in
try/catch(\RuntimeException) so an ownership/device mismatch is a 400
(invalid_zone) client error, not an uncaught 500. Adds
testSaveOwnershipMismatchIs400NotError with a throwing repo double.

phpunit: 88 passing (4 skipped: PDO-backed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 10:00:04 +09:00
유창욱
c66b034921 fix(cloud): logout order, url normalization, length caps, package hygiene (P4-9/10/11, P5-6)
- P4-9 [L] logout() rotates the session id before wiping (was regenerate-after-destroy → warning).
- P4-10 [L] EventValidator caps device_id/camera_id (64) + zone_id (32) → 400 not a MySQL
  'Data too long' 500 the edge retries forever.
- P4-11 [L] Request::pathFor collapses leading slashes so '//api/events' isn't misrouted to '/events'.
- P5-6 [L] cafe24 build prunes dev caches (.ruff_cache/.impeccable/__pycache__/…) from the package.

python + phpunit (86) green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 09:48:35 +09:00
유창욱
1187df5628 feat(delivery-audit): PIPA retention + cloud hardening (P3-2, P4-1..4)
- P3-2 [H] snapshot retention (7 days): snapshot_retention_days config;
  SnapshotRepository::purgeOlderThan (interface + Pdo + double, files-then-rows,
  bounded batch); opportunistic purge in the ingest path (Cafe24 has no cron).
- P4-1 [H] index.php sets display_errors=0 + a global exception handler → generic
  {"error":"internal"} + error_log (no DSN/db_user leak); ships www/move_detect/.user.ini.
- P4-2 [H] ConfigController + HeartbeatController take an optional rate limiter +
  clientIp; pre-auth per-IP anti-flood → 429 (were unthrottled).
- P4-3 [M] PdoNonceRepository::remember + PdoRateLimiterRepository::hit opportunistically
  reap expired rows (Cafe24 has no cron; tables grew unbounded).
- P4-4 [M] Router::dispatch rawurldecodes captured params (Korean/space camera_id could
  save zones but never load them).

Tests: python green; phpunit 84 green. See docs/delivery-audit.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 09:28:16 +09:00
유창욱
9386dfc580 feat(delivery): install-path fixes + cafe24 package + delivery-audit hardening
Three intertwined bodies of work developed and tested together this session.
Full test suite green: python (edge) + phpunit (cloud).

## Edge/Pi install path
- setup_online.sh: apt-lock retry (apt-daily contention), Type=exec unit +
  StartLimitIntervalSec in [Unit], journalctl-on-failure, crash-loop detection.
- onnxruntime is now best-effort (no sdist / no 32-bit-ARM wheel); [6/8] probes the
  real backend and hard-fails if none works.
- Hailo HEF auto-fetch: edge/tools/fetch_hailo_hef.py (pinned sha256, refuses to guess
  8 vs 8L, HAILO_ARCH override for serial-less boards); hailo_pose.py run() timeout fix.
- install_offline.sh: mirrors the backend gate; onnxruntime optional.

## Cafe24 cloud package (cloud/deploy/)
- build_cafe24_package.sh emits move_detect_app/ (private, one folder) + www/move_detect/
  (docroot subdir); no-dev classmap autoloader; preflight.php; hardened .htaccess.
- Subdirectory mount support: Request::baseFrom/pathFor strip the mount prefix; index.php
  walks up to find the app root; views/JS prefix every URL with APP_BASE; session cookie
  scoped to the mount.

## Delivery audit — silent-failure & correctness (docs/delivery-audit.md)
All 4 blockers + all Phase-1 silent-failure + Phase-2 HIGH correctness:
- Edge cloud clients send a custom User-Agent (cafe24 WAF blocks python-requests) and
  allow_redirects=False.
- Daemon fails loud on blank CAFE24_URL/DEVICE_SECRET; run_loop logs swallowed exceptions;
  heartbeat carries real fps + per-camera health; UvcSource reopens a dead camera;
  offline queue is size-capped and drops poison rows; TARGET_FPS/QUEUE_DB validated.
- Zone coordinates normalized 0..1 on both sides (were canvas-px vs camera-px — every zone
  misplaced); pinch zones emit PINCH/HIGH (were downgraded to WARNING).
- Fall detection uses bbox cues when keypoints are low-confidence (occluded fallen person);
  ghost incident not cancelled by a bystander; displacement normalized per-second (FPS-invariant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 09:07:33 +09:00
유창욱
b0d1241da1 feat(cloud): dashboard rows link to detail + desk Web Audio on critical 2026-07-12 11:49:07 +09:00
유창욱
55d99602ce feat(cloud): incident detail view renders snapshot images 2026-07-12 11:48:55 +09:00
유창욱
171ef3e1c5 fix(cloud): add nonce-replay + timestamp-window checks to config/heartbeat (M2)
ConfigController::get and HeartbeatController::post verified HMAC but never
checked nonce replay or timestamp freshness, so a captured signed request
(e.g. a replayed heartbeat) could be replayed forever, masking a dead
device. Inject NonceRepository (+Config) into both and add the same
timestamp-window + nonce-remember checks IngestController already applies,
after HMAC verification and before the response/side effect.
2026-07-12 09:19:32 +09:00
유창욱
3405c1e2cc fix(cloud): enforce CSRF on authenticated state-changing POSTs (M1)
Only SameSite=Lax protected the acknowledge and zone save/delete endpoints,
even though a Csrf helper and mintable token already existed. Add
GET /api/csrf (CsrfController::token) to mint/return a per-session token,
check it (auth -> rbac -> csrf -> mutate) in EventDetailController::acknowledge
and ZoneConfigController::save/delete, and wire app.js/zone-draw.js to fetch
the token on load and send it as X-Csrf-Token on every POST.
2026-07-12 09:16:38 +09:00
유창욱
238b932c86 fix(cloud): add per-IP rate limit to /login before Argon2id verify (H2)
Every login attempt, including unknown users (via DUMMY_HASH), forces a full
Argon2id verify with no rate limit, letting a flood take down the login
endpoint / shared host via hashing-cost amplification. Add a pre-auth
per-IP limiter (RateLimiterRepository, default 20/min) as the first check
in AuthController::login, before any user lookup or password hashing.
2026-07-12 09:11:47 +09:00
유창욱
7828f9c419 fix(cloud): move ingest per-device rate limit post-auth, add pre-auth IP limit (H1)
An unauthenticated attacker could guess a real device_id and 429-lock that
camera by hammering /api/events before HMAC verification ran, dropping its
accident events. Add a cheap pre-auth per-IP limiter (Config::ingestIpRateLimitPerMin,
default 300/min) that fires before any device-secret lookup, and move the
existing per-device limiter to run only after HMAC + timestamp + nonce checks
succeed, so only authenticated requests consume a device's own quota.
2026-07-12 09:09:31 +09:00
유창욱
c1fb22ee16 fix(cloud): deterministic event ordering + zone concurrent-delete detection
Self-review (Task 16) follow-up fixes:
- PdoEventRepository::recent(): add event_id DESC as a secondary sort key
  after occurred_at DESC so ties (equal device-reported timestamps) resolve
  deterministically, matching InMemoryEventRepository's insertion-order
  tie-break.
- PdoZoneRepository::updateOwned(): after the ownership-scoped UPDATE,
  disambiguate a 0-rowCount() result (MySQL reports "changed" rows, not
  "matched" rows) with a targeted existence check, so a genuine no-op
  resubmit (identical level/polygon) still succeeds while a zone deleted
  concurrently between the ownership check and the UPDATE now throws
  instead of save() silently reporting success for a zone that no longer
  exists.

Full suite still green: 59 tests, 114 assertions, 4 skipped, 0 failures,
0 warnings/deprecations.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ne4rU4FToTLHcBUMUvUnT1
2026-07-12 02:06:32 +09:00
유창욱
9aa7f44ea4 feat(cloud): PDO repositories + schema + Cafe24 deploy doc
Implements Task 16 (final, P1-B): App\Db\Database::connect(Config): PDO
factory and the 9 App\Repository\Pdo\Pdo*Repository classes backing the
repository interfaces consumed by controllers since T1-T15, all-prepared
statements, plus cloud/schema.sql (MySQL 8 DDL) and cloud/docs/cloud-deploy.md.

Security hardening incorporated per accumulated task reviews:
- PdoNonceRepository: nonces.nonce is PK; duplicate remember() throws instead
  of racing seen() (closes T7 TOCTOU).
- PdoRateLimiterRepository::hit(): atomic INSERT ... ON DUPLICATE KEY UPDATE
  upsert on (rate_key, window_start), no read-modify-write race.
- PdoSnapshotRepository::pathByUuid(): validates 32-hex uuid before building
  any filesystem path (closes T12 path-traversal risk).
- PdoZoneRepository::save(): update path is ownership-scoped by
  (zone_id, device_id, camera_id); throws on mismatch instead of silently
  overwriting an unrelated zone (closes T13 cross-tenant overwrite risk).
- Database::connect(): ERRMODE_EXCEPTION, EMULATE_PREPARES=false, FETCH_ASSOC.

cloud/tests/PdoIntegrationTest.php round-trips Nonce/Event/Zone against a
real sqlite :memory: DB, gated via markTestSkipped when pdo_sqlite is
unavailable (this host has pdo_mysql only, no pdo_sqlite) -- suite stays
green with 4 tests skipped.

Full suite: 59 tests, 114 assertions, 4 skipped, 0 failures, 0
warnings/deprecations. php -l passes on all new files and on
cloud/public/index.php (T15), which references all new FQCNs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ne4rU4FToTLHcBUMUvUnT1
2026-07-12 01:58:05 +09:00
유창욱
81eae5d045 fix(cloud): login form submits via fetch (redirect on success, show error) 2026-07-12 01:39:06 +09:00
유창욱
81e8e81b72 feat(cloud): front controller wiring + views + zone-draw UI 2026-07-12 01:24:42 +09:00
유창욱
5135c08e18 feat(cloud): device config + heartbeat sync API (HMAC) 2026-07-12 01:13:02 +09:00
유창욱
92c630bf58 feat(cloud): polygon validation + zone config controller (RBAC) 2026-07-12 01:02:37 +09:00
유창욱
90d3016b17 feat(cloud): dashboard list/detail/ack + auth-gated snapshot proxy 2026-07-12 00:56:43 +09:00
유창욱
430758c3b7 feat(cloud): path-param router + dispatch 2026-07-12 00:49:52 +09:00
유창욱
f7a0a3740e test(cloud): cover unknown-username 401 parity + logout session clear 2026-07-12 00:46:39 +09:00
유창욱
902bbe93c8 fix(cloud): reset lockout on window expiry + constant-time unknown-user path (anti-enumeration) 2026-07-12 00:39:19 +09:00
유창욱
450c88978f fix(cloud): session-id regeneration on login (fixation) + pristine test output 2026-07-12 00:35:41 +09:00
유창욱
b345a89788 feat(cloud): session store + auth controller with lockout 2026-07-12 00:28:18 +09:00
유창욱
9983bc8fe3 feat(cloud): RBAC permission matrix 2026-07-12 00:19:47 +09:00
유창욱
76ea1b4ecf feat(cloud): argon2id password + CSRF token helpers 2026-07-12 00:11:20 +09:00
유창욱
185629a4c4 fix(cloud): unify ingest auth errors (anti-enumeration) + guard snapshot write 2026-07-12 00:07:42 +09:00
유창욱
57cfc64548 feat(cloud): ingest controller (HMAC+nonce+ratelimit+reencode+persist) 2026-07-12 00:01:05 +09:00
유창욱
a0db1e06ca feat(cloud): Http Request/Response primitives 2026-07-11 23:54:58 +09:00
유창욱
7246e12c4a feat(cloud): gd image re-encode (strip payload, uuid, hash) 2026-07-11 23:50:08 +09:00
유창욱
2f88355071 fix(cloud): type-guard EventValidator fields against malformed input 2026-07-11 23:46:38 +09:00
유창욱
b5388b2a68 feat(cloud): event payload validator with enum whitelist 2026-07-11 23:40:53 +09:00
유창욱
4bbd28f95f fix(cloud): centralize test-double autoloading via composer files
Move InMemoryRepositories.php from require_once workaround to composer
files-autoload. Enables PSR-4 autoloading of test-double classes and
scales for 5+ future test files. All 8 tests pass with require_once removed.
2026-07-11 23:38:01 +09:00
유창욱
67b9999a31 feat(cloud): repository interfaces + in-memory test doubles 2026-07-11 23:32:16 +09:00
유창욱
6fbe4015dc test(cloud): golden HMAC vectors proving P1-A Python interop 2026-07-11 23:25:15 +09:00
유창욱
8e62304471 feat(cloud): HMAC sign/verify matching P1-A edge contract 2026-07-11 23:21:00 +09:00
유창욱
50cb2cfe82 feat(cloud): P1-B scaffold — composer autoload + Config 2026-07-11 23:16:13 +09:00