🔍 Amfor-Cast — Code Review v2

Generated: 2026-08-13 12:57 | Reviewer: AI | Post-fix re-review | Comparing against v1 review from earlier today

1. What Changed Since v1 Review

11 fixes were applied between the initial review and this re-review (commit 376aafa):

v1 FindingStatusDetails
Hardcoded DB password in gitFIXEDconfig.php → gitignored, only .example remains
Flask API duplicating PHP APIFIXEDEntire api/app.py + systemd service + Flask deps removed
SSL fix duplicated 7 timesPARTIALMoved to run.sh. But 2 files still have it: fetch.py, report.py
XSS via city namesPARTIALescapeHtml() added + used in search results. NOT used in city manager list, user menu, or tab rendering
CSP headers missingFIXEDAdded to index.html + both templates
fetch_all_models() too strictFIXEDNow tolerates failures, requires ≥3 models
bashrc.user in repoFIXEDRemoved + gitignored
Silent DB fallbackFIXEDconfig.py now logs warning when DB fails
Unused import os in some scriptsPARTIALRemoved from 5 files; still unused in weather-history.py, evaluate-routes.py, headache-analyzer.py
LIKE wildcards unescapedNOT FIXEDStill present in cities.php line 112
No rate limiting on authNOT FIXEDStill no rate limiting on login/register

2. Updated Scores

A−
Overall
A
Architecture
B+
Code Quality
B
Security
B−
Testing
A−
Operations

Score improvements vs v1: Overall B+ → A−, Security C+ → B, Operations B+ → A−. The Flask API removal alone eliminated an entire attack surface and simplified deployment. The architecture is now clean single-tier (PHP on hosting for auth/API, Pi for generation, rsync for delivery).

3. Security — Remaining Issues

3.1 Still Open

HIGH No rate limiting on authentication endpoints

api/php/auth.php still allows unlimited login attempts. An attacker can brute-force passwords at full speed. This is the highest-priority remaining security issue.

Impact: Any 8-character password can be cracked in reasonable time with parallel attempts (bcrypt cost 12 = ~250ms per attempt, but attackers use multiple IPs).

Fix options (in order of effort):

  1. Quick: Add a login_attempts table, check before password_verify():
    -- Add to schema
    CREATE TABLE login_attempts (
      email VARCHAR(255),
      ip VARCHAR(45),
      attempted_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      KEY idx_email_time (email, attempted_at),
      KEY idx_ip_time (ip, attempted_at)
    );
    
    -- In handle_login():
    $stmt = $db->prepare('SELECT COUNT(*) FROM login_attempts 
      WHERE email = ? AND attempted_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)');
    $stmt->execute([$email]);
    if ($stmt->fetchColumn() >= 5) {
      json_response(['error' => 'Too many attempts. Try again in 15 minutes.'], 429);
    }
  2. Better: Exponential backoff per email (1s, 2s, 4s, 8s…) + IP-level cap (20/hour)
  3. Best: Use a proper rate-limit middleware or Cloudflare's rate limiting

MEDIUM Incomplete XSS mitigation — escapeHtml() not applied everywhere

escapeHtml() was added and used in the search results rendering (line 466). But user-controlled data still goes into innerHTML unescaped in these locations:

FileLineExpression
user.js320${currentUser.display_name || 'User'}
user.js321${currentUser.email}
user.js368${c.display_name} (city manager list)

Attack vector: A user registers with display_name = "<img onerror=alert(1) src=x>". The display_name appears unescaped in their own user menu (self-XSS only, so LOW). But c.display_name at line 368 shows cities from the shared pool — if a malicious user adds a city with an XSS payload via the add endpoint, it renders in OTHER users' city manager. This is stored XSS.

Fix: Apply escapeHtml() to all three locations. The fix is trivial — just wrap the interpolated values.

MEDIUM LIKE wildcards not escaped in city search

cities.php line 112 still has:

$like = "%$query%";
$stmt->execute([$like, $like]);

Searching for % returns all cities. Searching for _____ finds all 5-character city names. This enables enumeration of the entire city database.

Fix:

$escaped_query = addcslashes($query, '%_\\');
$like = "%{$escaped_query}%";

MEDIUM No CSRF protection on POST endpoints

