# SiteWatch

Monitor and maintain your own websites from one dashboard.

- **Uptime**: response time, TTFB, SSL expiry, "up but broken" detection
- **Server**: CPU, RAM, swap, disk, network throughput, connections
- **Maintenance**: clear temp / sessions / cache, trim big logs, reset OPcache
- **Database**: table sizes, fragmentation, slow queries, optimize
- **Logs & backups**: error log viewer, backup freshness check
- **Alerts** (email + dashboard) and a full **audit log** of every action
- **Live view**: the Overview tiles and the activity feed update themselves, and
  the Cleanup page shows the cleaner working in real time (see "Live view" below)

```
 dashboard/   -> install ONCE (its own subdomain, e.g. monitor.yourdomain.com)
   stream.php     live event stream (SSE) behind the dashboard login
   assets/        live.js, the browser side of it
 agent/       -> install on EACH site you want server metrics/maintenance for
 cleaner/     -> runs from YOUR crontab; does the deleting the web user cannot
```

Requires PHP 8.0+ with `curl`, `pdo_sqlite`, `openssl`. The dashboard uses SQLite,
so it keeps working even if your MySQL goes down.

---

## 1. Install the dashboard

1. Upload `dashboard/` to e.g. `/var/www/sitewatch/`, serve it on its own **HTTPS** subdomain.
2. Make `data/` writable by the web user:
   ```
   chown -R www-data:www-data /var/www/sitewatch/data
   chmod 700 /var/www/sitewatch/data
   ```
3. Create the config:
   ```
   cd /var/www/sitewatch
   cp config.sample.php config.php
   php -r "echo password_hash('YOUR-STRONG-PASSWORD', PASSWORD_DEFAULT);"
   ```
   Paste the hash into `config.php` (`admin_pass_hash`), set `admin_user`, and `alert_email`.
   Then lock it down — note it must stay **readable by the web user**, so group-read,
   not `600`:
   ```
   chgrp www-data config.php && chmod 640 config.php
   ```
4. **Nginx users**: `.htaccess` is ignored. Add this so private folders are never served:
   ```
   location ~ ^/(data|lib|cron|views)/ { deny all; }
   location = /config.php { deny all; }
   ```
   Leave `/assets/` servable — `live.js` is fetched from there. Also make sure
   nothing in front of PHP buffers responses, or the live view silently degrades
   to polling: `proxy_buffering off;` for `stream.php` (it already sends
   `X-Accel-Buffering: no`).
   (The code also refuses direct access itself, but block them anyway.)
5. Add the collector to cron (runs every minute). In `/etc/cron.d/sitewatch`:
   ```
   * * * * * www-data /usr/bin/php /var/www/sitewatch/cron/collect.php >> /var/log/sitewatch.log 2>&1
   ```
   No root? Use your own `crontab -e` instead — but set `umask 0002` first, so the
   SQLite WAL files it creates stay group-writable for the web user:
   ```
   * * * * * umask 0002; /usr/bin/php /var/www/sitewatch/dashboard/cron/collect.php >> ~/logs/sitewatch.log 2>&1
   ```
   `data/` must then be setgid (`chgrp www-data data && chmod 2770 data`) so both
   users share the files. Without the collector cron, every site page just says
   "No agent data yet".
6. Open `https://monitor.yourdomain.com/`, log in.

## 2. Install the agent on each site

1. Generate a secret (one per site):
   ```
   php -r "echo bin2hex(random_bytes(32));"
   ```
2. Upload `agent/agent.php` as `sw-agent.php` into the site's web root.
3. Copy `sw-agent.config.sample.php` next to it as `sw-agent.config.php` and edit:
   - `secret` (same value you enter in the dashboard)
   - `allowed_ips` -> the dashboard server's public IP (strongly recommended)
   - the directory lists (see "Choosing directories" below)
