1. What Changed Since v1 Review
11 fixes were applied between the initial review and this re-review (commit 376aafa):
| v1 Finding | Status | Details |
|---|---|---|
| Hardcoded DB password in git | FIXED | config.php → gitignored, only .example remains |
| Flask API duplicating PHP API | FIXED | Entire api/app.py + systemd service + Flask deps removed |
| SSL fix duplicated 7 times | PARTIAL | Moved to run.sh. But 2 files still have it: fetch.py, report.py |
| XSS via city names | PARTIAL | escapeHtml() added + used in search results. NOT used in city manager list, user menu, or tab rendering |
| CSP headers missing | FIXED | Added to index.html + both templates |
fetch_all_models() too strict | FIXED | Now tolerates failures, requires ≥3 models |
bashrc.user in repo | FIXED | Removed + gitignored |
| Silent DB fallback | FIXED | config.py now logs warning when DB fails |
Unused import os in some scripts | PARTIAL | Removed from 5 files; still unused in weather-history.py, evaluate-routes.py, headache-analyzer.py |
| LIKE wildcards unescaped | NOT FIXED | Still present in cities.php line 112 |
| No rate limiting on auth | NOT FIXED | Still no rate limiting on login/register |
2. Updated Scores
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):
- 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); } - Better: Exponential backoff per email (1s, 2s, 4s, 8s…) + IP-level cap (20/hour)
- 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:
| File | Line | Expression |
|---|---|---|
| user.js | 320 | ${currentUser.display_name || 'User'} |
| user.js | 321 | ${currentUser.email} |
| user.js | 368 | ${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.pyscripts/model-validator/evaluate-routes.pyscripts/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
fetch_all_models()is now fault-tolerant — requires ≥3 models, logs warnings for failures instead of hard-crashing. This means a single model API outage doesn't break all forecast generation. ✅- DB fallback is now visible —
config.pylogs a warning when falling back to defaults, making configuration issues discoverable in cron output. ✅
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
| Component | Test Coverage | Risk |
|---|---|---|
| shared/ (config, headaches, model_selector) | Good — unit tests for all public functions | Low |
| Forecast data parsing + scoring | Good — TestComputeErrors, TestRainAccuracy, TestParseForecast | Low |
| Import/compile smoke tests | All .py files verified compilable | Low |
| render.py (629 LOC) | None | Medium — template changes could silently break output |
| PHP API (auth, cities, log-route) | None | High — 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) | None | Low (manual verification via --dry-run is adequate for a personal project) |
6.2 Recommended Next Tests
- render.py fixture test: Call
render_html()with mock data, assert output contains expected sections and no Python exceptions. - 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.
- escapeHtml unit test: Verify it handles
<>&"'correctly (add to test_current_weather.py).
7. Operations
7.1 Improved
- Single deployment target: rsync no longer excludes
api/— there's no API directory to protect on the Pi side. - SSL cert fix centralized in
run.sh: Set once before Python runs, inherited by all subprocesses. - Reduced dependencies:
requirements.txtwent from 5 packages to 2 (markdown + pymysql). Flask, flask-limiter, and gunicorn removed.
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)
- Clean responsive design, bilingual (EN/HU), theme system
- CSP headers now in place ✅
- Progressive enhancement: static pages work without JS
escapeHtml()utility function available for XSS prevention
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)
| # | Fix | File | Effort |
|---|---|---|---|
| 1 | Add rate limiting to login endpoint | auth.php | 10 min + schema change |
| 2 | Apply escapeHtml() to remaining 3 innerHTML locations | user.js:320,321,368 | 2 min |
| 3 | Escape LIKE wildcards in city search | cities.php:112 | 1 min |
🟡 Do Soon (30 min total)
| # | Fix | File | Effort |
|---|---|---|---|
| 4 | Remove residual SSL fix from fetch.py + report.py | 2 files | 1 min |
| 5 | Remove unused import os from 3 files + clean ruff per-file-ignores | 3 files + ruff.toml | 3 min |
| 6 | Delete empty SSL comment block from run-and-publish.py | run-and-publish.py:33-35 | 30 sec |
| 7 | Add *.tile.openstreetmap.org to CSP img-src (or route-weather needs own CSP) | index.html + templates | 2 min |
| 8 | Add defer to all 6 script tags | index.html | 1 min |
| 9 | Define escapeHtml() inside city-nav.js IIFE (avoid global dependency) | city-nav.js | 2 min |
| 10 | Add expired session cleanup to weekly cron | crontab or run.sh | 2 min |
🟢 Do Eventually (quality of life)
- Create
pyproject.tomlfor proper Python packaging (eliminate sys.path hacks) - Add render.py fixture test
- Add PHP API smoke test (curl script)
- Add "last updated" timestamp to frontend pages
- Add accessibility improvements (aria-labels, focus trapping)
- Batch DB cleanup with LIMIT to avoid long locks
- Add rate limiting to registration endpoint
- 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.