Mitigated by SameSite=Strict cookie flag (which blocks cross-site request submission in modern browsers). But older browsers (IE, pre-2020 Safari) don't enforce SameSite. The cors_headers() function checks Origin against ALLOWED_ORIGINS, which helps but isn't a complete CSRF defense (some requests don't send Origin header).

Residual risk: Low for this project's user base (tech-savvy, modern browsers). But if you want to be thorough, add X-Requested-With: XMLHttpRequest check for all POST handlers.

LOW Open registration without rate limiting or verification

While the threat model for a personal weather app is low, automated bots could fill the cities table with garbage entries. Adding rate limiting to registration (3/hour/IP) would prevent this without adding email verification complexity.

LOW No expired session cleanup

The sessions table grows indefinitely with expired rows. Per-user cleanup (keep last 5) runs on login, but globally expired sessions are never purged.

Fix: Add to run.sh or a weekly cron: mysql -e "DELETE FROM sessions WHERE expires_at < NOW()"

3.2 Fixed (Verified)

FIXED ✅ Hardcoded credentials removed from git

api/php/config.php is now gitignored. Only config.php.example (with CHANGE_ME placeholder) is tracked. Verified: the file doesn't exist in the working tree.

FIXED ✅ Flask API removed — single API surface

api/app.py, api/__init__.py, api/amfor-cast-api.service, and Flask/Gunicorn dependencies all removed. The only API is now the PHP layer on tarhely.com. This eliminates: wildcard CORS, duplicate route logging, separate rate-limit implementation, and the systemd attack surface.

FIXED ✅ CSP headers added to all page templates

Content-Security-Policy meta tag present on index.html, template.html (forecast), and template.html (history). Correctly restricts script-src to self + CDN, connect-src to known API domains.

4. Code Quality — Remaining Issues

LOW SSL fix still in 2 files despite run.sh handling it

scripts/weather-forecast/fetch.py (lines 24-26) and scripts/model-validator/report.py (lines 30-32) still set SSL_CERT_FILE. Since run.sh now exports it before launching Python, these are redundant. They're harmless (idempotent check) but add noise.

Fix: Remove the 3 lines from both files.

LOW Unused import os in 3 files

After removing the SSL fix code, these files still import os without using it:

  • scripts/weather-history/weather-history.py
  • scripts/model-validator/evaluate-routes.py
  • scripts/headache-analyzer/headache-analyzer.py

Ruff doesn't catch this because F401 (unused import) is in per-file-ignores for these files. Consider removing the per-file-ignores and cleaning up.

LOW escapeHtml() defined in user.js, used in city-nav.js IIFE

city-nav.js calls escapeHtml() at line 127, but the function is defined globally in user.js. This works because user.js loads before city-nav.js in index.html. But on any page that loads city-nav.js without user.js (e.g., static forecast pages), this would throw ReferenceError.

Fix: Either duplicate the 3-line function inside the IIFE, or create a shared utils.js loaded first everywhere.

LOW sys.path.insert still used everywhere

This remains the biggest code quality issue — no proper Python packaging. Every script manipulates sys.path. While it works, it makes the project hostile to IDEs, type checkers, and refactoring tools. A pyproject.toml with editable install would clean this up in one commit.

INFO run-and-publish.py still has empty SSL fix section

Lines 33-35 have a comment block # SSL fix (for CentOS/RHEL build servers) followed by an empty section. The code was removed but the comment skeleton remains.

5. Reliability

5.1 Improved

5.2 Still Remaining

MEDIUM No connection pooling for database

shared/db.py opens a new connection per operation. During a full run with the model validator (~40 DB operations), this creates excessive connection churn. On shared hosting with connection limits, this could cause intermittent failures under load.

LOW cleanup_old_forecasts() CASCADE delete could be expensive

A year's worth of 8 models × 4 cities × 16 days × 24 hours = ~4.5M forecast_hours rows. Deleting all at once with CASCADE could lock the table for minutes on shared hosting.

6. Testing

59 tests pass cleanly in 0.81s. Ruff reports zero warnings. This is solid for unit/smoke coverage.

6.1 Coverage Assessment

ComponentTest CoverageRisk
shared/ (config, headaches, model_selector)Good — unit tests for all public functionsLow
Forecast data parsing + scoringGood — TestComputeErrors, TestRainAccuracy, TestParseForecastLow
Import/compile smoke testsAll .py files verified compilableLow
render.py (629 LOC)NoneMedium — template changes could silently break output
PHP API (auth, cities, log-route)NoneHigh — security-critical, no automated verification
Frontend JS (user.js, city-nav.js, route-weather.js)None (only syntax check for current-weather.js)Medium
Database operations (shared/db.py)None (requires DB connection)Medium
End-to-end (full pipeline)NoneLow (manual verification via --dry-run is adequate for a personal project)

6.2 Recommended Next Tests

  1. render.py fixture test: Call render_html() with mock data, assert output contains expected sections and no Python exceptions.
  2. PHP API curl test: A shell script that registers, logs in, adds a city, removes it, and logs out — verifying HTTP status codes. Run after deploy.
  3. escapeHtml unit test: Verify it handles <>&"' correctly (add to test_current_weather.py).

7. Operations

7.1 Improved

7.2 Remaining

MEDIUM run.sh does git pull -r without validation

A broken commit to main immediately breaks the next hourly run. CI runs lint + test, but there's a race condition: if you push at 07:44 and CI takes 2 minutes, the 07:45 cron fires with untested code.

Mitigation: Since tests run in <1 second locally (and you work solo), this is acceptable risk. Just be aware that pushing broken code has immediate production impact.

LOW No "data freshness" indicator on frontend

If the Pi stops running (power outage, SD card failure), users see stale data with no indication it's outdated. A simple "Last updated: X hours ago" footer would help.

8. Frontend

8.1 Strengths (Unchanged)

8.2 Remaining Issues

MEDIUM Accessibility gaps

No changes since v1. Modals still lack role="dialog", aria-modal, focus trapping, and aria-labels on close buttons. Weather emojis should have aria-hidden="true" or equivalent text alternatives.

LOW 6 separate JS files loaded synchronously

All 6 scripts are render-blocking (<script src="..."> without defer or async). Adding defer to all scripts would improve First Contentful Paint without changing behavior (since they already run on DOMContentLoaded).

LOW CSP doesn't include *.tile.openstreetmap.org for map tiles

The route-weather page loads Leaflet map tiles from *.tile.openstreetmap.org. The CSP img-src only allows 'self' data: — this would block map tile loading. Either the route-weather page needs its own CSP, or the global CSP needs *.tile.openstreetmap.org added to img-src.

9. Remaining Action Items (Prioritized)

🔴 Do Now (15 min total)

#FixFileEffort
1Add rate limiting to login endpointauth.php10 min + schema change
2Apply escapeHtml() to remaining 3 innerHTML locationsuser.js:320,321,3682 min
3Escape LIKE wildcards in city searchcities.php:1121 min

🟡 Do Soon (30 min total)

#FixFileEffort
4Remove residual SSL fix from fetch.py + report.py2 files1 min
5Remove unused import os from 3 files + clean ruff per-file-ignores3 files + ruff.toml3 min
6Delete empty SSL comment block from run-and-publish.pyrun-and-publish.py:33-3530 sec
7Add *.tile.openstreetmap.org to CSP img-src (or route-weather needs own CSP)index.html + templates2 min
8Add defer to all 6 script tagsindex.html1 min
9Define escapeHtml() inside city-nav.js IIFE (avoid global dependency)city-nav.js2 min
10Add expired session cleanup to weekly croncrontab or run.sh2 min

🟢 Do Eventually (quality of life)

  1. Create pyproject.toml for proper Python packaging (eliminate sys.path hacks)
  2. Add render.py fixture test
  3. Add PHP API smoke test (curl script)
  4. Add "last updated" timestamp to frontend pages
  5. Add accessibility improvements (aria-labels, focus trapping)
  6. Batch DB cleanup with LIMIT to avoid long locks
  7. Add rate limiting to registration endpoint
  8. Connection pooling (when traffic justifies it)

Conclusion

The codebase is in significantly better shape after the 11 fixes. The biggest wins were removing the Flask API (eliminated an entire redundant surface area + 3 dependencies) and gitignoring the credentials file. The architecture is now clean and simple: Pi generates → rsync to hosting → PHP handles auth.

The three remaining must-fix items are all in the PHP API layer: login rate limiting, escapeHtml completion, and LIKE escaping. Together these are ~15 minutes of work and would bring the security score to A−.

For a personal project with a small user base, this codebase is production-ready. The code is well-organized, tests pass, CI enforces quality, and the operational model (hourly cron + rsync) is simple and reliable. The multi-model validation system continues to be the standout feature — it's a genuinely original approach to weather forecasting that produces actionable insights.