4. Lock the config down. It is read by PHP running as the **web user**, so it needs
   group-read — `chmod 600` gives a blank HTTP 500 and the dashboard reports
   "agent unreachable: bad response (HTTP 500)":
   ```
   chgrp www-data sw-agent.config.php && chmod 640 sw-agent.config.php
   ```
5. In the dashboard: **Manage sites -> Add site**, fill the site URL, agent URL
   (`https://yoursite.com/sw-agent.php`) and secret, then click **Test**.

### Choosing directories (IMPORTANT)
The agent deletes files only inside directories you list. Be exact.
- `temp_dirs`: a folder that only ever holds throwaway files
- `cache_dirs`: your app's cache folder
- `session_dirs`: PHP's session save path (`php -i | grep session.save_path`)
- **Never** list a folder containing uploads, invoices, or anything you can't regenerate.
- Directories you point at must be writable by the PHP user, or deletion silently frees nothing.

### Database access (least privilege)
Do NOT reuse your app's DB user. Create a dedicated one:
```sql
CREATE USER 'sw_monitor'@'127.0.0.1' IDENTIFIED BY 'long-random-password';
GRANT SELECT ON your_database.* TO 'sw_monitor'@'127.0.0.1';
GRANT SELECT ON performance_schema.* TO 'sw_monitor'@'127.0.0.1';
GRANT PROCESS ON *.* TO 'sw_monitor'@'127.0.0.1';
```
`OPTIMIZE TABLE` needs `SELECT` + `INSERT` on the tables; if you want that button,
add `GRANT INSERT ON your_database.* ...`. Skip it if you'd rather run OPTIMIZE by hand.
For the slow-query panel: `SET GLOBAL performance_schema` must be ON in `my.cnf`
(`performance_schema=ON`, needs restart).

---

## Security model (read this)

### Hardening applied

**Transport & proxy.** TLS terminates upstream, so Apache only ever sees plain
HTTP on `:80` and `REMOTE_ADDR` is the proxy. `'trusted_proxies'` in
`config.php` lists who may speak for the client; `X-Forwarded-Proto` and
`X-Forwarded-For` are honoured **only** from those addresses. Two things
depended on it:

- the session cookie now carries `Secure` (it did not before — the admin
  cookie was allowed onto a plaintext connection),
- the login throttle and audit log now record the real visitor instead of
  attributing every request on the box to the proxy's own IP.

**Headers.** Set by PHP (`sw_security_headers()` in `lib/core.php`) so they hold
on any web server, and repeated in the vhost with `Header unset` + `Header
always set` so static files and Apache-generated error pages are covered without
shipping each header twice:

| Header | Value |
|---|---|
| `Content-Security-Policy` | `default-src 'self'`, per-request `nonce` for scripts, `frame-ancestors 'none'`, `base-uri 'none'`, `object-src 'none'`, `form-action 'self'` |
| `Strict-Transport-Security` | 1 year, `includeSubDomains` (only when the proxy reports https) |
| `X-Frame-Options` / `X-Content-Type-Options` | `DENY` / `nosniff` |
| `Referrer-Policy` / `Permissions-Policy` | `no-referrer` / sensors and capture APIs disabled |
| `Cross-Origin-Opener-Policy` / `-Resource-Policy` | `same-origin` |
| `Cache-Control` | `no-store` on every PHP response |

The CSP carries **no `unsafe-inline` for scripts** — all eleven inline
`onclick`/`onsubmit` handlers were converted to delegated `addEventListener`
so the policy could stay strict. `style-src` still allows inline styles,
because the markup leans on `style=""` attributes, which cannot execute script.
Adding a new inline `<script>` means giving it `nonce="<?= h(sw_nonce()) ?>"`,
and inline `on*=` attributes will simply not fire.

**Session.** `__Host-` cookie prefix over https (no `Domain`, so a neighbouring
subdomain cannot plant a session for this host), `HttpOnly`, `SameSite=Strict`,
id regenerated on login and every 15 minutes, bound to a fingerprint of the
browser and the password hash — so a stolen cookie replayed elsewhere, or one
issued before a password change, is rejected. 2 h idle timeout, which the live
stream deliberately does not refresh.

**Login.** CSRF token, lockout after 5 failures per IP per 15 min, `password_verify`
always executed so timing does not reveal whether the username matched, one
generic error, and a randomised 0.25–0.6 s delay on failure.

**Abuse.** `?mode=probe` fans out to every monitored site, so the dashboard
enforces its own floor of one probe per 0.5 s per session — a runaway tab or a
hijacked session cannot turn this into a load generator aimed at your sites.

**Filesystem.** `data/`, `lib/`, `cron/` and `views/` are denied in the vhost;
`assets/` is served static-only with the PHP engine switched off; `*.sample.php`
and a long list of data/backup extensions are blocked; dotfiles are refused by
rewrite.

### Known gaps

- The `Server:` banner still carries the Apache version. Only server-scope
  `ServerTokens` suppresses that; it is not settable from a vhost and needs root.
- Site secrets remain plaintext in SQLite (see below) — the dashboard must be
  able to sign with them unattended.
- There is one admin account; there is no 2FA.


The agent can delete files, so it is treated as a high-value target:
- Every request is **HMAC-SHA256 signed** with the shared secret and must be < 60 s old.
- Optional **IP allowlist** so only the dashboard can call it.
- **Fixed action whitelist.** No action accepts a path from the network; all paths come
  from the local config file.
- Deletion **never follows symlinks**, re-checks every path stays inside its root, refuses
  system roots (`/`, `/etc`, `/var`...), never deletes the root folder itself, and only
  deletes files older than the configured age.
- Dashboard: bcrypt password, CSRF tokens on every state-changing request, login lockout
  (5 failures / 15 min), HttpOnly + SameSite=Strict cookies, 2 h idle timeout, audit log.

What it does NOT protect against:
- If someone steals the shared secret **and** is on your allowlisted IP, they can run the
  whitelisted maintenance actions (not arbitrary code).
- If the dashboard server is compromised, the attacker holds every site's secret
  (stored in plaintext in SQLite). Keep it patched, HTTPS-only, and behind a strong password.
  Consider also restricting the dashboard by IP at the web-server level.
- Always use **HTTPS** for both dashboard and agent URLs. Signatures stop tampering, but
  responses (error-log lines, table names) travel in the clear over HTTP.

## Limits you should know about
- Metrics are read from `/proc` -> **Linux only**.
- "Web connections" counts established TCP connections to ports 80/443, not bandwidth per site.
  Network throughput is **server-wide** (all interfaces), not per website.
- The agent runs as your web-server user, so it only sees what that user can read.
  Apache logs in `/var/log/apache2` are usually root-only; add the web user to the `adm`
  group or point `error_log` at a PHP log the user owns.
- It cannot restart services or edit server config (deliberately, that needs root).
- CPU is sampled over 250 ms per check, so it is a snapshot, not an average.
- History is kept `retention_days` (default 30) at 1-minute resolution.

---

## Cleanup (disk reclaim from the dashboard)

The **Cleanup** tab frees disk space — package caches, stray junk files — from the
browser, with a confirmation step and an audit-log entry.

### Why there is a cron runner

Apache runs as `www-data`. The caches worth reclaiming (`~/.npm`, `~/.cache`) and the
files under `htdocs/` are owned by the login user, and deleting a file needs write
permission on its *containing directory*. `www-data` has none there, so the dashboard
**cannot** delete them itself — and giving it those rights would hand the web server
delete access over the home directory.

Instead the work is split:

| Component | Runs as | Does |
|---|---|---|
| `dashboard/cleanup.php` | `www-data` | Shows sizes, queues a **signed job**. Deletes nothing. |
| `cleaner/run-cleaner.php` | you, via cron | Picks up the job, deletes, writes the result. |
| `dashboard/data/queue/` | shared (`0770`, group `www-data`) | The handoff point. |

The dashboard never sends a path — only a target **id**. Paths exist solely in
`cleaner/cleaner.config.php`, which the runner reads locally.

### Safety rails

- **Signed jobs.** Every job carries an HMAC-SHA256 signature over its canonical JSON.
  Unsigned or forged jobs are refused, so the shared queue dir cannot be abused by
  anything that can write to it.
- **Replay window.** Jobs older than `job_max_age_sec` (default 600s) are refused.
- **Id whitelist.** A target id absent from the config is refused by both sides.
- **`safe_roots` backstop.** Every resolved path must sit inside a declared root.
  `/`, `/etc`, `/home`, `~/.ssh`, and `../` traversal are all refused even if the
  config is edited to name them.
- **No symlink following**, and a `dir_contents` target empties a directory without
  removing the directory itself.
- **`pattern_sweep`** deletes only filenames matching explicit patterns, with an
  optional `max_size` — that is how "empty .sql dumps" targets 0-byte files and
  leaves real backups alone.
- Every run is written to the audit log with the user who requested it.

### Setup

```bash
cp cleaner/cleaner.config.sample.php cleaner/cleaner.config.php
php -r "echo bin2hex(random_bytes(32));"     # paste into 'secret'
chmod 640 cleaner/cleaner.config.php
chgrp www-data cleaner/cleaner.config.php    # dashboard reads the signing key

mkdir -p dashboard/data/queue
chgrp www-data dashboard/data/queue
chmod 2770 dashboard/data/queue              # setgid: new files inherit the group

crontab -e
* * * * * /usr/bin/php /full/path/sitewatch/cleaner/run-cleaner.php >/dev/null 2>&1
```

Edit the `targets` list to match the machine. Then open **Cleanup** in the dashboard.

### Useful commands

```bash
php cleaner/run-cleaner.php --status   # current measurements as JSON
php cleaner/run-cleaner.php --scan     # force a re-measure now
php cleaner/run-cleaner.php            # process the queue (what cron runs)
```

A "runner looks stopped" banner on the page means cron has not checked in recently —
measurements are stale and queued jobs will wait.

---

## Live view

Two pages update themselves rather than waiting for a reload:

| Page | What goes live |
|---|---|
| **Overview** | Each site tile (up/down, HTTP code, response time, 24 h uptime, SSL days, CPU/RAM/swap/disk bars) plus an **activity feed** of maintenance actions, uptime checks and alerts as they land. |
| **Overview — per-site latency** | Every site tile carries its own live tape: current round trip in ms, tick-to-tick deviation, session low/high/mean/jitter and connect time, drawn as a scrolling trace that turns red when the site is not answering 2xx/3xx. |
| **Cleanup** | What `run-cleaner.php` is doing right now — phase, per-target progress bars, running totals, and the runner's own log — then the result when it finishes. |

Both are fed by `dashboard/stream.php` over [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events),
with `dashboard/assets/live.js` on the browser side.

```
 cron -> collect.php ---> monitor.sqlite --                                            >--- stream.php ---SSE---> live.js -> the page
 cron -> run-cleaner.php -> activity.json -/
```

### How it behaves

- **Read-only.** `stream.php` is a GET that never writes, so it carries no CSRF
  token. Keep it that way if you extend it.
- **It does not keep you logged in.** The stream reads the session without
  refreshing the idle timer, so a tab left open overnight still times out after
  2 h — it then shows `session expired — reload`.
- **Reconnects are lossless.** Each event carries a cursor, so a dropped
  connection resumes from the last row the browser actually received. Rows can
  arrive twice after a reconnect; the page dedupes them.
- **It falls back to polling.** If something in front of Apache buffers the
  stream, `live.js` notices it never opened and switches to
  `stream.php?mode=json` every 3 s. The status pill says `polling` when that happens.
- **It lets go of the worker.** Apache here is prefork with mod_php, so every
  open stream is one busy process. Each connection closes itself after 5 minutes
  (the browser reconnects), and a tab hidden for 30 s drops the connection
  entirely. Budget one worker per open dashboard tab; `MaxRequestWorkers` is 150
  by default, so this is not a concern unless you leave dozens of tabs open.

### Where the millisecond data comes from

The uptime checks come from cron, so they move **once a minute** — there is no
millisecond-resolution series in them to draw. `stream.php?mode=probe` provides
one: it HEADs every enabled site and reports the timing.

All sites go out together through `curl_multi`, so one browser request per tick
covers the whole dashboard and holds **one** Apache worker for as long as the
*slowest* site rather than the sum of them — which matters, because mod_php here
is prefork. Measured on this box: four sites at 60–74 ms each complete in 88 ms
total.

- **HEAD, not GET** — we want the timing, not the payload. A site that rejects
  HEAD will show its status code (405) rather than a latency you can trust.
- **`conn`** is broken out because a PHP request cannot keep a connection pool
  between ticks, so every probe pays a fresh DNS+TCP+TLS setup. Without that
  column the number looks inflated next to what a browser with a warm
  connection sees.
- This is *not* the same measurement as the `Status` line below it. That is the
  cron check — a full GET, once a minute. Showing both as "response" invited a
  false comparison, so the tile no longer prints the cron figure.

Rate is selectable **1 s to 10 s**, default 5 s, remembered per browser. At 5 s
with four sites that is 0.2 requests/second against each site; at 1 s it is one.
Probing stops completely while the tab is hidden, and a tick is skipped if the
previous one is still in flight, so a slow site cannot make requests pile up.

The tape scales its y axis to the 90th percentile, so one stalled probe cannot
flatten the trace, and carries the last reading flat out to the right edge —
time keeps moving between samples, and the usual live-tape convention is to hold
the last value rather than let the trace detach from the edge.

### Time and timezone

Timestamps are stored as unix integers, so storage is timezone-free — the
timezone only affects *display*, and changing it never rewrites data.

- `'timezone'` in `config.php` sets what the dashboard renders in. Default
  `Asia/Kolkata`.
- The header carries a live clock showing **that zone and the server's own
  clock side by side** (they differ here: the box runs UTC). A bare time that
  does not say which zone it is in is worse than none during an incident, so
  both are always visible, with the date in `DD-MM-YYYY`.
- The clock is driven by the **server's** time, not the viewer's. Skew is
  measured at page render from `microtime()` and refined from the probe
  response, so a laptop with a wrong clock still reads the right time.
- Formats live in one place: `SW_FMT_DT` / `SW_FMT_SHORT` / `SW_FMT_TIME` in
  `lib/core.php` for PHP, and `SW.fmtTime` / `fmtHM` / `fmtDate` / `fmtDateTime`
  in `views/layout.php` for the browser. `live.js` and the site charts call
  through the JS helpers rather than formatting dates themselves, so a row in
  the live feed reads identically to the same instant printed on the audit page.
- The JS helpers build their output from `Intl.DateTimeFormat.formatToParts`,
  not a locale string — that is the only way to guarantee `DD-MM-YYYY` order and
  an uppercase `AM`/`PM` whatever locale the browser is set to.
- Hovering a timestamp on the Audit and Alerts pages shows the same instant on
  the server clock.

### Notes

- Deleting is usually *faster* than measuring. On a reasonably quick disk 40 k
  small files disappear in well under a second, so what you actually watch on the
  Cleanup page is the measure pass and the runner's log — the per-target bars may
  jump straight to 100 %. That is the job being fast, not the view being broken.
- Progress bars are drawn against the **last measurement**. A target that grew
  since the last scan can read over 100 % briefly; it is clamped.
- Alert *resolution* is an UPDATE, not a new row, so it does not appear in the
  feed. The open-alerts count next to the page title does track it.
- `activity.json` carries only target ids, labels and counters — never a
  filesystem path, the same rule the job queue follows.
- All motion is gated behind `prefers-reduced-motion: reduce`. Under it, values
  still update — they just arrive instantly, with no counting, flashing or
  scrolling. If you add a new animated value, gate it the same way.
