Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
783b0cba3e | ||
|
|
f4b295f582 |
No files matched your search
+19
-1
@@ -6,6 +6,24 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.0] - 2026-11-14
|
||||
|
||||
### Added
|
||||
|
||||
- **New interface:** a side rail with seven pages (Overview, Threats, Geography, Live, Traffic, IPs, Sources and hosts), an opening sentence on every page with the number that matters, the active slice (range, host, domain) always written under the title, an IP detail drawer, and light and dark themes from design tokens.
|
||||
- **Geography page:** a world map by attacker country; select a country to see its states or regions and cities (cities as circles on the zoomed country), the categories and the top IPs; select a region to narrow cities and IPs. The view lives in the URL (`#/geo/BR/Pernambuco`).
|
||||
- **Live page:** attacks drawn as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, with rate, categories, servers, recent origins and the latest events; filters, pause and full screen. It opens by replaying the latest events, so it is never still on a quiet server.
|
||||
- **API:** `GET /api/v1/geo` (countries, or one country with regions, cities and `top_ips`), `GET /api/v1/live/recent`, and `host`, `src` and `dst` on every live event.
|
||||
- **Live federation:** the hub keeps `GET /api/v1/peer/stream` open on each peer and relays their live events, bounded and sanitized.
|
||||
- **`--location` / `URUTAU_LOCATION`:** the position of the instance on the map.
|
||||
- **`--peer-blocklist` / `URUTAU_PEER_BLOCKLIST`** (`on` by default): `off` keeps the hub's blocklist to local observations.
|
||||
|
||||
### Security
|
||||
|
||||
- Events and summary rows from peers are rebuilt from validated fields (address, country code, category); `forged` and `unban` flags from peers are ignored.
|
||||
- The live relay disconnects a peer that sends more than about 1 MB/s, on top of the event rate cap.
|
||||
- Static files are served from the embedded directory by a strict name pattern.
|
||||
|
||||
## [1.0.0] - 2026-11-14
|
||||
|
||||
First release.
|
||||
@@ -22,7 +40,7 @@ First release.
|
||||
- Federation: `--peer name=https://url` aggregates other instances. A hub only calls `GET /api/v1/peer/export?range=1h|24h|7d` (`{"v":1,"summary":...,"traffic":{...}}`, top 500 IPs with detail, cached 5 s) every 15 s, with a 4 s timeout, an 8 MB limit, no redirects, `https` required outside loopback, and sanitized, capped peer data. `--peer-allow` / `URUTAU_PEER_ALLOW` limits the source CIDRs of the export.
|
||||
- Offline geolocation (country, city, ASN) from the DB-IP Lite databases (CC BY 4.0), downloaded and refreshed by Urutau (`--geo-dir`, `--geo-update`) and read by a built-in, dependency-free MMDB reader.
|
||||
- User-Agent parsing into browser, operating system, device, bots and attack tools.
|
||||
- Privacy-friendly web analytics for legitimate traffic (Traffic tab): unique visitors by a daily-salted hash, pages, referrers, countries, browsers, devices, latency p50 and p95, bytes and a world map. The IP of a legitimate visitor is never persisted. Threats and Traffic are separate tabs.
|
||||
- Privacy-friendly web analytics for legitimate traffic (Traffic page): unique visitors by a daily-salted hash, pages, referrers, countries, browsers, devices, latency p50 and p95, bytes and a world map. The IP of a legitimate visitor is never persisted. Threats and Traffic are separate pages.
|
||||
- Reverse DNS enrichment of listed IPs.
|
||||
- Noise filters: `--trusted` / `URUTAU_TRUSTED` (alias `--ignore`) drops events from trusted CIDRs, and `--monitor-ua` / `URUTAU_MONITOR_UA` keeps benign monitoring requests (such as Uptime-Kuma) out of the traffic numbers.
|
||||
- `urutau doctor [--json]` to check the configuration, the sources, the data directory, the geolocation databases and the snapshot; the JSON output carries `geo` and `state`.
|
||||
|
||||
+19
-1
@@ -6,6 +6,24 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.1.0] - 2026-11-14
|
||||
|
||||
### Adicionado
|
||||
|
||||
- **Interface nova:** trilho lateral com sete páginas (Visão geral, Ameaças, Geografia, Ao vivo, Tráfego, IPs, Fontes e hosts), uma frase de abertura em cada página com o número que importa, o recorte ativo (intervalo, host, domínio) sempre escrito sob o título, painel de detalhe de IP e temas claro e escuro a partir de tokens de design.
|
||||
- **Página Geografia:** mapa-múndi por país de origem dos ataques; selecione um país para ver estados ou regiões e cidades (cidades como círculos no país ampliado), as categorias e os IPs principais; selecione uma região para filtrar cidades e IPs. A vista fica na URL (`#/geo/BR/Pernambuco`).
|
||||
- **Página Ao vivo:** ataques desenhados como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, com ritmo, categorias, servidores, origens recentes e os últimos eventos; filtros, pausa e tela cheia. Ela abre reproduzindo os últimos eventos, então nunca fica parada num servidor calmo.
|
||||
- **API:** `GET /api/v1/geo` (países, ou um país com regiões, cidades e `top_ips`), `GET /api/v1/live/recent`, e `host`, `src` e `dst` em cada evento ao vivo.
|
||||
- **Federação ao vivo:** o hub mantém `GET /api/v1/peer/stream` aberto em cada peer e repassa os eventos ao vivo deles, com limites e sanitização.
|
||||
- **`--location` / `URUTAU_LOCATION`:** a posição da instância no mapa.
|
||||
- **`--peer-blocklist` / `URUTAU_PEER_BLOCKLIST`** (`on` por padrão): `off` restringe a blocklist do hub às observações locais.
|
||||
|
||||
### Segurança
|
||||
|
||||
- Eventos e linhas de resumo vindos de peers são reconstruídos a partir de campos validados (endereço, código de país, categoria); os sinalizadores `forged` e `unban` vindos de peers são ignorados.
|
||||
- O repasse ao vivo desconecta um peer que mande mais de cerca de 1 MB/s, além do teto de eventos.
|
||||
- Os arquivos estáticos são servidos do diretório embutido por um padrão de nome estrito.
|
||||
|
||||
## [1.0.0] - 2026-11-14
|
||||
|
||||
Primeira versão.
|
||||
@@ -22,7 +40,7 @@ Primeira versão.
|
||||
- Federação: `--peer nome=https://url` agrega outras instâncias. Um hub só chama `GET /api/v1/peer/export?range=1h|24h|7d` (`{"v":1,"summary":...,"traffic":{...}}`, 500 IPs principais com detalhe, cache de 5 s) a cada 15 s, com timeout de 4 s, limite de 8 MB, sem redirects, `https` obrigatório fora de loopback e dados do peer sanitizados e limitados. `--peer-allow` / `URUTAU_PEER_ALLOW` limita os CIDRs de origem do export.
|
||||
- Geolocalização offline (país, cidade, ASN) a partir das bases DB-IP Lite (CC BY 4.0), baixadas e atualizadas pelo Urutau (`--geo-dir`, `--geo-update`) e lidas por um leitor MMDB embutido e sem dependências.
|
||||
- Interpretação de User-Agent em navegador, sistema operacional, dispositivo, bots e ferramentas de ataque.
|
||||
- Web analytics amigável à privacidade para o tráfego legítimo (aba Tráfego): visitantes únicos por hash com sal diário, páginas, referrers, países, navegadores, dispositivos, latência p50 e p95, bytes e mapa-múndi. O IP de um visitante legítimo nunca é persistido. Ameaças e Tráfego são abas separadas.
|
||||
- Web analytics amigável à privacidade para o tráfego legítimo (página Tráfego): visitantes únicos por hash com sal diário, páginas, referrers, países, navegadores, dispositivos, latência p50 e p95, bytes e mapa-múndi. O IP de um visitante legítimo nunca é persistido. Ameaças e Tráfego são páginas separadas.
|
||||
- Enriquecimento com DNS reverso dos IPs listados.
|
||||
- Filtros de ruído: `--trusted` / `URUTAU_TRUSTED` (alias `--ignore`) descarta eventos de CIDRs confiáveis, e `--monitor-ua` / `URUTAU_MONITOR_UA` mantém requisições benignas de monitoramento (como o Uptime-Kuma) fora dos números de tráfego.
|
||||
- `urutau doctor [--json]` para conferir a configuração, as fontes, o diretório de dados, as bases de geolocalização e o snapshot; a saída JSON traz `geo` e `state`.
|
||||
|
||||
@@ -17,11 +17,11 @@ Urutau is a small panel that runs on each of your servers (as a container), read
|
||||
- **Scores IPs:** every event adds weight to its source IP. A score of 10 or more is **suspicious**; **hostile** needs 50 or more **and** a strong signal (an attack tool, two or more attack categories, a ban, or a clear exploit attempt that was refused). Scanner and exploit probes that got a 2xx or 3xx answer weigh only 0.5. An IP with a successful SSH login is never hostile and never reaches the blocklist.
|
||||
- **Geolocation, offline:** country, city and ASN for every IP from the free DB-IP Lite databases, downloaded and refreshed by Urutau itself, read by a built-in MMDB reader with no dependency. Nothing is looked up online.
|
||||
- **Understands User-Agents:** browser, operating system, device, bots and attack tools.
|
||||
- **Web analytics for legitimate traffic:** unique visitors, pages, referrers, countries, browsers, devices, latency (p50 and p95) and bytes, with a world map, replacing your proxy's analytics. Separate **Threats** and **Traffic** tabs.
|
||||
- **Web analytics for legitimate traffic:** unique visitors, pages, referrers, countries, browsers, devices, latency (p50 and p95) and bytes, with a world map, replacing your proxy's analytics. Separate **Threats** and **Traffic** pages.
|
||||
- **Lightweight:** Go standard library only, one static binary, a soft memory limit of 160 MiB, state in a single snapshot file. No database.
|
||||
- **Live dashboard:** embedded vanilla UI (English and Portuguese, light and dark), updated through Server-Sent Events.
|
||||
- **Live dashboard:** embedded vanilla UI (English and Portuguese, light and dark), updated through Server-Sent Events, with seven pages (see below).
|
||||
- **Blocklist:** hostile, globally routable IPs as plain text or JSON, ready for fail2ban, ipset, nginx or a firewall. IPv6 is aggregated by /64 and exported as `x:x:x:x::/64`.
|
||||
- **Federation:** one instance (the hub) aggregates others with `--peer name=url`, pulling `/api/v1/peer/export`.
|
||||
- **Federation:** one instance (the hub) aggregates others with `--peer name=url`, pulling `/api/v1/peer/export` and relaying their live events through `/api/v1/peer/stream`.
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -39,10 +39,26 @@ Urutau is a small panel that runs on each of your servers (as a container), read
|
||||
dashboard (SSE) /api/v1/* JSON blocklist.txt / .json
|
||||
|
||||
hub ── GET /api/v1/peer/export (peer token) ──► peer A
|
||||
│ ── GET /api/v1/peer/stream (live events) ──► peer A
|
||||
│ ── GET /api/v1/peer/export (peer token) ──► peer B
|
||||
│ ── GET /api/v1/peer/stream (live events) ──► peer B
|
||||
└──► one dashboard for the whole fleet
|
||||
```
|
||||
|
||||
## Interface
|
||||
|
||||
Seven pages, in a side rail, with the view kept in the URL hash:
|
||||
|
||||
- **Overview:** the headline numbers, the timeline and the top IPs.
|
||||
- **Threats:** categories over time, the live feed and the top attacked paths, domains, User-Agents and users.
|
||||
- **Geography:** a world map by attacker country; drill down country, states or regions, cities (`#/geo/BR/Pernambuco`).
|
||||
- **Live:** attacks as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, including the events of your peers. `--location` (`URUTAU_LOCATION`, `"lat,lon"` or `"lat,lon,label"`) sets where this server sits on the map.
|
||||
- **Traffic:** privacy-friendly web analytics for legitimate visitors.
|
||||
- **IPs:** the scored IP table with an IP detail drawer.
|
||||
- **Sources and hosts:** log sources, peers and the blocklist.
|
||||
|
||||
See [docs/interface.md](docs/interface.md).
|
||||
|
||||
## Install
|
||||
|
||||
Run it with Docker Compose (recommended):
|
||||
@@ -87,7 +103,7 @@ Your own infrastructure produces events too. Two filters keep it out of the pict
|
||||
- `--trusted` / `URUTAU_TRUSTED`: CIDRs of trusted origins (your office, your monitors, your other servers). Their events are dropped entirely. `--ignore` remains as an alias.
|
||||
- `--monitor-ua` / `URUTAU_MONITOR_UA`: a regular expression matching monitoring User-Agents (the default includes Uptime-Kuma). A request that matches and is benign is not counted as traffic; it feeds a separate "monitoring" counter. If the same request is a `scanner`, `exploit` or `bruteforce`, it counts as an attack, because a User-Agent is trivial to forge.
|
||||
- `--monitor-from` / `URUTAU_MONITOR_FROM`: CIDRs the monitors really come from. When set, the monitoring User-Agent is honored only from those networks. Without it, only `ok` answers are filtered (a `notfound` from a monitor User-Agent still counts), since anyone can forge the header.
|
||||
- `--domains` / `URUTAU_DOMAINS`: an allowlist of domains for the Traffic tab (exact names or `*.example.com`). A domain only gets a slot after a 2xx answer, and inactive domains are pruned, so random `Host` headers cannot fill the analytics.
|
||||
- `--domains` / `URUTAU_DOMAINS`: an allowlist of domains for the Traffic page (exact names or `*.example.com`). A domain only gets a slot after a 2xx answer, and inactive domains are pruned, so random `Host` headers cannot fill the analytics.
|
||||
|
||||
## Geolocation and attribution
|
||||
|
||||
|
||||
+21
-5
@@ -17,11 +17,11 @@ O Urutau é um painel pequeno que roda em cada um dos seus servidores (como cont
|
||||
- **Pontua IPs:** cada evento soma peso ao IP de origem. Pontuação 10 ou mais é **suspeito**; **hostil** exige 50 ou mais **e** um sinal forte (uma ferramenta de ataque, duas ou mais categorias de ataque, um ban ou uma tentativa clara de exploit recusada). Sondas de scanner e exploit que receberam resposta 2xx ou 3xx pesam só 0,5. Um IP com login SSH bem-sucedido nunca é hostil e nunca vai para a blocklist.
|
||||
- **Geolocalização offline:** país, cidade e ASN de todo IP a partir das bases gratuitas DB-IP Lite, baixadas e atualizadas pelo próprio Urutau, lidas por um leitor MMDB embutido e sem dependências. Nada é consultado online.
|
||||
- **Entende User-Agents:** navegador, sistema operacional, dispositivo, bots e ferramentas de ataque.
|
||||
- **Web analytics do tráfego legítimo:** visitantes únicos, páginas, referrers, países, navegadores, dispositivos, latência (p50 e p95) e bytes, com mapa-múndi, no lugar do analytics do seu proxy. Abas **Ameaças** e **Tráfego** separadas.
|
||||
- **Web analytics do tráfego legítimo:** visitantes únicos, páginas, referrers, países, navegadores, dispositivos, latência (p50 e p95) e bytes, com mapa-múndi, no lugar do analytics do seu proxy. Páginas **Ameaças** e **Tráfego** separadas.
|
||||
- **Leve:** só biblioteca padrão do Go, um binário estático, limite suave de memória de 160 MiB, estado em um único arquivo de snapshot. Sem banco de dados.
|
||||
- **Dashboard ao vivo:** UI vanilla embutida (inglês e português, claro e escuro), atualizada por Server-Sent Events.
|
||||
- **Dashboard ao vivo:** UI vanilla embutida (inglês e português, claro e escuro), atualizada por Server-Sent Events, com sete páginas (veja abaixo).
|
||||
- **Blocklist:** IPs hostis e globalmente roteáveis em texto ou JSON, prontos para fail2ban, ipset, nginx ou firewall. O IPv6 é agregado por /64 e exportado como `x:x:x:x::/64`.
|
||||
- **Federação:** uma instância (o hub) agrega outras com `--peer nome=url`, puxando `/api/v1/peer/export`.
|
||||
- **Federação:** uma instância (o hub) agrega outras com `--peer nome=url`, puxando `/api/v1/peer/export` e repassando os eventos ao vivo deles por `/api/v1/peer/stream`.
|
||||
|
||||
## Como funciona
|
||||
|
||||
@@ -39,10 +39,26 @@ O Urutau é um painel pequeno que roda em cada um dos seus servidores (como cont
|
||||
dashboard (SSE) /api/v1/* JSON blocklist.txt / .json
|
||||
|
||||
hub ── GET /api/v1/peer/export (token de peer) ──► peer A
|
||||
│ ── GET /api/v1/peer/stream (eventos ao vivo) ──► peer A
|
||||
│ ── GET /api/v1/peer/export (token de peer) ──► peer B
|
||||
│ ── GET /api/v1/peer/stream (eventos ao vivo) ──► peer B
|
||||
└──► um dashboard para a frota inteira
|
||||
```
|
||||
|
||||
## Interface
|
||||
|
||||
Sete páginas, numa barra lateral, com a visão guardada no hash da URL:
|
||||
|
||||
- **Visão geral:** os números principais, a linha do tempo e os principais IPs.
|
||||
- **Ameaças:** categorias ao longo do tempo, o feed ao vivo e os principais caminhos atacados, domínios, User-Agents e usuários.
|
||||
- **Geografia:** um mapa-múndi por país do atacante; detalhamento país, estados ou regiões, cidades (`#/geo/BR/Pernambuco`).
|
||||
- **Ao vivo:** ataques como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, incluindo os eventos dos seus peers. `--location` (`URUTAU_LOCATION`, `"lat,lon"` ou `"lat,lon,rótulo"`) define onde este servidor fica no mapa.
|
||||
- **Tráfego:** web analytics amigável à privacidade para visitantes legítimos.
|
||||
- **IPs:** a tabela de IPs pontuados com painel de detalhe do IP.
|
||||
- **Fontes e hosts:** fontes de log, peers e a blocklist.
|
||||
|
||||
Veja [docs/pt-BR/interface.md](docs/pt-BR/interface.md).
|
||||
|
||||
## Instalação
|
||||
|
||||
Rode com Docker Compose (recomendado):
|
||||
@@ -87,7 +103,7 @@ Sua própria infraestrutura também gera eventos. Dois filtros a tiram do quadro
|
||||
- `--trusted` / `URUTAU_TRUSTED`: CIDRs de origens confiáveis (seu escritório, seus monitores, seus outros servidores). Os eventos delas são descartados por completo. `--ignore` continua como alias.
|
||||
- `--monitor-ua` / `URUTAU_MONITOR_UA`: expressão regular de User-Agents de monitoramento (o padrão inclui Uptime-Kuma). Uma requisição que casa e é benigna não conta como tráfego; ela alimenta um contador "monitoring" à parte. Se a mesma requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque, porque um User-Agent é trivial de forjar.
|
||||
- `--monitor-from` / `URUTAU_MONITOR_FROM`: CIDRs de onde os monitores realmente vêm. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes. Sem ele, só respostas `ok` são filtradas (um `notfound` com User-Agent de monitor ainda conta), já que qualquer um pode forjar o cabeçalho.
|
||||
- `--domains` / `URUTAU_DOMAINS`: uma lista de domínios permitidos para a aba Tráfego (nomes exatos ou `*.exemplo.com`). Um domínio só ganha vaga depois de uma resposta 2xx, e domínios inativos são podados, então `Host` aleatórios não enchem o analytics.
|
||||
- `--domains` / `URUTAU_DOMAINS`: uma lista de domínios permitidos para a página Tráfego (nomes exatos ou `*.exemplo.com`). Um domínio só ganha vaga depois de uma resposta 2xx, e domínios inativos são podados, então `Host` aleatórios não enchem o analytics.
|
||||
|
||||
## Geolocalização e atribuição
|
||||
|
||||
@@ -99,7 +115,7 @@ A atribuição também aparece no dashboard. Se você redistribuir as bases ou a
|
||||
|
||||
## Privacidade
|
||||
|
||||
A aba **Tráfego** conta visitantes legítimos sem rastreá-los. Um visitante único é um hash calculado com um sal que muda todo dia, então não acompanha uma pessoa de um dia para o outro, e o endereço IP de um visitante legítimo nunca é persistido: nem no snapshot, nem em log, nem em exportação. Endereços IP são guardados apenas para atividade classificada como hostil, que é o que uma ferramenta de segurança existe para registrar. Sem cookies, fingerprinting nem requisições a terceiros, o desenho dispensa banner de consentimento, mas a licitude do seu uso perante a LGPD ou o GDPR continua sendo decisão sua, como controlador. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
|
||||
A página **Tráfego** conta visitantes legítimos sem rastreá-los. Um visitante único é um hash calculado com um sal que muda todo dia, então não acompanha uma pessoa de um dia para o outro, e o endereço IP de um visitante legítimo nunca é persistido: nem no snapshot, nem em log, nem em exportação. Endereços IP são guardados apenas para atividade classificada como hostil, que é o que uma ferramenta de segurança existe para registrar. Sem cookies, fingerprinting nem requisições a terceiros, o desenho dispensa banner de consentimento, mas a licitude do seu uso perante a LGPD ou o GDPR continua sendo decisão sua, como controlador. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
|
||||
|
||||
## Usando a blocklist
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ Urutau is lightweight, always-on threat intelligence for self-hosted servers: it
|
||||
- **Container and CI/CD (1.0.0):** multi-arch image, Coolify deployment, Gitea CI with an image-reuse release workflow, weekly audit.
|
||||
- **Bilingual documentation (1.0.0).**
|
||||
|
||||
- **Interface and live federation (1.1.0):** seven pages, Geography with country, region and city drill-down, Live arcs on a flat map or a 3D globe, `/api/v1/geo`, `/api/v1/live/recent`, relayed live events from peers (`/api/v1/peer/stream`) and `--location`.
|
||||
|
||||
## Next
|
||||
|
||||
- **More log sources:** other web servers and proxies (nginx, Caddy), and more daemons' auth failures.
|
||||
|
||||
@@ -17,6 +17,8 @@ O Urutau é threat intelligence leve e sempre ligado para servidores self-hosted
|
||||
- **Container e CI/CD (1.0.0):** imagem multi-arquitetura, deploy no Coolify, CI no Gitea com release que reaproveita imagem, auditoria semanal.
|
||||
- **Documentação bilíngue (1.0.0).**
|
||||
|
||||
- **Interface e federação ao vivo (1.1.0):** sete páginas, Geografia com detalhamento por país, região e cidade, arcos Ao vivo em mapa plano ou globo 3D, `/api/v1/geo`, `/api/v1/live/recent`, eventos ao vivo dos peers repassados (`/api/v1/peer/stream`) e `--location`.
|
||||
|
||||
## Próximo
|
||||
|
||||
- **Mais fontes de log:** outros servidores web e proxies (nginx, Caddy) e falhas de autenticação de mais daemons.
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
|
||||
|
||||
- **Hostile log fields:** paths, User-Agents, user names, hosts and jails are length-limited when parsed, kept as data, and escaped when rendered. A malformed, oversized or crafted line must be counted as malformed, never crash the daemon, exhaust memory or inject markup, a command or a script into the dashboard. The dashboard ships a Content-Security-Policy that forbids inline script and style.
|
||||
- **Authentication:** the dashboard and every API route except `/api/health` need `URUTAU_TOKEN` (at least 32 characters and about 128 bits of estimated entropy, compared in constant time; it can come from `URUTAU_TOKEN_FILE`), either as a bearer token or through a login that sets a session cookie (`HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS) valid for 12 hours. The session is revocable: it is a random id kept in memory, logout revokes it and closes its live stream, and a restart invalidates all sessions. Login and logout reject cross-site requests. After 5 failures per 10 minutes from a client (IPv6 counted per /64) the login answers 429, yet the correct token still gets in after a 1 second delay, so an attacker cannot lock the owner out; wrong bearer tokens count as failures too. The client IP comes from the TCP peer; `X-Forwarded-For` is honored only when the peer is in `--trusted-proxy` (default: the private networks), read from right to left, so it cannot be spoofed from outside. Generate tokens with `openssl rand -base64 48` (`-hex 32` also works).
|
||||
- **Peer token:** The server token (`URUTAU_PEER_TOKEN`, also as `_FILE`; 32+ characters, about 128 bits of estimated entropy, not periodic or sequential, different from `URUTAU_TOKEN`) is the only credential the local export accepts, and it only opens `GET /api/v1/peer/export`; every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on the export. Without a peer token the export is a 404. `--peer-allow` restricts the export to source CIDRs. `URUTAU_PEER_TOKEN_<NAME>` values are client credentials a hub sends to that peer; they never open the local export, and peer names that collide in the variable name are refused. A hub refuses to start with a peer that has no token, only talks to the export, requires `https` outside loopback, does not follow redirects, uses a 4 s timeout and an 8 MB limit, and sanitizes and caps everything a peer sends: an `admin` flag coming from a peer is ignored and a peer's `Strong` flag only counts with a score of 50 or more. Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries.
|
||||
- **Peer token:** The server token (`URUTAU_PEER_TOKEN`, also as `_FILE`; 32+ characters, about 128 bits of estimated entropy, not periodic or sequential, different from `URUTAU_TOKEN`) is the only credential the local export accepts, and it only opens the two federation routes, `GET /api/v1/peer/export` and the live stream `GET /api/v1/peer/stream` (at most 10 connections, malicious events only); every other route answers 403 to it, and `URUTAU_TOKEN` is refused (401) on both. Without a peer token they are a 404. `--peer-allow` restricts both to source CIDRs. `URUTAU_PEER_TOKEN_<NAME>` values are client credentials a hub sends to that peer; they never open the local export, and peer names that collide in the variable name are refused. A hub refuses to start with a peer that has no token, only talks to those two routes, requires `https` outside loopback, does not follow redirects, uses a 4 s timeout and an 8 MB limit, and sanitizes and caps everything a peer sends: an `admin` flag coming from a peer is ignored and a peer's `Strong` flag only counts with a score of 50 or more. The live relay from each peer is capped at about 50 events per second and about 1 MB/s (a peer that sends more is disconnected), lines of at most 16 KB, a 500-event buffer, reconnection with exponential backoff up to 60 s, and every relayed event is rebuilt from validated fields (address, known category, clipped strings without control characters, valid coordinates; the `host` is always the configured peer name). A compromised peer can still add hostile-looking global IPs to the hub's blocklist (only with score 50+ and a strong signal; `admin` and `forged` flags from peers are ignored); set `URUTAU_PEER_BLOCKLIST=off` to keep the blocklist to local observations. Treat a peer as able to read the top 500 IPs, paths and traffic figures its export carries, and its live attack events.
|
||||
- **HTTP server limits:** header and body timeouts, `MaxHeaderBytes` of 16 KB, `POST /login` capped at 4 KB, and at most 20 simultaneous live-stream clients (a 21st gets 503 with `Retry-After`; the stream sends a heartbeat every 20 s).
|
||||
- **Information exposure:** `/api/health` returns only `{"status":"ok"}` (no version), log file paths are never shown in the dashboard or to peers, responses carry `Referrer-Policy: same-origin` and a strict Content-Security-Policy.
|
||||
- **Framed requests:** with the `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` headers in the Traefik log, a request embedded by another page (cross-site or same-site, or a sub-resource destination such as image or script) creates an IP record like any other but weighs 0.25 per event, with at most 30 points per IP from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored. The headers come from the client, so a framed visitor never becomes hostile, and a scanner that forges them shows up as suspicious instead of vanishing.
|
||||
@@ -22,7 +22,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
|
||||
- **Container hardening:** the image runs as an unprivileged user (no `curl` or shell tools needed: its `HEALTHCHECK` is `urutau healthcheck`) with a read-only root filesystem and no capabilities. Logs are mounted read-only, and only the Traefik log directory is mounted from the proxy, never `acme.json` or its configuration. Logs come from a dedicated host directory, `/var/log/urutau`, not the whole `/var/log`. `--trusted-proxy` defaults to loopback only; the compose file creates the `urutau-edge` network (`10.250.0.0/24`) and trusts just that, so keep only the reverse proxy on it, since another container there could forge `X-Forwarded-For`. The only write target is the data volume (snapshot, mode `0700` directory).
|
||||
- **Read-only by design:** Urutau reads logs and never sends traffic to the IPs it lists. The only outbound connections are reverse DNS lookups, the periodic download of the DB-IP Lite databases from `download.db-ip.com` (verified by opening the file before it replaces the old one; a failure never stops the service) and, on a hub, the polls to the configured peers. Geolocation lookups are local.
|
||||
- **Privacy and local-first:** there is no telemetry. IPs and request details stay on your servers (and on the hub you configure).
|
||||
- **Visitor privacy (LGPD and GDPR):** the Traffic tab counts unique visitors with a hash computed with a daily salt, so a visitor cannot be followed across days, and the IP address of a legitimate visitor is never persisted. There are no cookies for visitors, no fingerprinting and no request to third parties. IPs are retained only for hostile activity, for at most the retention period (7 days). Whether this is enough for your legal basis and notices is your responsibility as the controller.
|
||||
- **Visitor privacy (LGPD and GDPR):** the Traffic page counts unique visitors with a hash computed with a daily salt, so a visitor cannot be followed across days, and the IP address of a legitimate visitor is never persisted. There are no cookies for visitors, no fingerprinting and no request to third parties. IPs are retained only for hostile activity, for at most the retention period (7 days). Whether this is enough for your legal basis and notices is your responsibility as the controller.
|
||||
- **Third-party data:** the geolocation databases are DB-IP Lite, CC BY 4.0, and the attribution must be kept where the data is shown.
|
||||
|
||||
## Known limitation
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
|
||||
|
||||
- **Campos hostis de log:** caminhos, User-Agents, usuários, hosts e jails têm tamanho limitado no parse, são mantidos como dado e escapados ao renderizar. Uma linha malformada, gigante ou forjada deve ser contada como malformada, nunca derrubar o daemon, esgotar memória ou injetar marcação, comando ou script no dashboard. O dashboard envia uma Content-Security-Policy que proíbe script e estilo inline.
|
||||
- **Autenticação:** o dashboard e toda rota da API, exceto `/api/health`, exigem `URUTAU_TOKEN` (no mínimo 32 caracteres e cerca de 128 bits de entropia estimada, comparado em tempo constante; pode vir de `URUTAU_TOKEN_FILE`), como bearer token ou por um login que define um cookie de sessão (`HttpOnly`, `SameSite=Strict`, `Secure` em HTTPS) válido por 12 horas. A sessão é revogável: é um id aleatório guardado em memória, o logout a revoga e fecha o stream ao vivo dela, e um reinício invalida todas as sessões. Login e logout rejeitam requisições cross-site. Após 5 falhas a cada 10 minutos de um cliente (IPv6 contado por /64) o login responde 429, mas o token correto ainda entra após 1 segundo de atraso, para que um atacante não tranque o dono do lado de fora; bearer tokens errados também contam como falha. O IP do cliente vem do peer TCP; `X-Forwarded-For` só vale quando o peer está em `--trusted-proxy` (padrão: as redes privadas), lido da direita para a esquerda, então não pode ser forjado de fora. Gere tokens com `openssl rand -base64 48` (`-hex 32` também serve).
|
||||
- **Token de peer:** O token de servidor (`URUTAU_PEER_TOKEN`, também via `_FILE`; 32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial, diferente de `URUTAU_TOKEN`) é a única credencial que o export local aceita, e só abre `GET /api/v1/peer/export`; todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) no export. Sem token de peer o export é 404. `--peer-allow` restringe o export a CIDRs de origem. Os valores `URUTAU_PEER_TOKEN_<NOME>` são credenciais de cliente que um hub envia àquele peer; nunca abrem o export local, e nomes de peer que colidem no nome da variável são recusados. Um hub se recusa a iniciar com um peer sem token, só fala com o export, exige `https` fora de loopback, não segue redirects, usa timeout de 4 s e limite de 8 MB, e sanitiza e limita tudo o que um peer envia: um sinalizador `admin` vindo de um peer é ignorado e o `Strong` de um peer só vale com pontuação 50 ou mais. Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega.
|
||||
- **Token de peer:** O token de servidor (`URUTAU_PEER_TOKEN`, também via `_FILE`; 32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial, diferente de `URUTAU_TOKEN`) é a única credencial que o export local aceita, e só abre as duas rotas de federação, `GET /api/v1/peer/export` e o fluxo ao vivo `GET /api/v1/peer/stream` (no máximo 10 conexões, só eventos maliciosos); todas as outras rotas respondem 403 a ele, e o `URUTAU_TOKEN` é recusado (401) nas duas. Sem token de peer elas são 404. `--peer-allow` restringe as duas a CIDRs de origem. Os valores `URUTAU_PEER_TOKEN_<NOME>` são credenciais de cliente que um hub envia àquele peer; nunca abrem o export local, e nomes de peer que colidem no nome da variável são recusados. Um hub se recusa a iniciar com um peer sem token, só fala com essas duas rotas, exige `https` fora de loopback, não segue redirects, usa timeout de 4 s e limite de 8 MB, e sanitiza e limita tudo o que um peer envia: um sinalizador `admin` vindo de um peer é ignorado e o `Strong` de um peer só vale com pontuação 50 ou mais. O repasse ao vivo de cada peer é limitado a cerca de 50 eventos por segundo e cerca de 1 MB/s (um peer que manda mais é desconectado), linhas de no máximo 16 KB, buffer de 500 eventos e reconexão com backoff exponencial até 60 s, e cada evento repassado é reconstruído a partir de campos validados (endereço, categoria conhecida, textos cortados e sem caracteres de controle, coordenadas válidas; o `host` é sempre o nome configurado do peer). Um peer comprometido ainda pode pôr IPs globais com cara de hostis na blocklist do hub (só com pontuação 50+ e sinal forte; os sinalizadores `admin` e `forged` vindos de peers são ignorados); defina `URUTAU_PEER_BLOCKLIST=off` para restringir a blocklist às observações locais. Trate um peer como alguém que pode ler os 500 IPs principais, caminhos e números de tráfego que o export carrega, e os seus eventos de ataque ao vivo.
|
||||
- **Limites do servidor HTTP:** timeouts de cabeçalho e corpo, `MaxHeaderBytes` de 16 KB, `POST /login` limitado a 4 KB e no máximo 20 clientes simultâneos no stream ao vivo (o 21º recebe 503 com `Retry-After`; o stream envia heartbeat a cada 20 s).
|
||||
- **Exposição de informação:** `/api/health` devolve só `{"status":"ok"}` (sem versão), os caminhos dos arquivos de log nunca aparecem no dashboard nem para peers, e as respostas levam `Referrer-Policy: same-origin` e uma Content-Security-Policy estrita.
|
||||
- **Requisições enquadradas:** com os cabeçalhos `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` no log do Traefik, uma requisição embutida por outra página (cross-site ou same-site, ou destino de subrecurso como image ou script) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados. Os cabeçalhos vêm do cliente, então um visitante enquadrado nunca vira hostil, e um scanner que os forja aparece como suspeito em vez de sumir.
|
||||
@@ -22,7 +22,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
|
||||
- **Endurecimento do container:** a imagem roda com usuário sem privilégios (sem `curl` nem ferramentas de shell: o `HEALTHCHECK` é `urutau healthcheck`), sistema de arquivos raiz somente leitura e sem capabilities. Os logs são montados somente leitura, e do proxy só o diretório de logs do Traefik é montado, nunca o `acme.json` nem a configuração. Os logs vêm de um diretório dedicado do host, `/var/log/urutau`, não do `/var/log` inteiro. `--trusted-proxy` tem como padrão só o loopback; o compose cria a rede `urutau-edge` (`10.250.0.0/24`) e confia só nela, então deixe nela apenas o proxy reverso, pois outro container ali poderia forjar o `X-Forwarded-For`. O único destino de escrita é o volume de dados (snapshot, diretório com modo `0700`).
|
||||
- **Somente leitura por desenho:** o Urutau lê logs e nunca envia tráfego aos IPs que lista. As únicas conexões de saída são as consultas de DNS reverso, o download periódico das bases DB-IP Lite em `download.db-ip.com` (verificado abrindo o arquivo antes de substituir o antigo; uma falha nunca interrompe o serviço) e, em um hub, as consultas aos peers configurados. As consultas de geolocalização são locais.
|
||||
- **Privacidade e local-first:** não há telemetria. IPs e detalhes de requisições ficam nos seus servidores (e no hub que você configurar).
|
||||
- **Privacidade dos visitantes (LGPD e GDPR):** a aba Tráfego conta visitantes únicos com um hash calculado com sal diário, então um visitante não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. Não há cookies para visitantes, fingerprinting nem requisição a terceiros. IPs são retidos apenas para atividade hostil, por no máximo o período de retenção (7 dias). Se isso basta para a sua base legal e seus avisos é responsabilidade sua, como controlador.
|
||||
- **Privacidade dos visitantes (LGPD e GDPR):** a página Tráfego conta visitantes únicos com um hash calculado com sal diário, então um visitante não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. Não há cookies para visitantes, fingerprinting nem requisição a terceiros. IPs são retidos apenas para atividade hostil, por no máximo o período de retenção (7 dias). Se isso basta para a sua base legal e seus avisos é responsabilidade sua, como controlador.
|
||||
- **Dados de terceiros:** as bases de geolocalização são DB-IP Lite, CC BY 4.0, e a atribuição deve ser mantida onde os dados são exibidos.
|
||||
|
||||
## Limitação conhecida
|
||||
|
||||
@@ -83,7 +83,7 @@ Events from a trusted origin (`--trusted`, plus the private ranges of `--ignore`
|
||||
|
||||
## Web analytics
|
||||
|
||||
Benign requests (`ok`, and the `notfound` that are not scanning) also feed the Traffic view. A domain only gets a slot after a 2xx answer (and `--domains` can restrict them to an allowlist), inactive domains are pruned, and top pages normalize token-looking path segments to `:id`: unique visitors, pages, referrers, countries, browsers, operating systems, devices, latency (p50 and p95) and bytes. A unique visitor is a hash computed with a salt that rotates daily, so it cannot be followed across days, and the IP address of a legitimate visitor is never persisted. Attack traffic stays in the Threats view, where the IP is the subject. Monitoring requests are kept out of both.
|
||||
Benign requests (`ok`, and the `notfound` that are not scanning) also feed the Traffic page. A domain only gets a slot after a 2xx answer (and `--domains` can restrict them to an allowlist), inactive domains are pruned, and top pages normalize token-looking path segments to `:id`: unique visitors, pages, referrers, countries, browsers, operating systems, devices, latency (p50 and p95) and bytes. A unique visitor is a hash computed with a salt that rotates daily, so it cannot be followed across days, and the IP address of a legitimate visitor is never persisted. Attack traffic stays in the Threats view, where the IP is the subject. Monitoring requests are kept out of both.
|
||||
|
||||
## State and persistence
|
||||
|
||||
@@ -97,6 +97,14 @@ The process sets a soft memory limit of 160 MiB unless `GOMEMLIMIT` is set.
|
||||
|
||||
A hub is an ordinary instance started with `--peer name=https://url`, and it needs `URUTAU_PEER_TOKEN`. Every 15 seconds it calls each peer's `GET /api/v1/peer/export?range=...` (for `1h`, `24h` and `7d`) with the peer token and keeps the latest answer. The export is `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail, cached for 5 seconds on the peer. It is the only route the peer token opens. The hub never follows redirects, requires `https` outside loopback, uses a 4 second timeout, caps the body at 8 MB and sanitizes and caps whatever a peer sends. A peer that fails is marked offline and the others carry on. The dashboard host selector then offers `all`, the hub itself and each peer; summaries, traffic and IP tables are merged, and every row carries the host it came from.
|
||||
|
||||
### Live relay
|
||||
|
||||
Besides the export, a hub keeps one `GET /api/v1/peer/stream` connection open per peer (a subscription per peer, with the peer's own token) and relays the live malicious events to its dashboard. What comes from a peer is bounded and sanitized: at most about 50 events per second per peer, lines of at most 16 KB, a buffer of the latest 500 relayed events (served by `/api/v1/live/recent`), and reconnection with backoff from 1 s up to 60 s. A peer serves at most 10 stream connections.
|
||||
|
||||
### Geography aggregation
|
||||
|
||||
`GET /api/v1/geo` is computed from the IP table (local and the peers' exports) joined with the geolocation databases: countries first, then, for one country, its regions, cities and top IPs. Results are cached for 5 seconds, in a cache of at most 256 keys.
|
||||
|
||||
## HTTP layer
|
||||
|
||||
The server sets read, write and idle timeouts, `MaxHeaderBytes` of 16 KB, caps `POST /login` at 4 KB and accepts at most 20 simultaneous live-stream (SSE) clients (the 21st gets 503 with `Retry-After`; each stream sends a heartbeat every 20 s). The handler uses the standard `net/http` mux. Every response carries a strict Content-Security-Policy (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, cross-origin isolation headers and, over HTTPS, HSTS. API answers are `Cache-Control: no-store`. The dashboard files are embedded in the binary. See [interface.md](interface.md) for the routes and [configuration.md](configuration.md) for the settings.
|
||||
+3
-1
@@ -32,7 +32,9 @@ The access token is never a flag: `urutau serve` reads it from the `URUTAU_TOKEN
|
||||
| `--peer` | `URUTAU_PEERS` | none | peer `name=https://url`; repeat the flag, or comma separate the variable |
|
||||
| `--peer-token` | `URUTAU_PEER_TOKEN` | empty | token shared with the peers; prefer the variable or `URUTAU_PEER_TOKEN_FILE` (a flag shows up in the process list). Per-peer: `URUTAU_PEER_TOKEN_<NAME>` |
|
||||
| `--admin-users` | `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h; the immunity is off unless set |
|
||||
| `--peer-allow` | `URUTAU_PEER_ALLOW` | empty | source CIDRs allowed to call the export; empty accepts any source with the token |
|
||||
| `--peer-allow` | `URUTAU_PEER_ALLOW` | empty | source CIDRs allowed to call the federation routes; empty accepts any source with the token |
|
||||
| `--peer-blocklist` | `URUTAU_PEER_BLOCKLIST` | `on` | `on` lists in the hub's blocklist the hostile IPs seen only by peers (score 50+ and a strong signal); `off` keeps the blocklist to this instance's own IPs |
|
||||
| `--location` | `URUTAU_LOCATION` | empty | map position of this instance, `"lat,lon"` or `"lat,lon,Label"` |
|
||||
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | proxies whose `X-Forwarded-For` is trusted, read right to left (login rate limit, `--peer-allow`) |
|
||||
| `--retention` | `URUTAU_RETENTION` | `168h` | how long data is kept (1h to 168h) |
|
||||
| `--insecure-no-auth` | none | off | disable authentication; only on a loopback bind |
|
||||
|
||||
@@ -10,7 +10,7 @@ Urutau has no configuration file. Everything is a flag with a `URUTAU_*` environ
|
||||
|---|---|
|
||||
| `URUTAU_TOKEN` | **Required.** Access token of the dashboard and the API: at least 32 characters and about 128 bits of estimated entropy (length times Shannon entropy; periodic or sequential tokens are refused). Generate one with `openssl rand -base64 48` (`openssl rand -hex 32` also works; `-hex 16` is refused by the entropy estimate). |
|
||||
| `URUTAU_TOKEN_FILE` | Path of a file holding the token (whitespace trimmed), instead of the variable. The variable wins when both are set. |
|
||||
| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its `GET /api/v1/peer/export` accepts, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. |
|
||||
| `URUTAU_PEER_TOKEN` | Optional. The server token of this instance: the only token its federation routes (`GET /api/v1/peer/export` and `GET /api/v1/peer/stream`) accept, and it opens nothing else. Same strength rules as `URUTAU_TOKEN` (32+ characters, about 128 bits of estimated entropy, not periodic or sequential), and it must differ from it. When this instance is a hub, it is also the fallback client token sent to peers that have no token of their own. |
|
||||
| `URUTAU_PEER_TOKEN_FILE` | Path of a file holding the general peer token. |
|
||||
| `URUTAU_PEER_TOKEN_<NAME>` and `..._<NAME>_FILE` | The client credential a hub sends to that one peer; it must equal the peer's own `URUTAU_PEER_TOKEN`. `<NAME>` is the peer name uppercased with every character other than a letter or digit turned into `_` (`my-peer` becomes `MY_PEER`). It does **not** open the local export. Two peer names that collapse to the same variable (`my-peer` and `my_peer`) are refused. A hub with a peer and no token for it refuses to start. |
|
||||
|
||||
@@ -31,7 +31,9 @@ Keep both in `.env` (never versioned) or in your orchestrator's secret store.
|
||||
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents |
|
||||
| `URUTAU_GEO_DIR` | `<data-dir>/geo` | where the DB-IP Lite databases live |
|
||||
| `URUTAU_GEO_UPDATE` | `24h` | interval between checks for a newer database; `0` disables the download |
|
||||
| `URUTAU_PEER_ALLOW` | empty | CIDRs allowed to call the export; empty accepts any source that has the token |
|
||||
| `URUTAU_PEER_ALLOW` | empty | CIDRs allowed to call the federation routes; empty accepts any source that has the token |
|
||||
| `URUTAU_PEER_BLOCKLIST` | `on` | `on`: the hub's blocklist includes hostile IPs seen only by peers (score 50+ and a strong signal); `off`: only this instance's own IPs |
|
||||
| `URUTAU_LOCATION` | empty | where this instance is on the map, `"lat,lon"` or `"lat,lon,Label"` (validated at start). It is the destination of the arcs on the Live page and is shared with the hub; empty lets the page fall back to an estimated destination |
|
||||
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (the compose file sets `10.250.0.0/24`) | reverse proxies whose `X-Forwarded-For` is trusted (read right to left); used by the login rate limit and by `URUTAU_PEER_ALLOW` |
|
||||
| `URUTAU_DOMAINS` | empty | allowlist of analytics domains, exact names or `*.example.com`; empty tracks every domain that answers 2xx; recommended, in practice required, when any backend answers 2xx for every Host (catch-all or wildcard), otherwise random Hosts can fill the 24 domain slots |
|
||||
| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them |
|
||||
@@ -54,7 +56,7 @@ In the container image the three log paths default to `/logs/traefik/access.log`
|
||||
|
||||
Country, city and ASN come from the DB-IP Lite databases (city and ASN), which Urutau downloads and refreshes by itself into `URUTAU_GEO_DIR`. Without them (for example on an air-gapped host) the dashboard works and the geographic fields stay empty; to run offline, place the `dbip-city-lite-YYYY-MM.mmdb` and `dbip-asn-lite-YYYY-MM.mmdb` files in that directory and set `URUTAU_GEO_UPDATE=0`. The databases are licensed CC BY 4.0: keep the attribution (the dashboard footer and the README already carry it).
|
||||
|
||||
The Traffic tab needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
|
||||
The Traffic page needs no setting. `URUTAU_DOMAINS` restricts which domains it tracks (exact names or `*.example.com`); a domain only gets a slot after a 2xx answer and inactive domains are pruned, so forged `Host` headers cannot fill the analytics. Top pages normalize token-looking path segments (ids, hashes, long random strings) to `:id`. It uses the Traefik log, counts unique visitors by a daily-salted hash and never persists the IP address of a legitimate visitor. See [SECURITY.md](../SECURITY.md).
|
||||
|
||||
## Peers (hub mode)
|
||||
|
||||
|
||||
+1
-1
@@ -150,7 +150,7 @@ Run one Urutau per server with its own `URUTAU_NAME`. Every instance that is pol
|
||||
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
|
||||
```
|
||||
|
||||
The hub calls only `GET /api/v1/peer/export` on each peer (three ranges every 15 seconds) with that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard.
|
||||
The hub calls only `GET /api/v1/peer/export` on each peer (three ranges every 15 seconds) and keeps one `GET /api/v1/peer/stream` open for the live events, with that peer's token, which opens nothing else on the peer and is refused over plain `http` outside loopback. Set `URUTAU_PEER_ALLOW` on a peer to the hub's address to restrict who may call the export. Each peer keeps its own login token for its own dashboard.
|
||||
|
||||
## Hardening
|
||||
|
||||
|
||||
+16
-14
@@ -8,6 +8,10 @@ The dashboard is embedded in the binary: plain HTML, CSS and JavaScript, no buil
|
||||
|
||||
Open the address of the instance. Without a session you are sent to `/login`: paste `URUTAU_TOKEN`. The session lasts 12 hours (`urutau_session` cookie, `HttpOnly`, `SameSite=Strict`) and is revocable: it holds a random id kept in memory, **Log out** revokes it (and closes its live stream), and a restart of the daemon invalidates every session. Login and logout reject cross-site requests. After 5 failures from the same address (IPv6 counted per /64) in 10 minutes the login answers 429, and a correct token is still accepted but after a 1 second delay, so the limiter cannot lock the owner out. Wrong bearer tokens on the API count as failures too. The address is the real client behind the proxies listed in `--trusted-proxy`.
|
||||
|
||||
## Navigation
|
||||
|
||||
A side rail (a tab bar on phones) holds seven pages. Each page opens with a sentence carrying the number that matters, and the active slice (range, host, domain) is always written under the title. The page lives in the URL hash (`#/overview`, `#/threats`, `#/geo`, `#/live`, `#/traffic`, `#/ips`, `#/sources`), so a view can be bookmarked or shared; the Geography page goes deeper, as in `#/geo/BR/Pernambuco`. An IP detail drawer opens from any IP.
|
||||
|
||||
## Header
|
||||
|
||||
- A live indicator showing whether the event stream (SSE) is connected (an instance serves at most 20 stream clients at once).
|
||||
@@ -15,20 +19,15 @@ Open the address of the instance. Without a session you are sent to `/login`: pa
|
||||
- The **range** selector: `1h`, `24h` or `7d`.
|
||||
- Language, theme and logout buttons.
|
||||
|
||||
## Threats tab
|
||||
## Pages
|
||||
|
||||
- **KPIs:** requests, malicious events, hostile IPs, suspicious IPs, bans and the "monitoring" counter (benign requests from monitor User-Agents, kept out of the traffic numbers).
|
||||
- **Timeline:** stacked counters per category over the selected range.
|
||||
- **IPs:** a table with score, level (`hostile`, `suspicious`, `low`), categories, hosts, reverse DNS, country, city and ASN, last seen and ban state. It has a search box (IP or reverse DNS), a level filter, a "banned only" filter, sorting by IP, score or last seen, and paging. Click a row for the detail drawer: first and last seen, per-category counts, sample paths, User-Agents (parsed into browser, OS, device, bot or attack tool), domains, users and jails.
|
||||
- **Live feed:** the latest events as they arrive. Fields from the logs are shown as text, never as markup.
|
||||
- **Top lists:** attacked paths, domains, User-Agents and targeted users.
|
||||
- **Blocklist:** pick a minimum score (default 50), copy the list or download it. It only lists hostile, globally routable addresses (never `--ignore` or `--trusted` ranges, never an IP with a successful SSH login); IPv6 appears as its /64, written `x:x:x:x::/64`.
|
||||
- **Map:** a world map of the origin countries of hostile activity.
|
||||
- **Hosts and sources:** every instance with its state (online, latency, version) and every log source with its state (`following`, `waiting`, `backfill`, `error`), lines read, malformed lines and last event. The file paths are not shown.
|
||||
|
||||
## Traffic tab
|
||||
|
||||
Privacy-friendly web analytics for legitimate traffic, built from the same Traefik log and replacing the analytics of the proxy: unique visitors, pages, referrers, countries, browsers, operating systems and devices, response latency (p50 and p95), bytes sent, and a world map of visitor countries. Unique visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md).
|
||||
- **Overview:** the headline numbers (requests, malicious events, hostile and suspicious IPs, bans, the "monitoring" counter of benign monitor requests kept out of the traffic numbers), the timeline and the top IPs.
|
||||
- **Threats:** stacked counters per category, the live feed of the latest events (log fields are shown as text, never as markup) and the top attacked paths, domains, User-Agents and targeted users.
|
||||
- **Geography:** a world map by attacker country. Select a country to see its states or regions and its cities (drawn as circles on the zoomed country), the categories and the top IPs; select a region to narrow cities and IPs. The view is `#/geo/<CC>/<region>`.
|
||||
- **Live:** attacks drawn as animated arcs from their origin to the server that saw them, on a flat map or a 3D globe, with the rate, categories, servers, recent origins and latest events, filters, pause and full screen. It opens by replaying the latest events (`/api/v1/live/recent`), so it is not still on a quiet server. On a hub it also shows the events of every peer. The position of each server comes from `--location`.
|
||||
- **Traffic:** privacy-friendly web analytics for legitimate traffic, built from the same Traefik log: unique visitors, pages, referrers, countries, browsers, operating systems, devices, response latency (p50 and p95), bytes sent and a world map of visitor countries, per domain. Unique visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md).
|
||||
- **IPs:** a table with score, level (`hostile`, `suspicious`, `low`), categories, hosts, reverse DNS, country, city and ASN, last seen and ban state, with a search box (IP or reverse DNS), a level filter, a "banned only" filter, sorting and paging. The detail drawer shows first and last seen, per-category counts, sample paths, User-Agents (parsed into browser, OS, device, bot or attack tool), domains, users and jails.
|
||||
- **Sources and hosts:** every instance with its state (online, latency, version), every log source with its state (`following`, `waiting`, `backfill`, `error`), lines read, malformed lines and last event (file paths are not shown), and the **blocklist**: pick a minimum score (default 50), copy or download it. It only lists hostile, globally routable addresses (never `--ignore` or `--trusted` ranges, never an IP with a successful SSH login); IPv6 appears as its /64, written `x:x:x:x::/64`.
|
||||
|
||||
## Attribution
|
||||
|
||||
@@ -43,6 +42,9 @@ IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](ht
|
||||
| `GET /` and the static files | session | the dashboard |
|
||||
| `GET /api/v1/summary` | session or bearer | everything the dashboard shows. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, a name) |
|
||||
| `GET /api/v1/traffic` | session or bearer | web analytics of legitimate traffic. Query: `range`, `domain` (`all` or one domain), `host`. Returns visitors, pages, requests, bots, bytes, status classes, `p50_ms`, `p95_ms`, a timeline, top pages, referrers, countries, cities, browsers, operating systems, devices and bot names |
|
||||
| `GET /api/v1/geo` | session or `URUTAU_TOKEN` | attacker geography. Without `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (up to 250). With `cc=XX` (and optionally `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regions, 200 cities, 50 IPs). Query: `range`, `host`. Cached for 5 s |
|
||||
| `GET /api/v1/live/recent` | session or `URUTAU_TOKEN` | `{"events":[...]}`: the latest malicious events of this instance and its peers, newest first, in the stream format. Query: `limit` (default 200, at most 500) |
|
||||
| `GET /api/v1/peer/stream` | peer token only | live federation: server-sent malicious events of this instance. At most 10 connections; same 404/401/403 rules as the export |
|
||||
| `GET /api/v1/peer/export` | peer token only | federation: `{"v":1,"summary":...,"traffic":{...}}` with the top 500 IPs and their detail. Query: `range` (`1h`, `24h`, `7d`). Cached for 5 s. 404 when no peer token is set, 401 for `URUTAU_TOKEN`, 403 from a source outside `--peer-allow` |
|
||||
| `GET /api/v1/ips` | session or bearer | IP table. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 to 200, default 50), `page` |
|
||||
| `GET /api/v1/ip/{ip}` | session or bearer | detail of one IP, merged with the peers' exports |
|
||||
@@ -50,4 +52,4 @@ IP geolocation data by [DB-IP](https://db-ip.com), licensed under [CC BY 4.0](ht
|
||||
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
|
||||
|
||||
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by `/api/v1/peer/export`; every other route answers 403 to it.
|
||||
API clients send `Authorization: Bearer <URUTAU_TOKEN>`. The peer token is accepted only by `/api/v1/peer/export` and `/api/v1/peer/stream`; every other route answers 403 to it.
|
||||
@@ -83,7 +83,7 @@ Eventos de uma origem confiável (`--trusted`, mais as faixas privadas de `--ign
|
||||
|
||||
## Web analytics
|
||||
|
||||
Requisições benignas (`ok`, e os `notfound` que não são varredura) também alimentam a visão Tráfego. Um domínio só ganha vaga depois de uma resposta 2xx (e `--domains` pode restringi-los a uma lista), domínios inativos são podados e o top de páginas normaliza segmentos com cara de token para `:id`: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência (p50 e p95) e bytes. Um visitante único é um hash calculado com um sal que gira todo dia, então não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. O tráfego de ataque fica na visão Ameaças, onde o IP é o assunto. Requisições de monitoramento ficam fora das duas.
|
||||
Requisições benignas (`ok`, e os `notfound` que não são varredura) também alimentam a página Tráfego. Um domínio só ganha vaga depois de uma resposta 2xx (e `--domains` pode restringi-los a uma lista), domínios inativos são podados e o top de páginas normaliza segmentos com cara de token para `:id`: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência (p50 e p95) e bytes. Um visitante único é um hash calculado com um sal que gira todo dia, então não pode ser seguido entre dias, e o endereço IP de um visitante legítimo nunca é persistido. O tráfego de ataque fica na visão Ameaças, onde o IP é o assunto. Requisições de monitoramento ficam fora das duas.
|
||||
|
||||
## Estado e persistência
|
||||
|
||||
@@ -97,6 +97,14 @@ O processo define um limite suave de memória de 160 MiB, a menos que `GOMEMLIMI
|
||||
|
||||
Um hub é uma instância comum iniciada com `--peer nome=https://url`, e precisa de `URUTAU_PEER_TOKEN`. A cada 15 segundos ele chama `GET /api/v1/peer/export?range=...` de cada peer (para `1h`, `24h` e `7d`) com o token de peer e guarda a última resposta. O export é `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes, em cache de 5 segundos no peer. É a única rota que o token de peer abre. O hub nunca segue redirects, exige `https` fora de loopback, usa timeout de 4 segundos, limita o corpo a 8 MB e sanitiza e limita o que um peer enviar. Um peer que falha é marcado offline e os demais seguem. O seletor de host do dashboard passa a oferecer `all`, o próprio hub e cada peer; resumos, tráfego e tabelas de IPs são mesclados, e cada linha carrega o host de origem.
|
||||
|
||||
### Repasse ao vivo
|
||||
|
||||
Além do export, um hub mantém uma conexão `GET /api/v1/peer/stream` aberta por peer (uma assinatura por peer, com o token do próprio peer) e repassa os eventos maliciosos ao vivo para o dashboard. O que vem de um peer é limitado e sanitizado: no máximo cerca de 50 eventos por segundo por peer, linhas de no máximo 16 KB, um buffer dos últimos 500 eventos repassados (servido por `/api/v1/live/recent`) e reconexão com backoff de 1 s até 60 s. Um peer atende no máximo 10 conexões de stream.
|
||||
|
||||
### Agregação de geografia
|
||||
|
||||
`GET /api/v1/geo` é calculado a partir da tabela de IPs (local e os exports dos peers) combinada com as bases de geolocalização: primeiro os países e, para um país, suas regiões, cidades e principais IPs. Os resultados ficam em cache por 5 segundos, num cache de no máximo 256 chaves.
|
||||
|
||||
## Camada HTTP
|
||||
|
||||
O servidor define timeouts de leitura, escrita e ociosidade, `MaxHeaderBytes` de 16 KB, limita `POST /login` a 4 KB e aceita no máximo 20 clientes simultâneos do stream ao vivo (SSE) (o 21º recebe 503 com `Retry-After`; cada stream envia heartbeat a cada 20 s). O handler usa o mux padrão do `net/http`. Toda resposta leva uma Content-Security-Policy estrita (`default-src 'self'`), `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, cabeçalhos de isolamento de origem cruzada e, em HTTPS, HSTS. As respostas da API são `Cache-Control: no-store`. Os arquivos do dashboard são embutidos no binário. Veja [interface.md](interface.md) para as rotas e [configuracao.md](configuracao.md) para os ajustes.
|
||||
+3
-1
@@ -32,7 +32,9 @@ O token de acesso nunca é uma flag: `urutau serve` o lê da variável de ambien
|
||||
| `--peer` | `URUTAU_PEERS` | nenhum | peer `nome=https://url`; repita a flag ou separe a variável por vírgula |
|
||||
| `--peer-token` | `URUTAU_PEER_TOKEN` | vazio | token compartilhado com os peers; prefira a variável ou `URUTAU_PEER_TOKEN_FILE` (uma flag aparece na lista de processos). Por peer: `URUTAU_PEER_TOKEN_<NOME>` |
|
||||
| `--admin-users` | `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da blocklist por 24 h; a imunidade fica desligada se não definido |
|
||||
| `--peer-allow` | `URUTAU_PEER_ALLOW` | vazio | CIDRs de origem autorizados a chamar o export; vazio aceita qualquer origem com o token |
|
||||
| `--peer-allow` | `URUTAU_PEER_ALLOW` | vazio | CIDRs de origem autorizados a chamar as rotas de federação; vazio aceita qualquer origem com o token |
|
||||
| `--peer-blocklist` | `URUTAU_PEER_BLOCKLIST` | `on` | `on` lista na blocklist do hub os IPs hostis vistos só pelos peers (pontuação 50+ e sinal forte); `off` restringe a blocklist aos IPs da própria instância |
|
||||
| `--location` | `URUTAU_LOCATION` | vazio | posição desta instância no mapa, `"lat,lon"` ou `"lat,lon,Rótulo"` |
|
||||
| `--trusted-proxy` | `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies cujo `X-Forwarded-For` é confiável, lido da direita para a esquerda (limite de login, `--peer-allow`) |
|
||||
| `--retention` | `URUTAU_RETENTION` | `168h` | por quanto tempo os dados ficam (1h a 168h) |
|
||||
| `--insecure-no-auth` | nenhuma | desligado | desativa a autenticação; só em bind loopback |
|
||||
|
||||
@@ -10,7 +10,7 @@ O Urutau não tem arquivo de configuração. Tudo é uma flag com padrão em var
|
||||
|---|---|
|
||||
| `URUTAU_TOKEN` | **Obrigatória.** Token de acesso do dashboard e da API: no mínimo 32 caracteres e cerca de 128 bits de entropia estimada (comprimento vezes entropia de Shannon; tokens periódicos ou sequenciais são recusados). Gere um com `openssl rand -base64 48` (`openssl rand -hex 32` também serve; `-hex 16` é recusado pela estimativa de entropia). |
|
||||
| `URUTAU_TOKEN_FILE` | Caminho de um arquivo com o token (espaços nas pontas são removidos), no lugar da variável. A variável vence quando as duas existem. |
|
||||
| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que o `GET /api/v1/peer/export` dela aceita, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. |
|
||||
| `URUTAU_PEER_TOKEN` | Opcional. O token de servidor desta instância: o único que as rotas de federação dela (`GET /api/v1/peer/export` e `GET /api/v1/peer/stream`) aceitam, e não abre mais nada. Mesmas regras de força do `URUTAU_TOKEN` (32+ caracteres, cerca de 128 bits de entropia estimada, sem padrão periódico nem sequencial), e deve ser diferente dele. Quando esta instância é um hub, também é o token de cliente de reserva enviado aos peers que não têm o seu. |
|
||||
| `URUTAU_PEER_TOKEN_FILE` | Caminho de um arquivo com o token de peer geral. |
|
||||
| `URUTAU_PEER_TOKEN_<NOME>` e `..._<NOME>_FILE` | A credencial de cliente que um hub envia àquele peer; deve ser igual ao `URUTAU_PEER_TOKEN` do próprio peer. `<NOME>` é o nome do peer em maiúsculas, com todo caractere que não seja letra ou dígito virando `_` (`my-peer` vira `MY_PEER`). Ela **não** abre o export local. Dois nomes de peer que viram a mesma variável (`my-peer` e `my_peer`) são recusados. Um hub com um peer sem token para ele se recusa a iniciar. |
|
||||
|
||||
@@ -31,7 +31,9 @@ Guarde os dois no `.env` (nunca versionado) ou no cofre de segredos do seu orque
|
||||
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento |
|
||||
| `URUTAU_GEO_DIR` | `<data-dir>/geo` | onde ficam as bases DB-IP Lite |
|
||||
| `URUTAU_GEO_UPDATE` | `24h` | intervalo entre buscas por uma base mais nova; `0` desativa o download |
|
||||
| `URUTAU_PEER_ALLOW` | vazio | CIDRs autorizados a chamar o export; vazio aceita qualquer origem que tenha o token |
|
||||
| `URUTAU_PEER_ALLOW` | vazio | CIDRs autorizados a chamar as rotas de federação; vazio aceita qualquer origem que tenha o token |
|
||||
| `URUTAU_PEER_BLOCKLIST` | `on` | `on`: a blocklist do hub inclui IPs hostis vistos só pelos peers (pontuação 50+ e sinal forte); `off`: só os IPs da própria instância |
|
||||
| `URUTAU_LOCATION` | vazio | onde esta instância fica no mapa, `"lat,lon"` ou `"lat,lon,Rótulo"` (validado na partida). É o destino dos arcos da página Ao vivo e é repassado ao hub; vazio faz a página usar um destino estimado |
|
||||
| `URUTAU_TRUSTED_PROXY` | `127.0.0.0/8,::1` (o compose define `10.250.0.0/24`) | proxies reversos cujo `X-Forwarded-For` é confiável (lido da direita para a esquerda); usado no limite de tentativas de login e em `URUTAU_PEER_ALLOW` |
|
||||
| `URUTAU_DOMAINS` | vazio | lista de domínios permitidos no analytics, nomes exatos ou `*.exemplo.com`; vazio acompanha todo domínio que responde 2xx; recomendado, na prática obrigatório, quando algum backend responde 2xx para qualquer Host (catch-all ou wildcard), senão Hosts aleatórios podem ocupar as 24 vagas de domínio |
|
||||
| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles |
|
||||
@@ -54,7 +56,7 @@ Na imagem do container os três caminhos de log têm como padrão `/logs/traefik
|
||||
|
||||
País, cidade e ASN vêm das bases DB-IP Lite (cidade e ASN), que o Urutau baixa e atualiza sozinho em `URUTAU_GEO_DIR`. Sem elas (por exemplo num host isolado da internet) o dashboard funciona e os campos geográficos ficam vazios; para operar offline, coloque os arquivos `dbip-city-lite-AAAA-MM.mmdb` e `dbip-asn-lite-AAAA-MM.mmdb` nesse diretório e defina `URUTAU_GEO_UPDATE=0`. As bases são licenciadas CC BY 4.0: mantenha a atribuição (o rodapé do dashboard e o README já a trazem).
|
||||
|
||||
A aba Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
||||
A página Tráfego não precisa de ajuste. `URUTAU_DOMAINS` restringe quais domínios ela acompanha (nomes exatos ou `*.exemplo.com`); um domínio só ganha vaga depois de uma resposta 2xx e domínios inativos são podados, então `Host` forjados não enchem o analytics. O top de páginas normaliza segmentos de caminho com cara de token (ids, hashes, strings aleatórias longas) para `:id`. Ela usa o log do Traefik, conta visitantes únicos por um hash com sal diário e nunca persiste o endereço IP de um visitante legítimo. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
||||
|
||||
## Peers (modo hub)
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ Rode um Urutau por servidor, cada um com seu `URUTAU_NAME`. Toda instância cons
|
||||
URUTAU_PEER_TOKEN_SERVER_3: ${TOKEN_FOR_SERVER_3}
|
||||
```
|
||||
|
||||
O hub chama apenas `GET /api/v1/peer/export` em cada peer (três intervalos a cada 15 segundos) com o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard.
|
||||
O hub chama apenas `GET /api/v1/peer/export` em cada peer (três intervalos a cada 15 segundos) e mantém um `GET /api/v1/peer/stream` aberto para os eventos ao vivo, com o token daquele peer, que não abre mais nada no peer e é recusado em `http` simples fora de loopback. Defina `URUTAU_PEER_ALLOW` em um peer com o endereço do hub para restringir quem pode chamar o export. Cada peer mantém seu próprio token de login para o próprio dashboard.
|
||||
|
||||
## Endurecimento
|
||||
|
||||
|
||||
+16
-14
@@ -8,6 +8,10 @@ O dashboard é embutido no binário: HTML, CSS e JavaScript puros, sem etapa de
|
||||
|
||||
Abra o endereço da instância. Sem sessão você é enviado a `/login`: cole o `URUTAU_TOKEN`. A sessão dura 12 horas (cookie `urutau_session`, `HttpOnly`, `SameSite=Strict`) e é revogável: ela guarda um id aleatório em memória, **Sair** a revoga (e fecha o stream ao vivo dela), e um reinício do daemon invalida todas as sessões. Login e logout rejeitam requisições cross-site. Após 5 falhas do mesmo endereço (IPv6 contado por /64) em 10 minutos o login responde 429, e um token correto ainda é aceito, mas com 1 segundo de atraso, para que o limitador não tranque o dono do lado de fora. Bearer tokens errados na API também contam como falha (o endereço é o do cliente real atrás dos proxies de `--trusted-proxy`). **Sair** encerra a sessão.
|
||||
|
||||
## Navegação
|
||||
|
||||
Uma barra lateral (barra de abas no celular) reúne sete páginas. Cada página abre com uma frase com o número que importa, e o recorte ativo (intervalo, host, domínio) fica sempre escrito sob o título. A página vive no hash da URL (`#/overview`, `#/threats`, `#/geo`, `#/live`, `#/traffic`, `#/ips`, `#/sources`), então uma visão pode ser salva ou compartilhada; a página Geografia vai mais fundo, como em `#/geo/BR/Pernambuco`. Um painel de detalhe do IP abre a partir de qualquer IP.
|
||||
|
||||
## Cabeçalho
|
||||
|
||||
- Um indicador ao vivo mostrando se o stream de eventos (SSE) está conectado (uma instância atende no máximo 20 clientes do stream ao mesmo tempo).
|
||||
@@ -15,20 +19,15 @@ Abra o endereço da instância. Sem sessão você é enviado a `/login`: cole o
|
||||
- O seletor de **intervalo**: `1h`, `24h` ou `7d`.
|
||||
- Botões de idioma, tema e sair.
|
||||
|
||||
## Aba Ameaças
|
||||
## Páginas
|
||||
|
||||
- **KPIs:** requisições, eventos maliciosos, IPs hostis, IPs suspeitos, bans e o contador "monitoring" (requisições benignas de User-Agents de monitor, fora dos números de tráfego).
|
||||
- **Linha do tempo:** contadores empilhados por categoria no intervalo escolhido.
|
||||
- **IPs:** uma tabela com pontuação, nível (`hostile`, `suspicious`, `low`), categorias, hosts, DNS reverso, país, cidade e ASN, último evento e estado de ban. Tem busca (IP ou DNS reverso), filtro de nível, filtro "só banidos", ordenação por IP, pontuação ou último evento e paginação. Clique numa linha para o painel de detalhe: primeiro e último evento, contagem por categoria, caminhos de exemplo, User-Agents (interpretados em navegador, SO, dispositivo, bot ou ferramenta de ataque), domínios, usuários e jails.
|
||||
- **Feed ao vivo:** os últimos eventos conforme chegam. Os campos dos logs são mostrados como texto, nunca como marcação.
|
||||
- **Listas de top:** caminhos atacados, domínios, User-Agents e usuários visados.
|
||||
- **Blocklist:** escolha uma pontuação mínima (padrão 50), copie a lista ou baixe. Ela só lista endereços hostis e globalmente roteáveis (nunca faixas de `--ignore` ou `--trusted`, nunca um IP com login SSH bem-sucedido); o IPv6 aparece como o /64, escrito `x:x:x:x::/64`.
|
||||
- **Mapa:** um mapa-múndi dos países de origem da atividade hostil.
|
||||
- **Hosts e fontes:** cada instância com seu estado (online, latência, versão) e cada fonte de log com seu estado (`following`, `waiting`, `backfill`, `error`), linhas lidas, linhas malformadas e último evento. Os caminhos dos arquivos não são mostrados.
|
||||
|
||||
## Aba Tráfego
|
||||
|
||||
Web analytics amigável à privacidade para o tráfego legítimo, construído do mesmo log do Traefik e substituindo o analytics do proxy: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais e dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes. Visitantes únicos são contados por um hash com sal diário; o IP de um visitante legítimo nunca é gravado. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
||||
- **Visão geral:** os números principais (requisições, eventos maliciosos, IPs hostis e suspeitos, bans, o contador "monitoring" de requisições benignas de monitores, fora dos números de tráfego), a linha do tempo e os principais IPs.
|
||||
- **Ameaças:** contadores empilhados por categoria, o feed ao vivo dos últimos eventos (campos dos logs são mostrados como texto, nunca como marcação) e os principais caminhos atacados, domínios, User-Agents e usuários visados.
|
||||
- **Geografia:** um mapa-múndi por país do atacante. Selecione um país para ver seus estados ou regiões e suas cidades (desenhadas como círculos no país ampliado), as categorias e os principais IPs; selecione uma região para restringir cidades e IPs. A visão é `#/geo/<CC>/<região>`.
|
||||
- **Ao vivo:** ataques desenhados como arcos animados da origem até o servidor que os viu, em mapa plano ou globo 3D, com taxa, categorias, servidores, origens recentes e últimos eventos, filtros, pausa e tela cheia. Abre reproduzindo os últimos eventos (`/api/v1/live/recent`), então não fica parada num servidor calmo. Em um hub mostra também os eventos de cada peer. A posição de cada servidor vem de `--location`.
|
||||
- **Tráfego:** web analytics amigável à privacidade para o tráfego legítimo, construído do mesmo log do Traefik: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes, por domínio. Visitantes únicos são contados por um hash com sal diário; o IP de um visitante legítimo nunca é gravado. Veja o [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
||||
- **IPs:** uma tabela com pontuação, nível (`hostile`, `suspicious`, `low`), categorias, hosts, DNS reverso, país, cidade e ASN, último evento e estado de ban, com busca (IP ou DNS reverso), filtro de nível, filtro "só banidos", ordenação e paginação. O painel de detalhe mostra primeiro e último evento, contagem por categoria, caminhos de exemplo, User-Agents (interpretados em navegador, SO, dispositivo, bot ou ferramenta de ataque), domínios, usuários e jails.
|
||||
- **Fontes e hosts:** cada instância com seu estado (online, latência, versão), cada fonte de log com seu estado (`following`, `waiting`, `backfill`, `error`), linhas lidas, linhas malformadas e último evento (os caminhos dos arquivos não são mostrados), e a **blocklist**: escolha uma pontuação mínima (padrão 50), copie ou baixe. Ela só lista endereços hostis e globalmente roteáveis (nunca faixas de `--ignore` ou `--trusted`, nunca um IP com login SSH bem-sucedido); o IPv6 aparece como o /64, escrito `x:x:x:x::/64`.
|
||||
|
||||
## Atribuição
|
||||
|
||||
@@ -43,6 +42,9 @@ Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob
|
||||
| `GET /` e os arquivos estáticos | sessão | o dashboard |
|
||||
| `GET /api/v1/summary` | sessão ou bearer | tudo o que o dashboard mostra. Query: `range` (`1h`, `24h`, `7d`), `host` (`all`, um nome) |
|
||||
| `GET /api/v1/traffic` | sessão ou bearer | web analytics do tráfego legítimo. Query: `range`, `domain` (`all` ou um domínio), `host`. Retorna visitantes, páginas, requisições, bots, bytes, classes de status, `p50_ms`, `p95_ms`, linha do tempo, top de páginas, referrers, países, cidades, navegadores, sistemas operacionais, dispositivos e nomes de bots |
|
||||
| `GET /api/v1/geo` | sessão ou `URUTAU_TOKEN` | geografia dos atacantes. Sem `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (até 250). Com `cc=XX` (e opcionalmente `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regiões, 200 cidades, 50 IPs). Query: `range`, `host`. Cache de 5 s |
|
||||
| `GET /api/v1/live/recent` | sessão ou `URUTAU_TOKEN` | `{"events":[...]}`: os últimos eventos maliciosos desta instância e dos peers, do mais novo ao mais velho, no formato do stream. Query: `limit` (padrão 200, máximo 500) |
|
||||
| `GET /api/v1/peer/stream` | só token de peer | federação ao vivo: eventos maliciosos desta instância por SSE. No máximo 10 conexões; mesmas regras 404/401/403 do export |
|
||||
| `GET /api/v1/peer/export` | só token de peer | federação: `{"v":1,"summary":...,"traffic":{...}}` com os 500 IPs principais e seus detalhes. Query: `range` (`1h`, `24h`, `7d`). Cache de 5 s. 404 sem token de peer, 401 para `URUTAU_TOKEN`, 403 de origem fora de `--peer-allow` |
|
||||
| `GET /api/v1/ips` | sessão ou bearer | tabela de IPs. Query: `range`, `host`, `min_score`, `level`, `q`, `banned=1`, `sort` (`score`, `last`, `first`, `events`, `ip`), `order=asc`, `per` (1 a 200, padrão 50), `page` |
|
||||
| `GET /api/v1/ip/{ip}` | sessão ou bearer | detalhe de um IP, mesclado com os exports dos peers |
|
||||
@@ -50,4 +52,4 @@ Dados de geolocalização de IP por [DB-IP](https://db-ip.com), licenciados sob
|
||||
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
|
||||
|
||||
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito por `/api/v1/peer/export`; todas as outras rotas respondem 403 a ele.
|
||||
Clientes da API enviam `Authorization: Bearer <URUTAU_TOKEN>`. O token de peer só é aceito por `/api/v1/peer/export` e `/api/v1/peer/stream`; todas as outras rotas respondem 403 a ele.
|
||||
@@ -413,3 +413,18 @@ func TestDefaultIgnoreCoversPrivateRanges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocationFlagIsValidated(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
v string
|
||||
ok bool
|
||||
}{{"", true}, {"-8.05,-34.9", true}, {"-8.05,-34.9,Recife", true}, {"95,0", false}, {"x", false}} {
|
||||
c, err := ParseFlags("t", []string{"--location", tc.v})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Validate("zK3vQ9xT2mLp7WdR4nYb8HsJ6cFg1UaE5oXi0VtN"); (err == nil) != tc.ok {
|
||||
t.Errorf("%q: %v", tc.v, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
-22
@@ -14,32 +14,35 @@ import (
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// Config is the runtime configuration of `urutau serve` and `urutau doctor`.
|
||||
type Config struct {
|
||||
Bind string
|
||||
Name string
|
||||
DataDir string
|
||||
TraefikLog string
|
||||
AuthLog string
|
||||
Fail2banLog string
|
||||
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
|
||||
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
|
||||
MonitorUA string // regex of monitoring User-Agents
|
||||
MonitorFrom string // networks monitors come from (empty: any source)
|
||||
Domains string // optional allowlist of analytics domains
|
||||
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
|
||||
PeerTokens []string // tokens accepted by /api/v1/peer/export
|
||||
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
|
||||
GeoDir string // directory of the geo databases (default <data-dir>/geo)
|
||||
GeoUpdate time.Duration
|
||||
Peers []string
|
||||
PeerToken string
|
||||
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
|
||||
TrustedProxy string // proxies whose X-Forwarded-For is believed
|
||||
Retention time.Duration
|
||||
NoAuth bool
|
||||
Bind string
|
||||
Name string
|
||||
DataDir string
|
||||
TraefikLog string
|
||||
AuthLog string
|
||||
Fail2banLog string
|
||||
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
|
||||
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
|
||||
MonitorUA string // regex of monitoring User-Agents
|
||||
MonitorFrom string // networks monitors come from (empty: any source)
|
||||
Domains string // optional allowlist of analytics domains
|
||||
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
|
||||
PeerTokens []string // tokens accepted by /api/v1/peer/export
|
||||
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
|
||||
GeoDir string // directory of the geo databases (default <data-dir>/geo)
|
||||
GeoUpdate time.Duration
|
||||
Peers []string
|
||||
PeerToken string
|
||||
Location string // "lat,lon" or "lat,lon,label" (--location)
|
||||
PeerBlocklist string // "on" (default) or "off"
|
||||
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
|
||||
TrustedProxy string // proxies whose X-Forwarded-For is believed
|
||||
Retention time.Duration
|
||||
NoAuth bool
|
||||
}
|
||||
|
||||
type listFlag []string
|
||||
@@ -115,6 +118,8 @@ func ParseFlags(name string, args []string) (Config, error) {
|
||||
tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)}
|
||||
fs.Var(allow, "peer-allow", "CIDRs allowed to call /api/v1/peer/export, empty allows any source with the token (URUTAU_PEER_ALLOW)")
|
||||
fs.Var(tproxy, "trusted-proxy", "reverse proxies whose X-Forwarded-For is trusted for the real client IP (URUTAU_TRUSTED_PROXY)")
|
||||
fs.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
|
||||
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
|
||||
fs.DurationVar(&c.Retention, "retention", 7*24*time.Hour, "how long data is kept, at most 168h (URUTAU_RETENTION)")
|
||||
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
|
||||
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
|
||||
@@ -168,6 +173,12 @@ func ParseFlags(name string, args []string) (Config, error) {
|
||||
|
||||
// Validate checks the configuration and returns the parsed peers.
|
||||
func (c Config) Validate(token string) ([]fed.Peer, error) {
|
||||
if _, err := store.ParseLocation(c.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
|
||||
return nil, fmt.Errorf("--peer-blocklist must be on or off")
|
||||
}
|
||||
var peers []fed.Peer
|
||||
seen := map[string]bool{}
|
||||
envSeen := map[string]string{}
|
||||
|
||||
@@ -40,7 +40,8 @@ func Serve(c Config) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()})
|
||||
loc, _ := store.ParseLocation(c.Location) // validated above
|
||||
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
|
||||
st.SetDomains(splitList(c.Domains))
|
||||
rd := rdns.New()
|
||||
st.SetRDNS(rd)
|
||||
@@ -68,7 +69,7 @@ func Serve(c Config) error {
|
||||
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
||||
bindHost, _, _ := net.SplitHostPort(c.Bind)
|
||||
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, Version: Version, Store: st, Hub: hub})
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
|
||||
ln, err := net.Listen("tcp", c.Bind)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -2,4 +2,4 @@ package app
|
||||
|
||||
// Version is the release version (SemVer). Release builds may override it with
|
||||
// -ldflags "-X .../internal/app.Version=...".
|
||||
var Version = "1.0.0"
|
||||
var Version = "1.1.0"
|
||||
@@ -0,0 +1,13 @@
|
||||
package fed
|
||||
|
||||
import "time"
|
||||
|
||||
// SetLiveLimits shrinks the flood window, the byte ceiling and the first backoff; it returns the restore func.
|
||||
func SetLiveLimits(window time.Duration, bytesPerSec int, backoff time.Duration) func() {
|
||||
w, b, k := liveByteWindow, maxLiveBytes, liveBackoff0
|
||||
liveByteWindow, maxLiveBytes, liveBackoff0 = window, bytesPerSec, backoff
|
||||
return func() { liveByteWindow, maxLiveBytes, liveBackoff0 = w, b, k }
|
||||
}
|
||||
|
||||
// WaitStream blocks until the live stream goroutines have returned (after ctx is cancelled).
|
||||
func (h *Hub) WaitStream() { h.swg.Wait() }
|
||||
+14
-1
@@ -61,6 +61,7 @@ type peerState struct {
|
||||
latency int64
|
||||
version string
|
||||
exports map[string]store.PeerExport
|
||||
live bool
|
||||
}
|
||||
|
||||
// Hub polls peers and serves their latest summaries.
|
||||
@@ -69,6 +70,11 @@ type Hub struct {
|
||||
Token string
|
||||
Interval time.Duration
|
||||
client *http.Client
|
||||
stream *http.Client // long-lived SSE: no overall timeout, no redirects
|
||||
|
||||
swg sync.WaitGroup // live stream goroutines
|
||||
lmu sync.Mutex
|
||||
live liveState
|
||||
|
||||
mu sync.RWMutex
|
||||
state map[string]*peerState
|
||||
@@ -78,6 +84,9 @@ type Hub struct {
|
||||
func NewHub(peers []Peer, token string) *Hub {
|
||||
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
|
||||
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr.ResponseHeaderTimeout = 10 * time.Second
|
||||
h.stream = &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
for _, p := range peers {
|
||||
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}}
|
||||
}
|
||||
@@ -186,6 +195,7 @@ func (h *Hub) Run(ctx context.Context) {
|
||||
if len(h.Peers) == 0 {
|
||||
return
|
||||
}
|
||||
h.Stream(ctx)
|
||||
h.Refresh(ctx)
|
||||
t := time.NewTicker(h.Interval)
|
||||
defer t.Stop()
|
||||
@@ -206,11 +216,14 @@ func (h *Hub) Hosts() []store.HostInfo {
|
||||
out := make([]store.HostInfo, 0, len(h.Peers))
|
||||
for _, p := range h.Peers {
|
||||
st := h.state[p.Name]
|
||||
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version}
|
||||
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version, Live: st.live && st.online}
|
||||
if e, ok := st.exports["24h"]; ok && st.online {
|
||||
s := e.Summary
|
||||
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
||||
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
||||
if len(s.Hosts) > 0 {
|
||||
hi.Location = s.Hosts[0].Location
|
||||
}
|
||||
}
|
||||
out = append(out, hi)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxLiveLine = 16 << 10 // longest SSE line accepted from a peer
|
||||
maxLiveRate = 50 // events per second accepted from one peer
|
||||
liveBuffer = 500 // events kept for /api/v1/live/recent
|
||||
liveIdle = 70 * time.Second
|
||||
liveBackoffTo = 60 * time.Second
|
||||
)
|
||||
|
||||
// Variables so tests can shrink them.
|
||||
var (
|
||||
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
|
||||
liveByteWindow = 10 * time.Second
|
||||
liveBackoff0 = time.Second
|
||||
)
|
||||
|
||||
type liveState struct {
|
||||
recent []store.LiveEvent // ring of the newest peer events
|
||||
head int
|
||||
subs map[chan store.LiveEvent]struct{}
|
||||
}
|
||||
|
||||
// Subscribe returns the live events relayed from peers; call stop when done.
|
||||
func (h *Hub) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
ch := make(chan store.LiveEvent, 64)
|
||||
h.lmu.Lock()
|
||||
if h.live.subs == nil {
|
||||
h.live.subs = map[chan store.LiveEvent]struct{}{}
|
||||
}
|
||||
h.live.subs[ch] = struct{}{}
|
||||
h.lmu.Unlock()
|
||||
return ch, func() {
|
||||
h.lmu.Lock()
|
||||
delete(h.live.subs, ch)
|
||||
h.lmu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Recent returns the newest relayed peer events, newest first.
|
||||
func (h *Hub) Recent(n int) []store.LiveEvent {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
total := len(h.live.recent)
|
||||
out := make([]store.LiveEvent, 0, min(n, total))
|
||||
for i := 0; i < total && len(out) < n; i++ {
|
||||
idx := ((h.live.head-1-i)%total + total) % total
|
||||
out = append(out, h.live.recent[idx])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Hub) publish(e store.LiveEvent) {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
if len(h.live.recent) < liveBuffer {
|
||||
h.live.recent = append(h.live.recent, e)
|
||||
} else {
|
||||
h.live.recent[h.live.head] = e
|
||||
h.live.head = (h.live.head + 1) % liveBuffer
|
||||
}
|
||||
for ch := range h.live.subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default: // slow client: drop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) setLive(name string, v bool) {
|
||||
h.mu.Lock()
|
||||
h.state[name].live = v
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// peerLocation is the location the peer reported in its last export.
|
||||
func (h *Hub) peerLocation(name string) *store.Location {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for _, e := range h.state[name].exports {
|
||||
if len(e.Summary.Hosts) > 0 && e.Summary.Hosts[0].Location != nil {
|
||||
l := *e.Summary.Hosts[0].Location
|
||||
return &l
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stream keeps one live subscription per peer until ctx is done, reconnecting
|
||||
// with an exponential backoff (1 s up to 60 s).
|
||||
func (h *Hub) Stream(ctx context.Context) {
|
||||
for _, p := range h.Peers {
|
||||
h.swg.Add(1)
|
||||
go func() { defer h.swg.Done(); h.streamPeer(ctx, p) }()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) streamPeer(ctx context.Context, p Peer) {
|
||||
back := liveBackoff0
|
||||
for ctx.Err() == nil {
|
||||
start := time.Now()
|
||||
h.consume(ctx, p)
|
||||
h.setLive(p.Name, false)
|
||||
if time.Since(start) > 2*liveBackoffTo {
|
||||
back = liveBackoff0 // it had been healthy for a while
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(back):
|
||||
}
|
||||
if back *= 2; back > liveBackoffTo {
|
||||
back = liveBackoffTo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var errLive = errors.New("live stream refused")
|
||||
|
||||
func (h *Hub) consume(ctx context.Context, p Peer) error {
|
||||
rctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
resp, err := h.stream.Do(req) // no redirects; https is enforced by ParsePeer
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
return errLive
|
||||
}
|
||||
idle := time.AfterFunc(liveIdle, cancel) // the peer pings every 20 s
|
||||
defer idle.Stop()
|
||||
h.setLive(p.Name, true)
|
||||
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
|
||||
var evName string
|
||||
var tokens = float64(maxLiveRate)
|
||||
winStart, winBytes := time.Now(), 0
|
||||
last := time.Now()
|
||||
for {
|
||||
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
idle.Reset(liveIdle)
|
||||
winBytes += len(line)
|
||||
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
|
||||
return errLive // a window's worth of budget burned already: flooding
|
||||
}
|
||||
if el := time.Since(winStart); el >= liveByteWindow {
|
||||
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
|
||||
return errLive // flooding: drop the connection, the backoff applies
|
||||
}
|
||||
winStart, winBytes = time.Now(), 0
|
||||
}
|
||||
line = bytes.TrimRight(line, "\r\n")
|
||||
switch {
|
||||
case bytes.HasPrefix(line, []byte("event:")):
|
||||
evName = strings.TrimSpace(string(line[6:]))
|
||||
case bytes.HasPrefix(line, []byte("data:")) && evName == "ev":
|
||||
now := time.Now()
|
||||
tokens += now.Sub(last).Seconds() * maxLiveRate
|
||||
if tokens > maxLiveRate {
|
||||
tokens = maxLiveRate
|
||||
}
|
||||
last = now
|
||||
if tokens < 1 {
|
||||
continue // over the budget: discard
|
||||
}
|
||||
tokens--
|
||||
var e store.LiveEvent
|
||||
if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) {
|
||||
continue
|
||||
}
|
||||
e.Host = p.Name
|
||||
if e.Dst == nil {
|
||||
e.Dst = h.peerLocation(p.Name)
|
||||
}
|
||||
h.publish(e)
|
||||
case len(line) == 0:
|
||||
evName = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func fakeStream(t *testing.T, conns *atomic.Int32, body func(w http.ResponseWriter)) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/peer/stream" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer tok" {
|
||||
http.Error(w, "no", 401)
|
||||
return
|
||||
}
|
||||
conns.Add(1)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(200)
|
||||
body(w)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
}
|
||||
|
||||
func ev(data string) string { return "event: ev\ndata: " + data + "\n\n" }
|
||||
|
||||
func TestLiveRelaySanitizesAndDrops(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
big := ev(`{"ip":"1.2.3.4","cat":"scanner","path":"` + strings.Repeat("a", 20000) + `"}`)
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, ": connected\n\n")
|
||||
fmt.Fprint(w, ev(`{"ip":"not-an-ip","cat":"scanner"}`))
|
||||
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"ok"}`)) // not malicious
|
||||
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"<script>"}`)) // unknown category
|
||||
fmt.Fprint(w, ev(`{"ip":"6.6.6.6","cat":"exploit","host":"evil","path":"/a\u0001b`+strings.Repeat("x", 500)+`","cc":"brasil","status":99999,"src":{"lat":500,"lon":1},"dst":{"lat":10,"lon":20,"label":"`+strings.Repeat("L", 200)+`"},"extra":"x"}`))
|
||||
fmt.Fprint(w, "event: other\ndata: {\"ip\":\"7.7.7.7\",\"cat\":\"exploit\"}\n\n")
|
||||
fmt.Fprint(w, ev(`{"ip":"8.8.8.8","cat":"scanner","src":{"lat":-8,"lon":-34,"cc":"BR","city":"Recife"}}`))
|
||||
fmt.Fprint(w, big) // over 16 KB: the stream is cut
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ch, stop := h.Subscribe()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
|
||||
var got []store.LiveEvent
|
||||
for len(got) < 2 {
|
||||
select {
|
||||
case e := <-ch:
|
||||
got = append(got, e)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("only %d events: %+v", len(got), got)
|
||||
}
|
||||
}
|
||||
a, b := got[0], got[1]
|
||||
if a.IP != "6.6.6.6" || a.Host != "edge" || a.Cat != "exploit" || a.CC != "" || a.Status != 0 || a.Src != nil {
|
||||
t.Fatalf("sanitized event %+v", a)
|
||||
}
|
||||
if strings.ContainsRune(a.Path, 1) || len(a.Path) > 240 || a.Dst == nil || len(a.Dst.Label) != 64 {
|
||||
t.Fatalf("strings %q dst %+v", a.Path, a.Dst)
|
||||
}
|
||||
if b.IP != "8.8.8.8" || b.Src == nil || b.Src.City != "Recife" || b.Host != "edge" {
|
||||
t.Fatalf("second %+v", b)
|
||||
}
|
||||
if r := h.Recent(10); len(r) != 2 || r[0].IP != "8.8.8.8" {
|
||||
t.Fatalf("recent %+v", r)
|
||||
}
|
||||
// the oversize line ended the stream: no event from it, and the hub reconnects
|
||||
deadline := time.After(5 * time.Second)
|
||||
for conns.Load() < 2 {
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatalf("no reconnection (%d)", conns.Load())
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
select {
|
||||
case e := <-ch:
|
||||
if e.IP == "1.2.3.4" {
|
||||
t.Fatal("oversize line must not become an event")
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveRateLimitAndFlag(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
for i := 0; i < 400; i++ {
|
||||
fmt.Fprint(w, ev(fmt.Sprintf(`{"ip":"9.9.%d.%d","cat":"scanner"}`, i/250, i%250+1)))
|
||||
}
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if n := len(h.Recent(500)); n < 40 || n > 120 {
|
||||
t.Fatalf("a burst of 400 must be cut to about 50 (got %d)", n)
|
||||
}
|
||||
if hs := h.Hosts(); len(hs) != 1 || hs[0].Live {
|
||||
// Live also needs the peer to be online (polled); here it never was
|
||||
t.Fatalf("hosts %+v", hs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveWithRealPeerServer(t *testing.T) {
|
||||
ps := store.New(store.Config{Name: "remote", Version: "t", Location: &store.Location{Lat: -8, Lon: -35, Label: "Recife"}})
|
||||
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Refresh(ctx)
|
||||
h.Stream(ctx)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
if len(h.Recent(5)) > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
r := h.Recent(5)
|
||||
if len(r) == 0 || r[0].Host != "edge" || r[0].IP != "5.5.5.5" || r[0].Dst == nil || r[0].Dst.Label != "Recife" {
|
||||
t.Fatalf("relayed %+v", r)
|
||||
}
|
||||
hs := h.Hosts()
|
||||
if !hs[0].Live || !hs[0].Online || hs[0].Location == nil || hs[0].Location.Label != "Recife" {
|
||||
t.Fatalf("hosts %+v", hs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveByteFloodDropsConnection(t *testing.T) {
|
||||
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
|
||||
start := time.Now()
|
||||
var conns atomic.Int32
|
||||
pad := strings.Repeat("a", 1000)
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
|
||||
fmt.Fprintf(w, ": %s\n", pad)
|
||||
}
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
// the flood ends the connection (window check), then the hub reconnects after the backoff
|
||||
for conns.Load() < 2 {
|
||||
if time.Since(start) > 2500*time.Millisecond {
|
||||
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
geoCountries = 250
|
||||
geoRegions = 64
|
||||
geoCities = 200
|
||||
geoIPs = 50
|
||||
geoTTL = 5 * time.Second
|
||||
geoCacheMax = 256
|
||||
)
|
||||
|
||||
var ccRe = regexp.MustCompile(`^[A-Z]{2}$`)
|
||||
|
||||
type geoCache struct {
|
||||
mu sync.Mutex
|
||||
at map[string]time.Time
|
||||
v map[string]any
|
||||
}
|
||||
|
||||
type regionOut struct {
|
||||
Name string `json:"name"`
|
||||
Events uint64 `json:"events"`
|
||||
IPs int `json:"ips"`
|
||||
Cats map[string]int `json:"cats"`
|
||||
}
|
||||
|
||||
type cityOut struct {
|
||||
Name string `json:"name"`
|
||||
Region string `json:"region"`
|
||||
Lat *float64 `json:"lat,omitempty"`
|
||||
Lon *float64 `json:"lon,omitempty"`
|
||||
Events uint64 `json:"events"`
|
||||
IPs int `json:"ips"`
|
||||
}
|
||||
|
||||
type geoIPOut struct {
|
||||
IP string `json:"ip"`
|
||||
Score float64 `json:"score"`
|
||||
Level string `json:"level"`
|
||||
City string `json:"city"`
|
||||
Reg string `json:"region"`
|
||||
ASN uint32 `json:"asn"`
|
||||
ASOrg string `json:"as_org"`
|
||||
Last int64 `json:"last"`
|
||||
}
|
||||
|
||||
type countryOut struct {
|
||||
CC string `json:"cc"`
|
||||
Events uint64 `json:"events"`
|
||||
IPs int `json:"ips"`
|
||||
Hostile int `json:"hostile"`
|
||||
Suspicious int `json:"suspicious"`
|
||||
Cats map[string]int `json:"cats"`
|
||||
}
|
||||
|
||||
type agg struct {
|
||||
events uint64
|
||||
ips int
|
||||
hostile, suspic int
|
||||
cats map[string]int
|
||||
}
|
||||
|
||||
func (a *agg) add(x store.IPSummary, ev uint64, cats map[string]int) {
|
||||
if a.cats == nil {
|
||||
a.cats = map[string]int{}
|
||||
}
|
||||
a.events += ev
|
||||
a.ips++
|
||||
switch x.Level {
|
||||
case core.LevelHostile:
|
||||
a.hostile++
|
||||
case core.LevelSuspicious:
|
||||
a.suspic++
|
||||
}
|
||||
for k, v := range cats {
|
||||
a.cats[k] += v
|
||||
}
|
||||
}
|
||||
|
||||
// attackerEvents sums the malicious category counts of an IP row.
|
||||
func attackerEvents(x store.IPSummary) (uint64, map[string]int) {
|
||||
var n uint64
|
||||
cats := map[string]int{}
|
||||
for _, c := range core.Categories {
|
||||
if !c.IsMalicious() {
|
||||
continue
|
||||
}
|
||||
if v := x.Counts[string(c)]; v > 0 {
|
||||
n += uint64(v)
|
||||
cats[string(c)] = int(v)
|
||||
}
|
||||
}
|
||||
return n, cats
|
||||
}
|
||||
|
||||
// geoAPI serves GET /api/v1/geo (see the package documentation of the routes).
|
||||
func (s *Server) geoAPI(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
rg := store.ParseRange(q.Get("range")).Name
|
||||
host := q.Get("host")
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
cc, region := q.Get("cc"), q.Get("region")
|
||||
if cc != "" && !ccRe.MatchString(cc) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid cc"})
|
||||
return
|
||||
}
|
||||
if region != "" && (cc == "" || len(region) > 80) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid region"})
|
||||
return
|
||||
}
|
||||
key := strings.Join([]string{rg, host, cc, region}, "\x00")
|
||||
s.geo.mu.Lock()
|
||||
defer s.geo.mu.Unlock()
|
||||
if v, ok := s.geo.v[key]; ok && time.Since(s.geo.at[key]) < geoTTL {
|
||||
writeJSON(w, 200, v)
|
||||
return
|
||||
}
|
||||
if s.geo.v == nil || len(s.geo.v) >= geoCacheMax {
|
||||
s.geo.v, s.geo.at = map[string]any{}, map[string]time.Time{}
|
||||
}
|
||||
var out any
|
||||
if cc == "" {
|
||||
out = s.geoWorld(rg, host)
|
||||
} else {
|
||||
out = s.geoCountry(rg, host, cc, region)
|
||||
}
|
||||
s.geo.v[key], s.geo.at[key] = out, time.Now()
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// geoOf resolves the geography of a row: the local databases first, the data
|
||||
// the row already carries (a peer's) as the fallback for country and city.
|
||||
func (s *Server) geoOf(x store.IPSummary) core.GeoInfo {
|
||||
g := s.opt.Store.GeoOf(x.IP)
|
||||
if g.CC == "" && ccRe.MatchString(x.CC) {
|
||||
g.CC, g.Country, g.City = x.CC, x.Country, x.City
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func (s *Server) geoWorld(rg, host string) map[string]any {
|
||||
by := map[string]*agg{}
|
||||
for _, x := range s.allIPs(rg, host) {
|
||||
ev, cats := attackerEvents(x)
|
||||
if ev == 0 {
|
||||
continue
|
||||
}
|
||||
g := s.geoOf(x)
|
||||
if g.CC == "" {
|
||||
continue
|
||||
}
|
||||
a := by[g.CC]
|
||||
if a == nil {
|
||||
a = &agg{}
|
||||
by[g.CC] = a
|
||||
}
|
||||
a.add(x, ev, cats)
|
||||
}
|
||||
list := make([]countryOut, 0, len(by))
|
||||
for cc, a := range by {
|
||||
list = append(list, countryOut{cc, a.events, a.ips, a.hostile, a.suspic, a.cats})
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool {
|
||||
if list[i].Events != list[j].Events {
|
||||
return list[i].Events > list[j].Events
|
||||
}
|
||||
return list[i].CC < list[j].CC
|
||||
})
|
||||
if len(list) > geoCountries {
|
||||
list = list[:geoCountries]
|
||||
}
|
||||
return map[string]any{"range": rg, "host": host, "countries": list}
|
||||
}
|
||||
|
||||
func (s *Server) geoCountry(rg, host, cc, region string) map[string]any {
|
||||
total := &agg{}
|
||||
regs := map[string]*agg{}
|
||||
type ck struct{ name, region string }
|
||||
cities := map[ck]*cityOut{}
|
||||
var rows []geoIPOut
|
||||
for _, x := range s.allIPs(rg, host) {
|
||||
ev, cats := attackerEvents(x)
|
||||
if ev == 0 {
|
||||
continue
|
||||
}
|
||||
g := s.geoOf(x)
|
||||
if g.CC != cc {
|
||||
continue
|
||||
}
|
||||
ra := regs[g.Region]
|
||||
if ra == nil {
|
||||
ra = &agg{}
|
||||
regs[g.Region] = ra
|
||||
}
|
||||
ra.add(x, ev, cats)
|
||||
if region != "" && g.Region != region {
|
||||
continue
|
||||
}
|
||||
total.add(x, ev, cats)
|
||||
c := cities[ck{g.City, g.Region}]
|
||||
if c == nil {
|
||||
c = &cityOut{Name: g.City, Region: g.Region}
|
||||
if (g.Lat != 0 || g.Lon != 0) && g.Lat >= -90 && g.Lat <= 90 && g.Lon >= -180 && g.Lon <= 180 {
|
||||
lat, lon := g.Lat, g.Lon
|
||||
c.Lat, c.Lon = &lat, &lon
|
||||
}
|
||||
cities[ck{g.City, g.Region}] = c
|
||||
}
|
||||
c.Events += ev
|
||||
c.IPs++
|
||||
s.opt.Store.Enrich(&x)
|
||||
rows = append(rows, geoIPOut{IP: x.IP, Score: x.Score, Level: string(x.Level), City: g.City, Reg: g.Region,
|
||||
ASN: g.ASN, ASOrg: g.ASOrg, Last: x.Last})
|
||||
}
|
||||
if total.cats == nil {
|
||||
total.cats = map[string]int{}
|
||||
}
|
||||
rl := make([]regionOut, 0, len(regs))
|
||||
for name, a := range regs {
|
||||
rl = append(rl, regionOut{name, a.events, a.ips, a.cats})
|
||||
}
|
||||
sort.Slice(rl, func(i, j int) bool {
|
||||
if rl[i].Events != rl[j].Events {
|
||||
return rl[i].Events > rl[j].Events
|
||||
}
|
||||
return rl[i].Name < rl[j].Name
|
||||
})
|
||||
if len(rl) > geoRegions {
|
||||
rl = rl[:geoRegions]
|
||||
}
|
||||
cl := make([]cityOut, 0, len(cities))
|
||||
for _, c := range cities {
|
||||
cl = append(cl, *c)
|
||||
}
|
||||
sort.Slice(cl, func(i, j int) bool {
|
||||
if cl[i].Events != cl[j].Events {
|
||||
return cl[i].Events > cl[j].Events
|
||||
}
|
||||
return cl[i].Name < cl[j].Name
|
||||
})
|
||||
if len(cl) > geoCities {
|
||||
cl = cl[:geoCities]
|
||||
}
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
if rows[i].Score != rows[j].Score {
|
||||
return rows[i].Score > rows[j].Score
|
||||
}
|
||||
return rows[i].IP < rows[j].IP
|
||||
})
|
||||
if len(rows) > geoIPs {
|
||||
rows = rows[:geoIPs]
|
||||
}
|
||||
out := map[string]any{"range": rg, "host": host, "cc": cc, "events": total.events, "ips": total.ips,
|
||||
"hostile": total.hostile, "suspicious": total.suspic, "cats": total.cats,
|
||||
"regions": rl, "cities": cl, "top_ips": rows}
|
||||
if region != "" {
|
||||
out["region"] = region
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
type fakeGeo struct{}
|
||||
|
||||
func (fakeGeo) Geo(ip string) core.GeoInfo {
|
||||
switch {
|
||||
case strings.HasPrefix(ip, "200.1.1."):
|
||||
return core.GeoInfo{CC: "BR", Country: "Brazil", Region: "Pernambuco", City: "Recife", Lat: -8.05, Lon: -34.9, ASN: 64500, ASOrg: "Net A"}
|
||||
case strings.HasPrefix(ip, "200.2.2."):
|
||||
return core.GeoInfo{CC: "BR", Country: "Brazil", Region: "Sao Paulo", City: "Campinas"} // no coordinates
|
||||
case strings.HasPrefix(ip, "200.3.3."):
|
||||
return core.GeoInfo{CC: "BR", Country: "Brazil", City: "Nowhere"} // empty region
|
||||
case strings.HasPrefix(ip, "9.9.9."):
|
||||
return core.GeoInfo{CC: "US", Region: "Texas", City: "Austin", Lat: 30.2, Lon: -97.7}
|
||||
}
|
||||
return core.GeoInfo{}
|
||||
}
|
||||
func (fakeGeo) UA(string) core.UAInfo { return core.UAInfo{} }
|
||||
|
||||
func geoSetup(t *testing.T) (http.Handler, map[string]string) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Location: &store.Location{Lat: 1, Lon: 2, Label: "Home"}})
|
||||
st.SetEnricher(fakeGeo{})
|
||||
now := time.Now()
|
||||
ing := func(ip string, c core.Category, n int, strong bool) {
|
||||
for i := 0; i < n; i++ {
|
||||
st.Ingest(core.Event{Time: now, IP: ip, Cat: c, Strong: strong, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
}
|
||||
}
|
||||
ing("200.1.1.1", core.Exploit, 8, true) // 64 points: hostile
|
||||
ing("200.1.1.2", core.Scanner, 2, false)
|
||||
ing("200.1.1.3", core.NotFound, 5, false) // not malicious: ignored
|
||||
ing("200.2.2.2", core.Scanner, 5, false)
|
||||
ing("200.3.3.3", core.BruteForce, 1, false)
|
||||
ing("9.9.9.9", core.SSHFail, 3, false)
|
||||
ing("8.8.8.8", core.Exploit, 1, false) // unknown geo: skipped
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st})
|
||||
return h, map[string]string{"Authorization": "Bearer " + utok}
|
||||
}
|
||||
|
||||
func getJSON(t *testing.T, h http.Handler, path string, hd map[string]string) map[string]any {
|
||||
w := do(h, "GET", path, cloneHdr(hd), nil)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func cloneHdr(h map[string]string) map[string]string {
|
||||
o := map[string]string{}
|
||||
for k, v := range h {
|
||||
o[k] = v
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func TestGeoAggregation(t *testing.T) {
|
||||
h, u := geoSetup(t)
|
||||
m := getJSON(t, h, "/api/v1/geo?range=24h&host=all", u)
|
||||
cs := m["countries"].([]any)
|
||||
if m["range"] != "24h" || len(cs) != 2 {
|
||||
t.Fatalf("%v", m)
|
||||
}
|
||||
br := cs[0].(map[string]any)
|
||||
if br["cc"] != "BR" || br["events"].(float64) != 8+2+5+1 || br["ips"].(float64) != 4 || br["hostile"].(float64) != 1 {
|
||||
t.Fatalf("BR %v", br)
|
||||
}
|
||||
if c := br["cats"].(map[string]any); c["exploit"].(float64) != 8 || c["scanner"].(float64) != 7 || c["notfound"] != nil {
|
||||
t.Fatalf("cats %v", c)
|
||||
}
|
||||
if cs[1].(map[string]any)["cc"] != "US" {
|
||||
t.Fatalf("order %v", cs)
|
||||
}
|
||||
|
||||
d := getJSON(t, h, "/api/v1/geo?cc=BR", u)
|
||||
if d["cc"] != "BR" || len(d["regions"].([]any)) != 3 || len(d["cities"].([]any)) != 3 || len(d["top_ips"].([]any)) != 4 {
|
||||
t.Fatalf("detail %v", d)
|
||||
}
|
||||
top := d["top_ips"].([]any)[0].(map[string]any)
|
||||
if top["ip"] != "200.1.1.1" || top["level"] != "hostile" || top["city"] != "Recife" || top["asn"].(float64) != 64500 {
|
||||
t.Fatalf("top ip %v", top)
|
||||
}
|
||||
for _, c := range d["cities"].([]any) {
|
||||
c := c.(map[string]any)
|
||||
_, hasLat := c["lat"]
|
||||
if (c["name"] == "Recife") != hasLat {
|
||||
t.Fatalf("coordinates only for cities that have them: %v", c)
|
||||
}
|
||||
}
|
||||
empty := false
|
||||
for _, r := range d["regions"].([]any) {
|
||||
empty = empty || r.(map[string]any)["name"] == ""
|
||||
}
|
||||
if !empty {
|
||||
t.Fatal("empty region must be kept as an empty name")
|
||||
}
|
||||
|
||||
r := getJSON(t, h, "/api/v1/geo?cc=BR®ion=Pernambuco", u)
|
||||
if r["events"].(float64) != 10 || len(r["cities"].([]any)) != 1 || len(r["top_ips"].([]any)) != 2 || r["ips"].(float64) != 2 || r["region"] != "Pernambuco" {
|
||||
t.Fatalf("region %v", r)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo?cc=br", cloneHdr(u), nil); w.Code != 400 {
|
||||
t.Fatalf("lowercase cc: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo?host=nope", cloneHdr(u), nil); w.Code != 404 {
|
||||
t.Fatalf("unknown host: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocationOnSummaryAndRecent(t *testing.T) {
|
||||
h, u := geoSetup(t)
|
||||
m := getJSON(t, h, "/api/v1/summary", u)
|
||||
loc := m["hosts"].([]any)[0].(map[string]any)["location"].(map[string]any)
|
||||
if loc["lat"].(float64) != 1 || loc["label"] != "Home" {
|
||||
t.Fatalf("%v", loc)
|
||||
}
|
||||
rc := getJSON(t, h, "/api/v1/live/recent?limit=3", u)["events"].([]any)
|
||||
if len(rc) != 3 {
|
||||
t.Fatalf("limit: %d", len(rc))
|
||||
}
|
||||
all := getJSON(t, h, "/api/v1/live/recent?limit=9999", u)["events"].([]any)
|
||||
if len(all) != 8+2+5+1+3+1 {
|
||||
t.Fatalf("only malicious events: %d", len(all))
|
||||
}
|
||||
var seenSrc bool
|
||||
for _, e := range all {
|
||||
e := e.(map[string]any)
|
||||
if e["host"] != "oracle" || e["dst"].(map[string]any)["label"] != "Home" || e["cat"] == "notfound" {
|
||||
t.Fatalf("event %v", e)
|
||||
}
|
||||
if s, ok := e["src"].(map[string]any); ok && e["ip"] == "200.1.1.1" {
|
||||
seenSrc = s["cc"] == "BR" && s["city"] == "Recife"
|
||||
}
|
||||
if e["ip"] == "8.8.8.8" && e["src"] != nil {
|
||||
t.Fatal("src omitted when unknown")
|
||||
}
|
||||
}
|
||||
if !seenSrc {
|
||||
t.Fatal("src missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticAssetsWhitelist(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
if w := do(h, "GET", "/style.css", nil, nil); w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/css") || w.Header().Get("Content-Security-Policy") == "" {
|
||||
t.Fatalf("css %d %v", w.Code, w.Header())
|
||||
}
|
||||
if w := do(h, "GET", "/logo.png", nil, nil); w.Code != 200 || w.Header().Get("Content-Type") != "image/png" {
|
||||
t.Fatalf("png %d", w.Code)
|
||||
}
|
||||
for _, p := range []string{"/index.html", "/login.html", "/missing.js", "/Style.css", "/web", "/..%2fserver.go", "/%2e%2e/go.mod", "/a.go", "/.js", "/app.js/", "/x/app.js"} {
|
||||
if w := do(h, "GET", p, nil, nil); w.Code == 200 {
|
||||
t.Errorf("%s must not be served (200)", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerStreamIsPeerOnly(t *testing.T) {
|
||||
old := sseHeartbeat
|
||||
sseHeartbeat = 50 * time.Millisecond
|
||||
defer func() { sseHeartbeat = old }()
|
||||
h, _ := geoSetup(t)
|
||||
if w := do(h, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + utok}, nil); w.Code != 401 {
|
||||
t.Fatalf("user token: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/stream", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous: %d", w.Code)
|
||||
}
|
||||
for _, p := range []string{"/api/v1/events/stream"} {
|
||||
if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token on %s: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
h2 := New(Options{Token: utok, PeerAllow: mustPrefixes("203.0.113.0/24"), PeerTokens: []string{ptok}, Version: "t", Store: store.New(store.Config{Name: "x"})})
|
||||
if w := do(h2, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("--peer-allow: %d", w.Code)
|
||||
}
|
||||
h3 := New(Options{Token: utok, Version: "t", Store: store.New(store.Config{Name: "x"})})
|
||||
if w := do(h3, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 404 {
|
||||
t.Fatalf("federation off: %d", w.Code)
|
||||
}
|
||||
|
||||
st := store.New(store.Config{Name: "edge", Version: "t", Location: &store.Location{Lat: 3, Lon: 4, Label: "Edge"}})
|
||||
st.SetEnricher(fakeGeo{})
|
||||
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
|
||||
defer ts.Close()
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+ptok)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
t.Fatal(err, resp)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik"}) // not malicious, not sent
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp"})
|
||||
}()
|
||||
sc := bufio.NewScanner(resp.Body)
|
||||
deadline := time.After(5 * time.Second)
|
||||
got := make(chan string, 1)
|
||||
go func() {
|
||||
for sc.Scan() {
|
||||
if strings.HasPrefix(sc.Text(), "data: ") {
|
||||
got <- sc.Text()[6:]
|
||||
return
|
||||
}
|
||||
}
|
||||
got <- ""
|
||||
}()
|
||||
select {
|
||||
case d := <-got:
|
||||
var e map[string]any
|
||||
if json.Unmarshal([]byte(d), &e) != nil || e["ip"] != "200.1.1.9" || e["cat"] != "scanner" || e["dst"].(map[string]any)["label"] != "Edge" || e["src"].(map[string]any)["cc"] != "BR" {
|
||||
t.Fatalf("peer event %s", d)
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatal("no event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
|
||||
const ptk = "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
strongHits := func(st *store.Store, ip string) {
|
||||
for i := 0; i < 8; i++ {
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
}
|
||||
}
|
||||
remote := store.New(store.Config{Name: "remote"})
|
||||
strongHits(remote, "45.94.31.7") // only the peer saw it
|
||||
rs := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptk}, Store: remote}))
|
||||
defer rs.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + rs.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, ptk)
|
||||
hub.Refresh(context.Background())
|
||||
for _, off := range []bool{false, true} {
|
||||
st := store.New(store.Config{Name: "o"})
|
||||
strongHits(st, "45.94.31.5")
|
||||
hh := New(Options{Token: utok, Store: st, Hub: hub, LocalBlocklist: off})
|
||||
w := do(hh, "GET", "/api/v1/blocklist.txt", map[string]string{"Authorization": "Bearer " + utok}, nil)
|
||||
b := w.Body.String()
|
||||
if w.Code != 200 || !strings.Contains(b, "45.94.31.5") {
|
||||
t.Fatalf("off=%v: local IP missing: %d %s", off, w.Code, b)
|
||||
}
|
||||
if has := strings.Contains(b, "45.94.31.7"); has == off {
|
||||
t.Fatalf("off=%v: peer-only IP listed=%v: %s", off, has, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
-16
@@ -11,6 +11,7 @@ import (
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -29,6 +30,9 @@ var webFS embed.FS
|
||||
// maxSSE bounds the simultaneous live streams.
|
||||
const maxSSE = 20
|
||||
|
||||
// maxPeerSSE bounds the simultaneous hub subscriptions to /api/v1/peer/stream.
|
||||
const maxPeerSSE = 10
|
||||
|
||||
// sseHeartbeat is how often a live stream pings and revalidates its session.
|
||||
var sseHeartbeat = 20 * time.Second
|
||||
|
||||
@@ -58,10 +62,12 @@ type Options struct {
|
||||
PeerAllow []netip.Prefix
|
||||
TrustedProxy []netip.Prefix
|
||||
NoAuth bool
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
Now func() time.Time
|
||||
// LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off).
|
||||
LocalBlocklist bool
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Server is the HTTP handler.
|
||||
@@ -73,6 +79,8 @@ type Server struct {
|
||||
lim *limiter
|
||||
mux *http.ServeMux
|
||||
assets fs.FS
|
||||
geo geoCache
|
||||
psse atomic.Int32
|
||||
}
|
||||
|
||||
// New builds the handler.
|
||||
@@ -88,11 +96,11 @@ func New(opt Options) http.Handler {
|
||||
m.HandleFunc("POST /login", s.login)
|
||||
m.HandleFunc("POST /logout", s.logout)
|
||||
m.HandleFunc("GET /{$}", s.index)
|
||||
for _, f := range []string{"/style.css", "/app.js", "/i18n.js", "/login.js", "/logo.png", "/favicon.png", "/world.js"} {
|
||||
name := strings.TrimPrefix(f, "/")
|
||||
m.HandleFunc("GET "+f, func(w http.ResponseWriter, r *http.Request) { s.static(w, r, name) })
|
||||
}
|
||||
m.HandleFunc("GET /{file}", s.asset)
|
||||
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
|
||||
m.HandleFunc("GET /api/v1/peer/stream", s.peerStream)
|
||||
m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI))
|
||||
m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent))
|
||||
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
|
||||
m.HandleFunc("GET /api/v1/traffic", s.api(s.traffic))
|
||||
m.HandleFunc("GET /api/v1/ips", s.api(s.ips))
|
||||
@@ -220,17 +228,18 @@ type exportCache struct {
|
||||
v map[string][]byte
|
||||
}
|
||||
|
||||
// peerExport is the only route the peer token opens: GET /api/v1/peer/export.
|
||||
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
// peerGate admits only the federation token (and --peer-allow sources); it
|
||||
// answers the request itself and returns false when it refuses.
|
||||
func (s *Server) peerGate(w http.ResponseWriter, r *http.Request) bool {
|
||||
if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"})
|
||||
return
|
||||
return false
|
||||
}
|
||||
if len(s.opt.PeerAllow) > 0 {
|
||||
a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy))
|
||||
if err != nil || !prefixesContain(s.opt.PeerAllow, a) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"})
|
||||
return
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
@@ -239,6 +248,14 @@ func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// peerExport: GET /api/v1/peer/export, opened by the peer token.
|
||||
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
rg := store.ParseRange(r.URL.Query().Get("range")).Name
|
||||
@@ -267,6 +284,22 @@ func prefixesContain(ps []netip.Prefix, a netip.Addr) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var assetRe = regexp.MustCompile(`^[a-z0-9-]+\.(js|css|png|svg|json)$`)
|
||||
|
||||
// asset serves a top-level file of the embedded web directory by name.
|
||||
func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("file")
|
||||
if !assetRe.MatchString(name) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if st, err := fs.Stat(s.assets, name); err != nil || !st.Mode().IsRegular() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
s.static(w, r, name)
|
||||
}
|
||||
|
||||
func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) {
|
||||
b, err := fs.ReadFile(s.assets, name)
|
||||
if err != nil {
|
||||
@@ -281,6 +314,10 @@ func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) {
|
||||
ct = "text/javascript; charset=utf-8"
|
||||
case strings.HasSuffix(name, ".png"):
|
||||
ct = "image/png"
|
||||
case strings.HasSuffix(name, ".svg"):
|
||||
ct = "image/svg+xml"
|
||||
case strings.HasSuffix(name, ".json"):
|
||||
ct = "application/json; charset=utf-8"
|
||||
case strings.HasSuffix(name, ".html"):
|
||||
ct = "text/html; charset=utf-8"
|
||||
}
|
||||
@@ -429,13 +466,17 @@ func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// allIPs returns the merged IP table for the requested host selection.
|
||||
func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
|
||||
return s.ipsOf(rangeName, host, false)
|
||||
}
|
||||
|
||||
func (s *Server) ipsOf(rangeName, host string, localOnly bool) []store.IPSummary {
|
||||
rg := store.ParseRange(rangeName)
|
||||
var lists [][]store.IPSummary
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" || host == self {
|
||||
lists = append(lists, s.opt.Store.AllIPs(rg, false))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
if s.opt.Hub != nil && host != self && !localOnly {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
@@ -539,10 +580,27 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
ch, stop := s.opt.Store.Subscribe()
|
||||
defer stop()
|
||||
var hubCh <-chan store.LiveEvent // nil blocks forever: no hub, no peer events
|
||||
if s.opt.Hub != nil {
|
||||
c, stopHub := s.opt.Hub.Subscribe()
|
||||
defer stopHub()
|
||||
hubCh = c
|
||||
}
|
||||
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
|
||||
fl.Flush()
|
||||
tick := time.NewTicker(sseHeartbeat)
|
||||
defer tick.Stop()
|
||||
send := func(e store.LiveEvent) bool {
|
||||
if k := s.authKind(r); k != "session" && k != "bearer" {
|
||||
return false
|
||||
}
|
||||
b, _ := json.Marshal(e)
|
||||
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
|
||||
return false
|
||||
}
|
||||
fl.Flush()
|
||||
return true
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
@@ -556,10 +614,63 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
fl.Flush()
|
||||
case e := <-ch:
|
||||
if k := s.authKind(r); k != "session" && k != "bearer" {
|
||||
if !send(s.opt.Store.Live(e)) {
|
||||
return
|
||||
}
|
||||
b, _ := json.Marshal(e)
|
||||
case e := <-hubCh:
|
||||
if !send(e) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// peerStream: GET /api/v1/peer/stream, SSE of this instance's own malicious
|
||||
// events for a hub. Opened only by the peer token, like the export.
|
||||
func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
fl, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", 500)
|
||||
return
|
||||
}
|
||||
if s.psse.Add(1) > maxPeerSSE {
|
||||
s.psse.Add(-1)
|
||||
w.Header().Set("Retry-After", "10")
|
||||
http.Error(w, "too many peer streams", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer s.psse.Add(-1)
|
||||
_ = http.NewResponseController(w).SetWriteDeadline(time.Time{})
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
ch, stop := s.opt.Store.Subscribe()
|
||||
defer stop()
|
||||
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
|
||||
fl.Flush()
|
||||
tick := time.NewTicker(sseHeartbeat)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
return
|
||||
}
|
||||
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case e := <-ch:
|
||||
if !core.Category(e.Cat).IsMalicious() {
|
||||
continue
|
||||
}
|
||||
b, _ := json.Marshal(s.opt.Store.Live(e))
|
||||
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -568,6 +679,26 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// liveRecent: GET /api/v1/live/recent?limit=200 (max 500), newest first, local and peers.
|
||||
func (s *Server) liveRecent(w http.ResponseWriter, r *http.Request) {
|
||||
n, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
if n < 1 {
|
||||
n = 200
|
||||
}
|
||||
if n > 500 {
|
||||
n = 500
|
||||
}
|
||||
list := s.opt.Store.LiveRecent(n)
|
||||
if s.opt.Hub != nil {
|
||||
list = append(list, s.opt.Hub.Recent(n)...)
|
||||
}
|
||||
sort.SliceStable(list, func(i, j int) bool { return list[i].T > list[j].T })
|
||||
if len(list) > n {
|
||||
list = list[:n]
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"events": list})
|
||||
}
|
||||
|
||||
func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
@@ -586,7 +717,7 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
|
||||
family = "all"
|
||||
}
|
||||
var out []store.IPSummary
|
||||
for _, x := range s.allIPs(rangeName, q.Get("host")) {
|
||||
for _, x := range s.ipsOf(rangeName, q.Get("host"), s.opt.LocalBlocklist) {
|
||||
if x.Score < min || !x.Strong || x.Admin {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -253,7 +253,7 @@ func TestPeerTokenOnlyOpensExport(t *testing.T) {
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream",
|
||||
"/api/v1/blocklist.txt", "/api/v1/blocklist.json"} {
|
||||
"/api/v1/blocklist.txt", "/api/v1/blocklist.json", "/api/v1/geo", "/api/v1/live/recent"} {
|
||||
if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden {
|
||||
t.Errorf("peer token on %s: %d (want 403)", p, w.Code)
|
||||
}
|
||||
|
||||
+1179
-603
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,101 @@
|
||||
/* Urutau - página Geografia. Só tokens do shell; sem cores fixas além do fallback. */
|
||||
.geo { display: grid; gap: 14px; min-width: 0; }
|
||||
.geo.is-busy .geo-main, .geo.is-busy .geo-detail { opacity: .72; transition: opacity .2s; }
|
||||
.geo-top { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: space-between; }
|
||||
.geo-crumbs { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-width: 0; font-size: 14px; }
|
||||
.geo-crumb { background: none; border: 0; padding: 4px 6px; margin: 0 -2px; border-radius: 8px; color: var(--accent); cursor: pointer; font: inherit; }
|
||||
.geo-crumb:hover { background: var(--surface-raised); text-decoration: underline; }
|
||||
.geo-crumb.cur { color: var(--ink); font-weight: 600; padding: 4px 2px; overflow-wrap: anywhere; }
|
||||
.geo-sep { color: var(--ink-muted); }
|
||||
.geo-back, .geo-retry, .geo-chip {
|
||||
background: var(--surface-raised); border: 1px solid var(--line); border-radius: 10px; padding: 6px 12px; min-height: 36px; cursor: pointer; color: var(--ink);
|
||||
}
|
||||
.geo-back:hover, .geo-retry:hover, .geo-chip:hover { border-color: var(--accent); }
|
||||
.geo-back[hidden] { display: none; }
|
||||
/* o texto de abertura usa o .lead do shell */
|
||||
.geo-leadbox { min-height: 70px; }
|
||||
.geo-lead { max-width: none !important; }
|
||||
.geo-lead:focus { outline: none; }
|
||||
.geo-err { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; padding: 12px 14px; border-radius: 12px; border: 1px solid var(--danger); background: color-mix(in srgb, var(--danger) 10%, transparent); }
|
||||
.geo-err[hidden] { display: none; }
|
||||
|
||||
.geo-main { display: grid; grid-template-columns: minmax(0, 2fr) minmax(280px, 1fr); gap: 14px; align-items: stretch; }
|
||||
.geo-panel { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; box-shadow: var(--shadow); min-width: 0; }
|
||||
.geo-panel h2 { font: 700 1rem/1.3 var(--font-display); color: var(--heading); margin: 0 0 10px; }
|
||||
.geo-panel h2:focus { outline: none; }
|
||||
.geo-mappanel { padding: 10px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.geo-map { position: relative; width: 100%; aspect-ratio: 2000 / 789; min-height: 240px; overflow: hidden; border-radius: 10px; background: color-mix(in srgb, var(--surface-sunken) 60%, transparent); }
|
||||
.geo-svg { width: 100%; height: 100%; display: block; }
|
||||
.geo-cn { fill: var(--ink-muted); fill-opacity: .14; stroke: var(--line); stroke-width: 1; vector-effect: non-scaling-stroke; transition: opacity .3s; }
|
||||
.geo-cn.hit { fill: var(--accent); cursor: pointer; stroke: color-mix(in srgb, var(--accent) 45%, var(--line)); }
|
||||
.geo-cn.hit:hover { stroke: var(--ink); stroke-width: 1.6; }
|
||||
.geo-svg.zoomed .geo-cn:not(.sel) { opacity: .35; }
|
||||
.geo-svg.zoomed .geo-cn.sel { fill: var(--accent); fill-opacity: .22 !important; stroke: var(--accent); stroke-width: 1.5; cursor: default; }
|
||||
.geo-city { fill: var(--viz-7); fill-opacity: .5; stroke: var(--danger); stroke-width: 1.2; vector-effect: non-scaling-stroke; animation: geo-in .35s ease-out; }
|
||||
.geo-city-click { cursor: pointer; }
|
||||
.geo-city:hover, .geo-city.hl { fill-opacity: .85; stroke: var(--ink); stroke-width: 2; }
|
||||
@keyframes geo-in { from { opacity: 0; } to { opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) { .geo-city { animation: none; } .geo-cn { transition: none; } }
|
||||
.geo-tip { position: absolute; pointer-events: none; z-index: 5; background: var(--surface-overlay); border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; font-size: 12px; min-width: 140px; max-width: 260px; box-shadow: var(--shadow); }
|
||||
.geo-tip[hidden], .geo-loading[hidden], .geo-legend[hidden], .geo-detail[hidden] { display: none; }
|
||||
.geo-tip-h { font-weight: 600; margin-bottom: 4px; overflow-wrap: anywhere; }
|
||||
.geo-tip-r { display: flex; justify-content: space-between; gap: 12px; color: var(--ink-muted); }
|
||||
.geo-tip-r b { color: var(--ink); font-weight: 600; text-align: right; overflow-wrap: anywhere; }
|
||||
.geo-loading { position: absolute; inset: 0; display: grid; place-items: center; color: var(--ink-muted); }
|
||||
.geo-legend { display: grid; grid-template-columns: auto minmax(60px, 160px) auto 1fr; gap: 8px; align-items: center; font-size: 12px; color: var(--ink-muted); padding: 0 4px; }
|
||||
.geo-legend-bar { height: 8px; border-radius: 4px; background: linear-gradient(90deg, color-mix(in srgb, var(--accent) 20%, transparent), var(--accent)); border: 1px solid var(--line); }
|
||||
.geo-legend-t { margin-left: 6px; }
|
||||
|
||||
.geo-side { display: flex; flex-direction: column; min-height: 0; }
|
||||
.geo-list { display: flex; flex-direction: column; gap: 4px; overflow-y: auto; flex: 1 1 0; min-height: 120px; padding-right: 2px; }
|
||||
.geo-row { display: block; width: 100%; text-align: left; background: none; border: 1px solid transparent; border-radius: 10px; padding: 6px 8px; color: var(--ink); font: inherit; }
|
||||
button.geo-row { cursor: pointer; }
|
||||
button.geo-row:hover { background: var(--surface-raised); border-color: var(--line); }
|
||||
.geo-row.on { background: color-mix(in srgb, var(--accent) 14%, transparent); border-color: var(--accent); }
|
||||
.geo-row-top { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
|
||||
.geo-rank { color: var(--ink-muted); font-size: 11px; min-width: 1.8em; font-variant-numeric: tabular-nums; }
|
||||
.geo-name { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.geo-sub { flex: 1 1 0; min-width: 0; color: var(--ink-muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.geo-name + .geo-num { margin-left: auto; }
|
||||
.geo-num { font-variant-numeric: tabular-nums; font-weight: 600; flex: none; margin-left: auto; }
|
||||
.geo-bar { display: block; height: 4px; border-radius: 2px; background: var(--surface-raised); margin-top: 5px; overflow: hidden; }
|
||||
.geo-bar i { display: block; height: 100%; background: var(--accent); border-radius: 2px; }
|
||||
.geo-chip { align-self: flex-start; margin-bottom: 6px; }
|
||||
.geo-empty { color: var(--ink-muted); padding: 16px 4px; text-align: center; }
|
||||
.geo-note { color: var(--ink-muted); font-size: 12px; margin-top: 8px; }
|
||||
|
||||
.geo-detail { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; align-items: start; }
|
||||
.geo-stack { display: flex; height: 14px; border-radius: 7px; overflow: hidden; gap: 2px; margin-bottom: 12px; }
|
||||
.geo-stack span { min-width: 3px; }
|
||||
.geo-chips { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
|
||||
.geo-chipcat { display: flex; align-items: center; gap: 8px; font-size: 13px; }
|
||||
.geo-chipcat b { margin-left: auto; font-variant-numeric: tabular-nums; font-weight: 600; }
|
||||
.geo-chipcat i { width: 10px; height: 10px; border-radius: 3px; flex: none; }
|
||||
.geo-c-notfound { background: var(--cat-notfound); } .geo-c-scanner { background: var(--cat-scanner); }
|
||||
.geo-c-bruteforce { background: var(--cat-bruteforce); } .geo-c-exploit { background: var(--cat-exploit); }
|
||||
.geo-c-ssh-fail { background: var(--cat-ssh-fail); } .geo-c-ssh-probe { background: var(--cat-ssh-probe); }
|
||||
.geo-c-ban { background: var(--cat-ban); } .geo-c-other { background: var(--ink-faint); }
|
||||
|
||||
.geo-ip { display: block; width: 100%; text-align: left; background: none; border: 1px solid transparent; border-radius: 10px; padding: 7px 8px; color: var(--ink); font: inherit; cursor: pointer; }
|
||||
.geo-ip:hover { background: var(--surface-raised); border-color: var(--line); }
|
||||
.geo-ip-l1 { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.geo-ip-l1 code { font-size: 13px; font-weight: 600; }
|
||||
.geo-ip-l2, .geo-ip-l3 { display: block; color: var(--ink-muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.geo-lv { font-size: 11px; padding: 1px 7px; border-radius: 999px; border: 1px solid currentColor; }
|
||||
.geo-lv-hostile { color: var(--danger); } .geo-lv-suspicious { color: var(--warn); }
|
||||
.geo-lv-clean, .geo-lv-low { color: var(--ok); } .geo-lv-unknown { color: var(--ink-faint); }
|
||||
.geo-score { color: var(--ink-muted); font-size: 12px; margin-left: auto; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.geo-main { grid-template-columns: minmax(0, 1fr); }
|
||||
.geo-list { max-height: 360px; flex: none; }
|
||||
.geo-detail { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.geo-map { aspect-ratio: 4 / 3; min-height: 0; }
|
||||
/* o texto de abertura usa o .lead do shell */
|
||||
.geo-leadbox { min-height: 70px; }
|
||||
.geo-lead { max-width: none !important; }
|
||||
.geo-legend { grid-template-columns: auto minmax(40px, 1fr) auto; }
|
||||
.geo-legend-t { grid-column: 1 / -1; margin-left: 0; }
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
/* Urutau - página Geografia: mapa coroplético, zoom em país, estados e cidades.
|
||||
Todos os dados externos (cidade, região, AS) entram só via textContent. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var U = window.Urutau;
|
||||
if (!U || typeof U.registerPage !== 'function') return;
|
||||
|
||||
// ---------------------------------------------------------------- i18n
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'geo.title': 'Geography',
|
||||
'geo.world': 'World',
|
||||
'geo.nav': 'Location path',
|
||||
'geo.back': 'Back',
|
||||
'geo.back.hint': 'Back (Esc)',
|
||||
'geo.map.label': 'Map of attack origins. Use the list to choose a country.',
|
||||
'geo.map.country.label': 'Map of {country} with the cities that attack the most',
|
||||
'geo.lead.world': '{events} from {ips} across {countries}, in the last {range}; {top} leads with {pct}.',
|
||||
'geo.lead.country': '{country} originated {events} from {ips} in the last {range}; {region} leads with {pct}.',
|
||||
'geo.lead.country.flat': '{country} originated {events} from {ips} in the last {range}.',
|
||||
'geo.lead.region': '{region} ({country}) originated {events} from {ips} in the last {range}; {city} leads with {pct}.',
|
||||
'geo.lead.region.flat': '{region} ({country}) originated {events} from {ips} in the last {range}.',
|
||||
'geo.lead.empty': 'No geolocated attacks in the last {range}.',
|
||||
'geo.lead.empty.country': 'No attacks from {country} in the last {range}.',
|
||||
'geo.u.events.one': '{n} event', 'geo.u.events.other': '{n} events',
|
||||
'geo.u.ips.one': '{n} IP', 'geo.u.ips.other': '{n} IPs',
|
||||
'geo.u.countries.one': '{n} country', 'geo.u.countries.other': '{n} countries',
|
||||
'geo.range.1h': 'hour', 'geo.range.24h': '24 hours', 'geo.range.7d': '7 days',
|
||||
'geo.legend': 'Events per country (log scale)',
|
||||
'geo.tip.events': 'Events', 'geo.tip.ips': 'IPs', 'geo.tip.hostile': 'Hostile',
|
||||
'geo.tip.region': 'Region',
|
||||
'geo.countries': 'Countries',
|
||||
'geo.regions': 'States / regions',
|
||||
'geo.cities': 'Cities',
|
||||
'geo.cats': 'Attack categories',
|
||||
'geo.ips': 'Top IPs',
|
||||
'geo.unknown': 'Unknown',
|
||||
'geo.all_regions': 'All regions',
|
||||
'geo.pick': 'Open {name}: {events}',
|
||||
'geo.pick.region': 'Filter by {name}: {events}',
|
||||
'geo.city.pick': 'Filter by region {name}',
|
||||
'geo.nocoords.one': '{n} city has no coordinates and is not on the map.', 'geo.nocoords.other': '{n} cities have no coordinates and are not on the map.',
|
||||
'geo.empty': 'Nothing to show for this range.',
|
||||
'geo.empty.list': 'No data.',
|
||||
'geo.loading': 'Loading…',
|
||||
'geo.error': 'Could not load geography data.',
|
||||
'geo.retry': 'Try again',
|
||||
'geo.level.hostile': 'hostile', 'geo.level.suspicious': 'suspicious', 'geo.level.clean': 'clean', 'geo.level.low': 'low', 'geo.level.unknown': 'unknown',
|
||||
'geo.score': 'score {n}',
|
||||
'geo.open_ip': 'Open details of {ip}',
|
||||
'geo.hostile_suspicious': '{h} hostile, {s} suspicious',
|
||||
'geo.cat.notfound': 'not found', 'geo.cat.scanner': 'scanner', 'geo.cat.bruteforce': 'brute force',
|
||||
'geo.cat.exploit': 'exploit', 'geo.cat.ssh-fail': 'SSH failures', 'geo.cat.ssh-probe': 'SSH probe', 'geo.cat.ban': 'ban'
|
||||
},
|
||||
'pt-BR': {
|
||||
'geo.title': 'Geografia',
|
||||
'geo.world': 'Mundo',
|
||||
'geo.nav': 'Caminho da localização',
|
||||
'geo.back': 'Voltar',
|
||||
'geo.back.hint': 'Voltar (Esc)',
|
||||
'geo.map.label': 'Mapa das origens dos ataques. Use a lista para escolher um país.',
|
||||
'geo.map.country.label': 'Mapa de {country} com as cidades que mais atacam',
|
||||
'geo.lead.world': '{events} de {ips} em {countries}, nas últimas {range}; {top} lidera com {pct}.',
|
||||
'geo.lead.country': '{country} originou {events} de {ips} nas últimas {range}; {region} lidera com {pct}.',
|
||||
'geo.lead.country.flat': '{country} originou {events} de {ips} nas últimas {range}.',
|
||||
'geo.lead.region': '{region} ({country}) originou {events} de {ips} nas últimas {range}; {city} lidera com {pct}.',
|
||||
'geo.lead.region.flat': '{region} ({country}) originou {events} de {ips} nas últimas {range}.',
|
||||
'geo.lead.empty': 'Nenhum ataque geolocalizado nas últimas {range}.',
|
||||
'geo.lead.empty.country': 'Nenhum ataque de {country} nas últimas {range}.',
|
||||
'geo.u.events.one': '{n} evento', 'geo.u.events.other': '{n} eventos',
|
||||
'geo.u.ips.one': '{n} IP', 'geo.u.ips.other': '{n} IPs',
|
||||
'geo.u.countries.one': '{n} país', 'geo.u.countries.other': '{n} países',
|
||||
'geo.range.1h': 'hora', 'geo.range.24h': '24 horas', 'geo.range.7d': '7 dias',
|
||||
'geo.legend': 'Eventos por país (escala log)',
|
||||
'geo.tip.events': 'Eventos', 'geo.tip.ips': 'IPs', 'geo.tip.hostile': 'Hostis',
|
||||
'geo.tip.region': 'Região',
|
||||
'geo.countries': 'Países',
|
||||
'geo.regions': 'Estados / regiões',
|
||||
'geo.cities': 'Cidades',
|
||||
'geo.cats': 'Categorias de ataque',
|
||||
'geo.ips': 'IPs que mais atacam',
|
||||
'geo.unknown': 'Desconhecido',
|
||||
'geo.all_regions': 'Todas as regiões',
|
||||
'geo.pick': 'Abrir {name}: {events}',
|
||||
'geo.pick.region': 'Filtrar por {name}: {events}',
|
||||
'geo.city.pick': 'Filtrar pela região {name}',
|
||||
'geo.nocoords.one': '{n} cidade sem coordenadas não aparece no mapa.', 'geo.nocoords.other': '{n} cidades sem coordenadas não aparecem no mapa.',
|
||||
'geo.empty': 'Nada para mostrar neste período.',
|
||||
'geo.empty.list': 'Sem dados.',
|
||||
'geo.loading': 'Carregando…',
|
||||
'geo.error': 'Não foi possível carregar os dados de geografia.',
|
||||
'geo.retry': 'Tentar de novo',
|
||||
'geo.level.hostile': 'hostil', 'geo.level.suspicious': 'suspeito', 'geo.level.clean': 'limpo', 'geo.level.low': 'baixo', 'geo.level.unknown': 'desconhecido',
|
||||
'geo.score': 'pontuação {n}',
|
||||
'geo.open_ip': 'Abrir detalhes de {ip}',
|
||||
'geo.hostile_suspicious': '{h} hostis, {s} suspeitos',
|
||||
'geo.cat.notfound': 'não encontrado', 'geo.cat.scanner': 'scanner', 'geo.cat.bruteforce': 'força bruta',
|
||||
'geo.cat.exploit': 'exploit', 'geo.cat.ssh-fail': 'falhas SSH', 'geo.cat.ssh-probe': 'sondagem SSH', 'geo.cat.ban': 'banimento'
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
var NS = 'http://www.w3.org/2000/svg';
|
||||
var CAT_CLASS = { notfound: 1, scanner: 1, bruteforce: 1, exploit: 1, 'ssh-fail': 1, 'ssh-probe': 1, ban: 1 };
|
||||
var LEVELS = { hostile: 1, suspicious: 1, clean: 1, low: 1, unknown: 1 };
|
||||
var RANGES = { '1h': 1, '24h': 1, '7d': 1 };
|
||||
var LAT_TOP = 84, LAT_SPAN = 142;
|
||||
|
||||
function t(k, v) { return U.t(k, v); }
|
||||
function h(tag, cls, text) {
|
||||
var e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text != null) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
function sv(tag, attrs) {
|
||||
var e = document.createElementNS(NS, tag);
|
||||
if (attrs) for (var k in attrs) e.setAttribute(k, attrs[k]);
|
||||
return e;
|
||||
}
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
function nf(n) {
|
||||
try { if (U.fmt && U.fmt.num) return U.fmt.num(n); } catch (e) { /* fallback */ }
|
||||
return new Intl.NumberFormat(lang).format(n);
|
||||
}
|
||||
function pct(x) { return Math.round(x * 100) + '%'; }
|
||||
function unit(kind, n) { return t('geo.u.' + kind + (n === 1 ? '.one' : '.other'), { n: nf(n) }); }
|
||||
function flagOf(cc) { try { return (U.fmt && U.fmt.flag && U.fmt.flag(cc)) || ''; } catch (e) { return ''; } }
|
||||
var dn = null, dnLang = '';
|
||||
function countryName(cc) {
|
||||
try {
|
||||
if (!dn || dnLang !== lang) { dn = new Intl.DisplayNames([lang], { type: 'region' }); dnLang = lang; }
|
||||
return dn.of(cc) || cc;
|
||||
} catch (e) { return cc; }
|
||||
}
|
||||
function regionName(r) { return r ? r : t('geo.unknown'); }
|
||||
function catLabel(c) { var k = 'geo.cat.' + c, v = t(k); return v && v !== k ? v : c; }
|
||||
function catCls(c) { return CAT_CLASS[c] ? 'geo-c-' + c : 'geo-c-other'; }
|
||||
function rangeLabel(r) { return t('geo.range.' + (RANGES[r] ? r : '24h')); }
|
||||
function sum(o) { var s = 0; for (var k in o) s += o[k]; return s; }
|
||||
|
||||
// ---------------------------------------------------------------- geometry
|
||||
var world = null, bboxCache = {};
|
||||
function projX(lon) { return (lon + 180) / 360 * world.w; }
|
||||
function projY(lat) { return (LAT_TOP - lat) / LAT_SPAN * world.h; }
|
||||
|
||||
// Bbox of a country's path: main land masses only (drops far-away small islands).
|
||||
function bboxOf(cc) {
|
||||
if (bboxCache[cc]) return bboxCache[cc];
|
||||
var d = world.paths[cc];
|
||||
if (!d) return null;
|
||||
var re = /([MmLlzZ])|(-?\d+(?:\.\d+)?)/g, m, cmd = '', nums = [], subs = [], cur = null, cx = 0, cy = 0, sx = 0, sy = 0;
|
||||
function flush() {
|
||||
for (var i = 0; i + 1 < nums.length; i += 2) {
|
||||
if (cmd === 'M' && i === 0) { cx = nums[i]; cy = nums[i + 1]; sx = cx; sy = cy; cur = [cx, cy, cx, cy]; subs.push(cur); }
|
||||
else { if (cmd === 'l' || cmd === 'm') { cx += nums[i]; cy += nums[i + 1]; } else { cx = nums[i]; cy = nums[i + 1]; }
|
||||
if (cur) { if (cx < cur[0]) cur[0] = cx; if (cy < cur[1]) cur[1] = cy; if (cx > cur[2]) cur[2] = cx; if (cy > cur[3]) cur[3] = cy; } }
|
||||
}
|
||||
nums = [];
|
||||
}
|
||||
while ((m = re.exec(d))) {
|
||||
if (m[1]) { flush(); cmd = m[1]; if (cmd === 'z' || cmd === 'Z') { cx = sx; cy = sy; } }
|
||||
else nums.push(parseFloat(m[2]));
|
||||
}
|
||||
flush();
|
||||
var maxA = 0;
|
||||
subs.forEach(function (b) { var a = (b[2] - b[0]) * (b[3] - b[1]); if (a > maxA) maxA = a; });
|
||||
var out = null;
|
||||
subs.forEach(function (b) {
|
||||
var a = (b[2] - b[0]) * (b[3] - b[1]);
|
||||
if (a < maxA * 0.12 && subs.length > 1) return;
|
||||
if (!out) out = b.slice();
|
||||
else { out[0] = Math.min(out[0], b[0]); out[1] = Math.min(out[1], b[1]); out[2] = Math.max(out[2], b[2]); out[3] = Math.max(out[3], b[3]); }
|
||||
});
|
||||
bboxCache[cc] = out;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
var lang = 'en', ctx = null, root = null, ui = null, alive = false;
|
||||
var S = { cc: '', region: '' };
|
||||
var data = { world: null, country: null, full: null, error: false, loading: false };
|
||||
var seq = 0, cache = {}, view = null, anim = 0, cityEls = [], ro = null;
|
||||
|
||||
function parseHash() {
|
||||
var m = /^#\/geo(?:\/([A-Za-z]{2})(?:\/(.*))?)?$/.exec(location.hash || '');
|
||||
var cc = '', region = '';
|
||||
if (m && m[1]) {
|
||||
cc = m[1].toUpperCase();
|
||||
if (m[2]) { try { region = decodeURIComponent(m[2]); } catch (e) { region = ''; } }
|
||||
}
|
||||
return { cc: cc, region: region };
|
||||
}
|
||||
function writeHash() {
|
||||
var hsh = '#/geo' + (S.cc ? '/' + S.cc + (S.region ? '/' + encodeURIComponent(S.region) : '') : '');
|
||||
if (location.hash !== hsh) { try { history.pushState(null, '', hsh); } catch (e) { location.hash = hsh; } }
|
||||
}
|
||||
function go(cc, region, focus) {
|
||||
if (world && cc && !world.paths[cc]) cc = '';
|
||||
S.cc = cc || '';
|
||||
S.region = cc ? (region || '') : '';
|
||||
writeHash();
|
||||
load(true);
|
||||
if (focus && ui) setTimeout(function () { try { ui.lead.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, 0);
|
||||
}
|
||||
function goBack() {
|
||||
if (S.region) go(S.cc, '', true);
|
||||
else if (S.cc) go('', '', true);
|
||||
}
|
||||
function onHash() {
|
||||
if (!alive) return;
|
||||
var p = parseHash();
|
||||
if (p.cc === S.cc && p.region === S.region) return;
|
||||
S.cc = p.cc; S.region = p.region;
|
||||
load(true);
|
||||
}
|
||||
function onKey(e) {
|
||||
if (!alive || e.key !== 'Escape' || e.defaultPrevented) return;
|
||||
var tg = e.target && e.target.tagName;
|
||||
if (tg === 'INPUT' || tg === 'SELECT' || tg === 'TEXTAREA') return;
|
||||
if (S.cc) { e.preventDefault(); goBack(); }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- data
|
||||
function key(extra) { return [ctx.range, ctx.host || '', extra || ''].join('|'); }
|
||||
function fetchJSON(params) {
|
||||
var p = { range: ctx.range };
|
||||
if (ctx.host) p.host = ctx.host;
|
||||
for (var k in params) p[k] = params[k];
|
||||
return Promise.resolve(U.api('/api/v1/geo', p));
|
||||
}
|
||||
function cached(k, params) {
|
||||
if (cache[k]) return Promise.resolve(cache[k]);
|
||||
return fetchJSON(params).then(function (d) { cache[k] = d; return d; });
|
||||
}
|
||||
function load(refit) {
|
||||
var my = ++seq;
|
||||
data.loading = true; data.error = false;
|
||||
paintState();
|
||||
var cc = S.cc, region = S.region;
|
||||
var jobs = [cached(key('w'), {})];
|
||||
if (cc) {
|
||||
jobs.push(cached(key('c:' + cc), { cc: cc }));
|
||||
jobs.push(region ? cached(key('r:' + cc + ':' + region), { cc: cc, region: region }) : null);
|
||||
}
|
||||
Promise.all(jobs).then(function (r) {
|
||||
if (my !== seq || !alive) return;
|
||||
data.world = r[0];
|
||||
data.full = cc ? r[1] : null;
|
||||
data.country = cc ? (region ? r[2] : r[1]) : null;
|
||||
data.loading = false;
|
||||
render(refit);
|
||||
}).catch(function () {
|
||||
if (my !== seq || !alive) return;
|
||||
data.loading = false; data.error = true;
|
||||
render(false);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- build
|
||||
function build(el) {
|
||||
clear(el);
|
||||
root = h('div', 'geo');
|
||||
var top = h('div', 'geo-top');
|
||||
var nav = h('nav', 'geo-crumbs'); nav.setAttribute('aria-label', t('geo.nav'));
|
||||
var back = h('button', 'geo-back', '‹ ' + t('geo.back')); back.type = 'button';
|
||||
back.title = t('geo.back.hint'); back.addEventListener('click', goBack);
|
||||
top.appendChild(nav); top.appendChild(back);
|
||||
var lead = h('h2', 'geo-lead'); lead.tabIndex = -1; lead.setAttribute('aria-live', 'polite');
|
||||
var leadBox = h('div', 'lead geo-leadbox'); leadBox.appendChild(lead);
|
||||
var err = h('div', 'geo-err'); err.setAttribute('role', 'alert'); err.hidden = true;
|
||||
var errMsg = h('span', '', t('geo.error')), retry = h('button', 'geo-retry', t('geo.retry')); retry.type = 'button';
|
||||
retry.addEventListener('click', function () { cache = {}; load(false); });
|
||||
err.appendChild(errMsg); err.appendChild(retry);
|
||||
|
||||
var main = h('div', 'geo-main');
|
||||
var mapPanel = h('section', 'geo-panel geo-mappanel');
|
||||
var box = h('div', 'geo-map');
|
||||
var svg = sv('svg', { 'class': 'geo-svg', role: 'img', preserveAspectRatio: 'xMidYMid meet' });
|
||||
var gC = sv('g', { 'class': 'geo-countries' }), gCity = sv('g', { 'class': 'geo-cities' });
|
||||
svg.appendChild(gC); svg.appendChild(gCity);
|
||||
var paths = {};
|
||||
Object.keys(world.paths).forEach(function (cc) {
|
||||
var p = sv('path', { d: world.paths[cc], 'class': 'geo-cn', 'data-cc': cc });
|
||||
paths[cc] = p; gC.appendChild(p);
|
||||
});
|
||||
var tip = h('div', 'geo-tip'); tip.hidden = true; tip.setAttribute('role', 'presentation');
|
||||
var ld = h('div', 'geo-loading', t('geo.loading')); ld.hidden = true;
|
||||
box.appendChild(svg); box.appendChild(tip); box.appendChild(ld);
|
||||
var legend = h('div', 'geo-legend');
|
||||
var lg = h('div', 'geo-legend-bar'); lg.setAttribute('aria-hidden', 'true');
|
||||
var lmin = h('span', '', '1'), lmax = h('span', '', ''), ltx = h('span', 'geo-legend-t', t('geo.legend'));
|
||||
legend.appendChild(lmin); legend.appendChild(lg); legend.appendChild(lmax); legend.appendChild(ltx);
|
||||
mapPanel.appendChild(box); mapPanel.appendChild(legend);
|
||||
|
||||
var side = h('section', 'geo-panel geo-side');
|
||||
var sideH = h('h2', '', ''); sideH.tabIndex = -1;
|
||||
var sideList = h('div', 'geo-list');
|
||||
side.appendChild(sideH); side.appendChild(sideList);
|
||||
main.appendChild(mapPanel); main.appendChild(side);
|
||||
|
||||
var detail = h('div', 'geo-detail');
|
||||
function panel(title) {
|
||||
var p = h('section', 'geo-panel'), hd = h('h2', '', title), body = h('div', 'geo-body');
|
||||
p.appendChild(hd); p.appendChild(body); detail.appendChild(p);
|
||||
return { p: p, h: hd, body: body };
|
||||
}
|
||||
var pCities = panel(''), pCats = panel(''), pIps = panel('');
|
||||
|
||||
root.appendChild(top); root.appendChild(leadBox); root.appendChild(err); root.appendChild(main); root.appendChild(detail);
|
||||
el.appendChild(root);
|
||||
ui = { nav: nav, back: back, lead: lead, err: err, errMsg: errMsg, retry: retry, svg: svg, gCity: gCity, paths: paths, box: box,
|
||||
tip: tip, loading: ld, legendMax: lmax, legend: legend, legendBar: lg, side: side, sideH: sideH, sideList: sideList, detail: detail,
|
||||
pCities: pCities, pCats: pCats, pIps: pIps };
|
||||
|
||||
gC.addEventListener('click', function (e) {
|
||||
var cc = e.target && e.target.getAttribute && e.target.getAttribute('data-cc');
|
||||
if (cc && hit(cc)) go(cc, '', true);
|
||||
});
|
||||
gC.addEventListener('mousemove', function (e) {
|
||||
var cc = e.target && e.target.getAttribute && e.target.getAttribute('data-cc');
|
||||
var r = cc && hit(cc);
|
||||
if (!r) { ui.tip.hidden = true; return; }
|
||||
showTip(e, [[flagOf(cc) + ' ' + countryName(cc), ''], [t('geo.tip.events'), nf(r.events)], [t('geo.tip.ips'), nf(r.ips)], [t('geo.tip.hostile'), nf(r.hostile || 0)]]);
|
||||
});
|
||||
gC.addEventListener('mouseleave', function () { ui.tip.hidden = true; });
|
||||
gCity.addEventListener('mouseleave', function () { ui.tip.hidden = true; });
|
||||
if (window.ResizeObserver) {
|
||||
ro = new ResizeObserver(function () { if (alive && data.world && !data.error && !anim) { fitNow(); drawCities(); } });
|
||||
ro.observe(box);
|
||||
}
|
||||
}
|
||||
|
||||
function hit(cc) {
|
||||
var cs = data.world && data.world.countries;
|
||||
if (!cs) return null;
|
||||
for (var i = 0; i < cs.length; i++) if (cs[i].cc === cc) return cs[i];
|
||||
return null;
|
||||
}
|
||||
function showTip(e, rows) {
|
||||
var tip = ui.tip;
|
||||
clear(tip);
|
||||
rows.forEach(function (r, i) {
|
||||
var d = h('div', i === 0 ? 'geo-tip-h' : 'geo-tip-r');
|
||||
d.appendChild(h('span', '', r[0]));
|
||||
if (r[1] !== '') d.appendChild(h('b', '', r[1]));
|
||||
tip.appendChild(d);
|
||||
});
|
||||
tip.hidden = false;
|
||||
var b = ui.box.getBoundingClientRect();
|
||||
var x = e.clientX - b.left + 14, y = e.clientY - b.top + 14;
|
||||
var w = tip.offsetWidth, hh = tip.offsetHeight;
|
||||
if (x + w > b.width - 4) x = Math.max(4, e.clientX - b.left - w - 14);
|
||||
if (y + hh > b.height - 4) y = Math.max(4, e.clientY - b.top - hh - 14);
|
||||
tip.style.left = x + 'px'; tip.style.top = y + 'px';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- map view
|
||||
function boxSize() {
|
||||
var r = ui.box.getBoundingClientRect();
|
||||
return { w: r.width || 800, h: r.height || 360 };
|
||||
}
|
||||
function targetView() {
|
||||
var sz = boxSize(), asp = sz.w / sz.h, bb, margin = 1.22;
|
||||
if (!S.cc) { bb = [0, 0, world.w, world.h]; margin = 1; }
|
||||
else {
|
||||
bb = bboxOf(S.cc) || [0, 0, world.w, world.h];
|
||||
var cs = data.country && data.country.cities;
|
||||
if (S.region && cs) {
|
||||
var pts = cs.filter(function (c) { return isNum(c.lat) && isNum(c.lon); });
|
||||
if (pts.length) {
|
||||
var x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
|
||||
pts.forEach(function (c) { var x = projX(c.lon), y = projY(c.lat); x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); });
|
||||
bb = [x0, y0, x1, y1]; margin = 1.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
var bw = Math.max(bb[2] - bb[0], 36), bh = Math.max(bb[3] - bb[1], 36 / asp);
|
||||
var vw = Math.max(bw * margin, bh * margin * asp);
|
||||
var vh = vw / asp;
|
||||
var cx = (bb[0] + bb[2]) / 2, cy = (bb[1] + bb[3]) / 2;
|
||||
return [cx - vw / 2, cy - vh / 2, vw, vh];
|
||||
}
|
||||
function setView(v) { if (!(v[2] > 0 && v[3] > 0)) return; view = v; ui.svg.setAttribute('viewBox', v.map(function (n) { return n.toFixed(2); }).join(' ')); }
|
||||
function fitNow() { setView(targetView()); }
|
||||
function reduced() { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) { return false; } }
|
||||
function animateTo(to, done) {
|
||||
cancelAnimationFrame(anim); anim = 0;
|
||||
if (!view || reduced()) { setView(to); done(); return; }
|
||||
var from = view.slice(), t0 = performance.now(), dur = 420;
|
||||
(function step(now) {
|
||||
var k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3);
|
||||
setView(from.map(function (f, i) { return f + (to[i] - f) * e; }));
|
||||
if (k < 1) anim = requestAnimationFrame(step); else { anim = 0; done(); }
|
||||
})(t0);
|
||||
}
|
||||
// O contrato repete a chave "ips" (contagem e lista); aceita os dois formatos.
|
||||
function ipList(d) { return Array.isArray(d.top_ips) ? d.top_ips : (Array.isArray(d.ips) ? d.ips : []); }
|
||||
function ipCount(d) {
|
||||
if (isNum(d.ips)) return d.ips;
|
||||
var k = ['ip_count', 'ips_total', 'unique_ips', 'ips_count'];
|
||||
for (var i = 0; i < k.length; i++) if (isNum(d[k[i]])) return d[k[i]];
|
||||
if (S.region && data.full) { var rs = data.full.regions || []; for (var j = 0; j < rs.length; j++) if (rs[j].name === S.region) return rs[j].ips; }
|
||||
var w = hit(S.cc); if (w && !S.region) return w.ips;
|
||||
return (d.cities || []).reduce(function (a, c) { return a + (c.ips || 0); }, 0);
|
||||
}
|
||||
function isNum(n) { return typeof n === 'number' && isFinite(n); }
|
||||
|
||||
function drawCities() {
|
||||
clear(ui.gCity); cityEls = [];
|
||||
var d = data.country;
|
||||
if (!S.cc || !d || !d.cities || !view) return;
|
||||
var sz = boxSize(), upp = view[2] / sz.w, max = 1;
|
||||
d.cities.forEach(function (c) { if (c.events > max) max = c.events; });
|
||||
var rmax = sz.w < 560 ? 16 : 26;
|
||||
d.cities.forEach(function (c, i) {
|
||||
if (!isNum(c.lat) || !isNum(c.lon)) return;
|
||||
var x = projX(c.lon), y = projY(c.lat);
|
||||
if (x < view[0] - 20 || x > view[0] + view[2] + 20 || y < view[1] - 20 || y > view[1] + view[3] + 20) return;
|
||||
var r = Math.max(3, rmax * Math.sqrt(c.events / max)) * upp;
|
||||
var el = sv('circle', { cx: x.toFixed(2), cy: y.toFixed(2), r: r.toFixed(2), 'class': 'geo-city' });
|
||||
el.addEventListener('mousemove', function (e) {
|
||||
var rows = [[c.name || t('geo.unknown'), '']];
|
||||
if (c.region) rows.push([t('geo.tip.region'), c.region]);
|
||||
rows.push([t('geo.tip.events'), nf(c.events)], [t('geo.tip.ips'), nf(c.ips)]);
|
||||
showTip(e, rows);
|
||||
});
|
||||
el.addEventListener('mouseleave', function () { ui.tip.hidden = true; });
|
||||
if (c.region && !S.region) {
|
||||
el.addEventListener('click', function () { go(S.cc, c.region, true); });
|
||||
el.classList.add('geo-city-click');
|
||||
}
|
||||
cityEls[i] = el; ui.gCity.appendChild(el);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- render
|
||||
function paintState() {
|
||||
if (!ui) return;
|
||||
ui.loading.hidden = !data.loading || !!data.world;
|
||||
root.classList.toggle('is-busy', data.loading);
|
||||
}
|
||||
|
||||
function crumbs() {
|
||||
var nav = ui.nav; clear(nav);
|
||||
function sep() { var s = h('span', 'geo-sep', '›'); s.setAttribute('aria-hidden', 'true'); nav.appendChild(s); }
|
||||
var parts = [{ txt: t('geo.world'), act: S.cc ? function () { go('', '', true); } : null }];
|
||||
if (S.cc) parts.push({ txt: flagOf(S.cc) + ' ' + countryName(S.cc), act: S.region ? function () { go(S.cc, '', true); } : null });
|
||||
if (S.region) parts.push({ txt: regionName(S.region), act: null });
|
||||
parts.forEach(function (p, i) {
|
||||
if (i) sep();
|
||||
var n;
|
||||
if (p.act) { n = h('button', 'geo-crumb', p.txt); n.type = 'button'; n.addEventListener('click', p.act); }
|
||||
else { n = h('span', 'geo-crumb cur', p.txt); n.setAttribute('aria-current', 'page'); }
|
||||
nav.appendChild(n);
|
||||
});
|
||||
ui.back.hidden = !S.cc;
|
||||
}
|
||||
|
||||
function lead() {
|
||||
var rl = rangeLabel(ctx.range), L = ui.lead;
|
||||
if (data.error || !data.world) { L.textContent = ''; return; }
|
||||
var cs = data.world.countries || [];
|
||||
if (!S.cc) {
|
||||
var tot = 0, ips = 0;
|
||||
cs.forEach(function (c) { tot += c.events; ips += c.ips; });
|
||||
if (!cs.length) { L.textContent = t('geo.lead.empty', { range: rl }); return; }
|
||||
var top = cs.slice().sort(function (a, b) { return b.events - a.events; })[0];
|
||||
L.textContent = t('geo.lead.world', { events: unit('events', tot), ips: unit('ips', ips), countries: unit('countries', cs.length),
|
||||
range: rl, top: countryName(top.cc), pct: pct(top.events / tot) });
|
||||
return;
|
||||
}
|
||||
var d = data.country, cn = countryName(S.cc);
|
||||
if (!d || !d.events) { L.textContent = t('geo.lead.empty.country', { country: cn, range: rl }); return; }
|
||||
var base = { country: cn, events: unit('events', d.events), ips: unit('ips', ipCount(d)), range: rl };
|
||||
if (S.region) {
|
||||
var c0 = (d.cities || [])[0];
|
||||
base.region = regionName(S.region);
|
||||
if (c0 && c0.name) { base.city = c0.name; base.pct = pct(c0.events / d.events); L.textContent = t('geo.lead.region', base); }
|
||||
else L.textContent = t('geo.lead.region.flat', base);
|
||||
return;
|
||||
}
|
||||
var r0 = ((d.regions || []).filter(function (r) { return r.name; })[0]);
|
||||
if (r0 && d.regions.length > 1) { base.region = r0.name; base.pct = pct(r0.events / d.events); L.textContent = t('geo.lead.country', base); }
|
||||
else L.textContent = t('geo.lead.country.flat', base);
|
||||
}
|
||||
|
||||
function colorize() {
|
||||
var cs = (data.world && data.world.countries) || [], max = 1, by = {};
|
||||
cs.forEach(function (c) { by[c.cc] = c; if (c.events > max) max = c.events; });
|
||||
var lm = Math.log(1 + max);
|
||||
ui.legendMax.textContent = nf(max);
|
||||
var zoomed = !!S.cc;
|
||||
ui.svg.setAttribute('class', 'geo-svg' + (zoomed ? ' zoomed' : ''));
|
||||
Object.keys(ui.paths).forEach(function (cc) {
|
||||
var p = ui.paths[cc], c = by[cc], cls = 'geo-cn';
|
||||
if (c) {
|
||||
cls += ' hit';
|
||||
p.style.fillOpacity = (0.2 + 0.8 * Math.log(1 + c.events) / lm).toFixed(3);
|
||||
} else p.style.fillOpacity = '';
|
||||
if (cc === S.cc) cls += ' sel';
|
||||
p.setAttribute('class', cls);
|
||||
});
|
||||
ui.legend.hidden = zoomed;
|
||||
if (S.cc) ui.svg.setAttribute('aria-label', t('geo.map.country.label', { country: countryName(S.cc) }));
|
||||
else ui.svg.setAttribute('aria-label', t('geo.map.label'));
|
||||
}
|
||||
|
||||
function emptyNote(txt) { return h('div', 'geo-empty', txt); }
|
||||
|
||||
function row(opts) {
|
||||
// opts: name, sub, n, frac, onClick, label, pressed, rank, cls
|
||||
var r = h(opts.onClick ? 'button' : 'div', 'geo-row' + (opts.cls ? ' ' + opts.cls : ''));
|
||||
if (opts.onClick) {
|
||||
r.type = 'button'; r.addEventListener('click', opts.onClick);
|
||||
if (opts.label) r.setAttribute('aria-label', opts.label);
|
||||
if (opts.pressed != null) r.setAttribute('aria-pressed', opts.pressed ? 'true' : 'false');
|
||||
}
|
||||
var top = h('span', 'geo-row-top');
|
||||
if (opts.rank) top.appendChild(h('span', 'geo-rank', String(opts.rank)));
|
||||
var nm = h('span', 'geo-name', opts.name); top.appendChild(nm);
|
||||
if (opts.sub) top.appendChild(h('span', 'geo-sub', opts.sub));
|
||||
top.appendChild(h('span', 'geo-num', nf(opts.n)));
|
||||
r.appendChild(top);
|
||||
var bar = h('span', 'geo-bar'), i = h('i'); i.style.width = Math.max(2, opts.frac * 100) + '%';
|
||||
bar.appendChild(i); r.appendChild(bar);
|
||||
return r;
|
||||
}
|
||||
|
||||
function renderSide() {
|
||||
var L = ui.sideList; clear(L);
|
||||
if (!S.cc) {
|
||||
ui.sideH.textContent = t('geo.countries');
|
||||
var cs = ((data.world && data.world.countries) || []).slice().sort(function (a, b) { return b.events - a.events; });
|
||||
if (!cs.length) { L.appendChild(emptyNote(t('geo.empty'))); return; }
|
||||
var max = cs[0].events || 1;
|
||||
cs.forEach(function (c, i) {
|
||||
var nm = countryName(c.cc);
|
||||
L.appendChild(row({ rank: i + 1, name: flagOf(c.cc) + ' ' + nm, n: c.events, frac: c.events / max,
|
||||
label: t('geo.pick', { name: nm, events: unit('events', c.events) }), onClick: function () { go(c.cc, '', true); } }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
ui.sideH.textContent = t('geo.regions');
|
||||
var d = data.full;
|
||||
var rs = (d && d.regions) || [];
|
||||
if (!rs.length) { L.appendChild(emptyNote(t('geo.empty.list'))); return; }
|
||||
if (S.region) {
|
||||
var all = h('button', 'geo-chip', t('geo.all_regions')); all.type = 'button';
|
||||
all.addEventListener('click', function () { go(S.cc, '', true); });
|
||||
L.appendChild(all);
|
||||
}
|
||||
var mx = rs[0].events || 1;
|
||||
rs.forEach(function (r, i) {
|
||||
var can = !!r.name;
|
||||
L.appendChild(row({ rank: i + 1, name: regionName(r.name), sub: unit('ips', r.ips), n: r.events, frac: r.events / mx,
|
||||
cls: S.region === r.name && can ? 'on' : '',
|
||||
pressed: can ? S.region === r.name : null,
|
||||
label: can ? t('geo.pick.region', { name: r.name, events: unit('events', r.events) }) : '',
|
||||
onClick: can ? function () { go(S.cc, S.region === r.name ? '' : r.name, true); } : null }));
|
||||
});
|
||||
}
|
||||
|
||||
function renderDetail() {
|
||||
var show = !!S.cc && !!data.country;
|
||||
ui.detail.hidden = !show;
|
||||
if (!show) return;
|
||||
var d = data.country;
|
||||
// cities
|
||||
ui.pCities.h.textContent = t('geo.cities');
|
||||
var B = ui.pCities.body; clear(B);
|
||||
var cs = d.cities || [];
|
||||
if (!cs.length) B.appendChild(emptyNote(t('geo.empty.list')));
|
||||
else {
|
||||
var mx = cs[0].events || 1, nocoord = 0;
|
||||
cs.slice(0, 15).forEach(function (c, i) {
|
||||
var can = !!c.region && !S.region;
|
||||
var r = row({ rank: i + 1, name: c.name || t('geo.unknown'), sub: c.region || '', n: c.events, frac: c.events / mx,
|
||||
label: can ? t('geo.city.pick', { name: c.region }) : '', onClick: can ? function () { go(S.cc, c.region, true); } : null });
|
||||
r.addEventListener('mouseenter', function () { if (cityEls[i]) cityEls[i].classList.add('hl'); });
|
||||
r.addEventListener('mouseleave', function () { if (cityEls[i]) cityEls[i].classList.remove('hl'); });
|
||||
B.appendChild(r);
|
||||
});
|
||||
cs.forEach(function (c) { if (!isNum(c.lat) || !isNum(c.lon)) nocoord++; });
|
||||
if (nocoord) B.appendChild(h('div', 'geo-note', t(nocoord === 1 ? 'geo.nocoords.one' : 'geo.nocoords.other', { n: nf(nocoord) })));
|
||||
}
|
||||
// categories
|
||||
ui.pCats.h.textContent = t('geo.cats');
|
||||
B = ui.pCats.body; clear(B);
|
||||
var cats = d.cats || {}, keys = Object.keys(cats).sort(function (a, b) { return cats[b] - cats[a]; }), tot = sum(cats);
|
||||
if (!keys.length || !tot) B.appendChild(emptyNote(t('geo.empty.list')));
|
||||
else {
|
||||
var st = h('div', 'geo-stack'); st.setAttribute('aria-hidden', 'true');
|
||||
keys.forEach(function (k) { var s = h('span', catCls(k)); s.style.flexGrow = String(cats[k]); st.appendChild(s); });
|
||||
B.appendChild(st);
|
||||
var ul = h('ul', 'geo-chips');
|
||||
keys.forEach(function (k) {
|
||||
var li = h('li', 'geo-chipcat'), dot = h('i', catCls(k)); dot.setAttribute('aria-hidden', 'true');
|
||||
li.appendChild(dot); li.appendChild(h('span', '', catLabel(k))); li.appendChild(h('b', '', nf(cats[k]) + ' · ' + pct(cats[k] / tot)));
|
||||
ul.appendChild(li);
|
||||
});
|
||||
B.appendChild(ul);
|
||||
if (d.hostile || d.suspicious) B.appendChild(h('div', 'geo-note', t('geo.hostile_suspicious', { h: nf(d.hostile || 0), s: nf(d.suspicious || 0) })));
|
||||
}
|
||||
// ips
|
||||
ui.pIps.h.textContent = t('geo.ips');
|
||||
B = ui.pIps.body; clear(B);
|
||||
var ips = ipList(d);
|
||||
if (!ips.length) B.appendChild(emptyNote(t('geo.empty.list')));
|
||||
else ips.slice(0, 12).forEach(function (x) {
|
||||
var b = h('button', 'geo-ip'); b.type = 'button';
|
||||
b.setAttribute('aria-label', t('geo.open_ip', { ip: x.ip }));
|
||||
b.addEventListener('click', function () { U.openIP(x.ip); });
|
||||
var l1 = h('span', 'geo-ip-l1');
|
||||
l1.appendChild(h('code', '', x.ip));
|
||||
var lv = LEVELS[x.level] ? x.level : 'unknown';
|
||||
l1.appendChild(h('span', 'geo-lv geo-lv-' + lv, t('geo.level.' + lv)));
|
||||
if (isNum(x.score)) l1.appendChild(h('span', 'geo-score', t('geo.score', { n: nf(x.score) })));
|
||||
b.appendChild(l1);
|
||||
var where = [x.city, x.region].filter(Boolean).join(', '), who = [x.asn, x.as_org].filter(Boolean).join(' ');
|
||||
var l2 = h('span', 'geo-ip-l2', [where, who].filter(Boolean).join(' · '));
|
||||
b.appendChild(l2);
|
||||
if (x.last) { var ago = ''; try { ago = U.fmt.ago(x.last); } catch (e) { ago = ''; } if (ago) b.appendChild(h('span', 'geo-ip-l3', String(ago))); }
|
||||
B.appendChild(b);
|
||||
});
|
||||
}
|
||||
|
||||
function render(refit) {
|
||||
if (!ui) return;
|
||||
paintState();
|
||||
ui.err.hidden = !data.error;
|
||||
ui.loading.hidden = true;
|
||||
crumbs();
|
||||
if (data.error || !data.world) { lead(); ui.detail.hidden = true; clear(ui.sideList); clear(ui.gCity); ui.legend.hidden = true;
|
||||
ui.svg.setAttribute('class', 'geo-svg'); setView(targetView());
|
||||
Object.keys(ui.paths).forEach(function (cc) { ui.paths[cc].style.fillOpacity = ''; ui.paths[cc].setAttribute('class', 'geo-cn'); });
|
||||
return; }
|
||||
colorize(); lead(); renderSide(); renderDetail();
|
||||
clear(ui.gCity); cityEls = [];
|
||||
var to = targetView();
|
||||
if (refit === false) { setView(to); drawCities(); }
|
||||
else animateTo(to, drawCities);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- page
|
||||
U.registerPage({
|
||||
id: 'geo',
|
||||
icon: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.2 3 14.8 0 18M12 3c-3 3.2-3 14.8 0 18"/></svg>',
|
||||
titleKey: 'geo.title',
|
||||
mount: function (el, c) {
|
||||
ctx = c; lang = c.lang || 'en';
|
||||
world = U.world || window.URUTAU_WORLD;
|
||||
alive = true; cache = {}; view = null;
|
||||
if (!world || !world.paths) { clear(el); el.appendChild(h('div', 'geo-empty', t('geo.error'))); return; }
|
||||
var p = parseHash(); S.cc = world.paths[p.cc] ? p.cc : ''; S.region = S.cc ? p.region : '';
|
||||
build(el);
|
||||
window.addEventListener('hashchange', onHash);
|
||||
window.addEventListener('popstate', onHash);
|
||||
document.addEventListener('keydown', onKey);
|
||||
load(false);
|
||||
},
|
||||
update: function (c) {
|
||||
var langChanged = (c.lang || 'en') !== lang;
|
||||
ctx = c; lang = c.lang || 'en';
|
||||
if (!alive || !ui) return;
|
||||
cache = {};
|
||||
if (langChanged) { var el = root.parentNode; build(el); }
|
||||
load(false);
|
||||
},
|
||||
unmount: function () {
|
||||
alive = false; seq++;
|
||||
cancelAnimationFrame(anim); anim = 0;
|
||||
window.removeEventListener('hashchange', onHash);
|
||||
window.removeEventListener('popstate', onHash);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
if (ro) { ro.disconnect(); ro = null; }
|
||||
ui = null; root = null;
|
||||
}
|
||||
});
|
||||
})();
|
||||
+218
-27
@@ -1,20 +1,49 @@
|
||||
/* Urutau UI dictionaries. Every key must exist in both languages:
|
||||
scripts/check-ui-i18n.mjs enforces it. "{n}" is replaced by the caller. */
|
||||
scripts/check-ui-i18n.mjs enforces it. Placeholders are {n}, {name}...;
|
||||
scripts registered later add their own keys with Urutau.registerI18n.
|
||||
This file is loaded in <head>: the first lines below choose the theme and
|
||||
the language before the first paint, so there is no flash of the wrong theme. */
|
||||
(function () {
|
||||
try {
|
||||
var th = localStorage.getItem('urutau.theme');
|
||||
if (th === 'light' || th === 'dark') document.documentElement.setAttribute('data-theme', th);
|
||||
var lg = localStorage.getItem('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en');
|
||||
document.documentElement.lang = lg === 'pt-BR' ? 'pt-BR' : 'en';
|
||||
} catch (e) { /* storage blocked: the system preference applies */ }
|
||||
})();
|
||||
window.URUTAU_I18N = {
|
||||
en: {
|
||||
'tagline': 'Lightweight, always-on threat intelligence for self-hosted servers · local-first · authorized use.',
|
||||
'live.connecting': 'connecting',
|
||||
'live.on': 'live',
|
||||
'live.off': 'reconnecting',
|
||||
'conn.connecting': 'connecting',
|
||||
'conn.on': 'live',
|
||||
'conn.off': 'reconnecting',
|
||||
'host.label': 'Host',
|
||||
'host.all': 'All hosts',
|
||||
'range.label': 'Time range',
|
||||
'range.1h': '1 h',
|
||||
'range.24h': '24 h',
|
||||
'range.7d': '7 d',
|
||||
'range.long.1h': 'the last hour',
|
||||
'range.long.24h': 'the last 24 hours',
|
||||
'range.long.7d': 'the last 7 days',
|
||||
'lang.toggle': 'Switch language',
|
||||
'theme.toggle': 'Switch light/dark theme',
|
||||
'logout': 'Sign out',
|
||||
'nav.label': 'Main navigation',
|
||||
'nav.skip': 'Skip to content',
|
||||
'nav.more': 'More',
|
||||
'nav.overview': 'Overview',
|
||||
'nav.threats': 'Threats',
|
||||
'nav.traffic': 'Traffic',
|
||||
'nav.ips': 'IPs',
|
||||
'nav.sources': 'Sources and hosts',
|
||||
'slice.showing': 'Showing',
|
||||
'slice.allHosts': 'all hosts',
|
||||
'slice.host': 'host {name}',
|
||||
'slice.allDomains': 'all domains',
|
||||
'slice.domain': 'domain {name}',
|
||||
'slice.ips.one': '{n} IP',
|
||||
'slice.ips.other': '{n} IPs',
|
||||
'kpi.requests': 'Requests',
|
||||
'kpi.malicious': 'Malicious events',
|
||||
'kpi.hostile': 'Hostile IPs',
|
||||
@@ -22,14 +51,54 @@ window.URUTAU_I18N = {
|
||||
'kpi.bans': 'Active bans',
|
||||
'kpi.ips': 'Distinct IPs',
|
||||
'kpi.monitoring': '{n} monitoring requests filtered out.',
|
||||
'kpi.sub.hosts': 'hosts online: {n} of {m}',
|
||||
'kpi.sub.malicious': 'HTTP and SSH events',
|
||||
'kpi.sub.share': '{p} of {n} distinct IPs',
|
||||
'kpi.sub.bans': 'reported by fail2ban',
|
||||
'kpi.sub.range': 'in {range}',
|
||||
'ov.lead.hostile': '{n} hostile IPs in the selected slice',
|
||||
'ov.lead.hostile.one': '1 hostile IP in the selected slice',
|
||||
'ov.lead.calm': 'No hostile IPs in the selected slice',
|
||||
'ov.lead.empty': 'No events recorded in the selected slice',
|
||||
'ov.lead.body': 'Malicious events: {m}; requests: {r}; distinct IPs: {ips}; active bans: {b}.',
|
||||
'ov.lead.bodyEmpty': 'Widen the time range or choose another host. Sources report their state under Sources and hosts.',
|
||||
'ov.countries': 'Top countries',
|
||||
'ov.countries.hint': 'Origin of the events in the slice, by number of events.',
|
||||
'ov.topips': 'Top IPs by score',
|
||||
'ov.topips.hint': 'Highest threat score in the slice. Select an IP for its history.',
|
||||
'ov.all': 'View all',
|
||||
'ov.feed': 'Latest events',
|
||||
'ov.feed.hint': 'Most recent events, newest first, updated live.',
|
||||
'th.lead.top': 'Most activity is classified as "{cat}"',
|
||||
'th.lead.none': 'No attack activity in the selected slice',
|
||||
'th.lead.noneBody': 'No scanner, exploit, brute force or SSH events were classified in this slice.',
|
||||
'th.lead.body.one': '{n} of {m} classified event ({p}).',
|
||||
'th.lead.body.other': '{n} of {m} classified events ({p}).',
|
||||
'th.lead.domain': 'Most targeted domain: {name}.',
|
||||
'th.lead.origin': 'Main origin: {name}.',
|
||||
'tr.lead.some': 'Visitors: {n} · page views: {p}',
|
||||
'tr.lead.none': 'No traffic recorded in the selected slice',
|
||||
'tr.lead.noneBody': 'Analytics count only successful responses to non-bot clients on the configured domains.',
|
||||
'tr.lead.body': 'Requests: {r}, of which {b} from search and AI bots; latency p50 {a} ms and p95 {c} ms.',
|
||||
'ips.lead.one': '{n} distinct IP: {h} hostile, {s} suspicious',
|
||||
'ips.lead.other': '{n} distinct IPs: {h} hostile, {s} suspicious',
|
||||
'ips.lead.body': 'Banned IPs: {b}. Select a row for the full history of an IP.',
|
||||
'src.lead.all.one': 'The only source is being followed',
|
||||
'src.lead.all.other': 'All {n} sources are being followed',
|
||||
'src.lead.some': 'Sources following: {a} of {n}; needing attention: {x}',
|
||||
'src.lead.none': 'No log sources reported',
|
||||
'src.lead.body': 'Hosts online: {h} of {m}; lines read: {l}; malformed: {f}.',
|
||||
'feed.forged': 'forged monitor user agent',
|
||||
'timeline.title': 'Activity by category',
|
||||
'timeline.hint': 'Events per time bucket, stacked by category. Select a legend item to hide it.',
|
||||
'timeline.empty': 'No activity in this range.',
|
||||
'ips.title': 'Top IPs',
|
||||
'ips.hint': 'Every IP seen in the slice. Sort by a column heading; select a row for details.',
|
||||
'ips.search': 'Filter by IP or reverse DNS',
|
||||
'ips.level': 'Threat level',
|
||||
'ips.bannedOnly': 'Banned only',
|
||||
'ips.empty': 'No IPs match.',
|
||||
'ips.perPage': 'Rows per page',
|
||||
'ips.empty': 'No IPs match. Clear the filters or widen the time range.',
|
||||
'level.all': 'All levels',
|
||||
'level.hostile': 'Hostile',
|
||||
'level.suspicious': 'Suspicious',
|
||||
@@ -39,8 +108,11 @@ window.URUTAU_I18N = {
|
||||
'col.level': 'Level',
|
||||
'col.cats': 'Categories',
|
||||
'col.last': 'Last seen',
|
||||
'col.first': 'First seen',
|
||||
'col.events': 'Events',
|
||||
'col.banned': 'Banned',
|
||||
'col.host': 'Host',
|
||||
'col.hosts': 'Hosts',
|
||||
'col.source': 'Source',
|
||||
'col.state': 'State',
|
||||
'col.lines': 'Lines',
|
||||
@@ -48,30 +120,51 @@ window.URUTAU_I18N = {
|
||||
'col.lastEvent': 'Last event',
|
||||
'pager.prev': 'Previous',
|
||||
'pager.next': 'Next',
|
||||
'pager.count': '{n} IPs',
|
||||
'pager.count.one': '{n} IP',
|
||||
'pager.count.other': '{n} IPs',
|
||||
'pager.page': 'Page {n} of {m}',
|
||||
'feed.title': 'Live feed',
|
||||
'feed.empty': 'Waiting for events.',
|
||||
'top.paths': 'Most attacked paths',
|
||||
'top.domains': 'Most targeted domains',
|
||||
'top.uas': 'Top user agents',
|
||||
'top.users': 'SSH users tried',
|
||||
'top.empty': 'No data.',
|
||||
'top.empty': 'No data in the selected slice. Try a longer time range.',
|
||||
'blocklist.title': 'Blocklist',
|
||||
'blocklist.help': 'Export the IPs at or above a score as a plain list, one per line, for a firewall or fail2ban.',
|
||||
'blocklist.help': 'Export the IPs at or above a score as a plain list, one per line, for a firewall or fail2ban. Only IPs with strong evidence and a public address are listed.',
|
||||
'blocklist.minScore': 'Minimum score',
|
||||
'blocklist.family': 'Address family',
|
||||
'blocklist.family.all': 'IPv4 and IPv6',
|
||||
'blocklist.family.4': 'IPv4 only',
|
||||
'blocklist.family.6': 'IPv6 /64 only',
|
||||
'blocklist.copy': 'Copy list',
|
||||
'blocklist.download': 'Download',
|
||||
'blocklist.copied': '{n} IPs copied.',
|
||||
'blocklist.download': 'Download .txt',
|
||||
'blocklist.downloadJson': 'Download .json',
|
||||
'blocklist.copied.one': '{n} IP copied.',
|
||||
'blocklist.copied.other': '{n} IPs copied.',
|
||||
'blocklist.failed': 'Could not copy the list.',
|
||||
'hosts.title': 'Hosts',
|
||||
'blocklist.count.one': '{n} IP would be listed (selected range).',
|
||||
'blocklist.count.other': '{n} IPs would be listed (selected range).',
|
||||
'hosts.title': 'Hosts and peers',
|
||||
'hosts.hint': 'This instance and the peers it federates with.',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.self': 'this instance',
|
||||
'host.requests': 'Requests',
|
||||
'host.malicious': 'Malicious',
|
||||
'host.hostile': 'Hostile IPs',
|
||||
'host.bans': 'Bans',
|
||||
'host.latency': 'Latency',
|
||||
'sources.title': 'Sources',
|
||||
'host.seen': 'Last contact',
|
||||
'sources.title': 'Log sources',
|
||||
'sources.hint': 'Files this instance follows. Waiting or error states mean no new events are being read.',
|
||||
'sources.empty': 'No log source configured on the reporting hosts.',
|
||||
'src.geo.title': 'Geolocation',
|
||||
'src.geo.hint': 'Country, city and network of each IP come from a local database; nothing is queried online.',
|
||||
'src.geo.known': 'Listed IPs with a known origin: {n} of {m}',
|
||||
'src.geo.countries': 'Countries in the slice: {n}',
|
||||
'src.geo.attrib': 'Data attribution',
|
||||
'src.geo.none': 'No attribution reported by the geo database.',
|
||||
'state.following': 'following',
|
||||
'state.waiting': 'waiting for file',
|
||||
'state.backfill': 'reading history',
|
||||
@@ -94,6 +187,7 @@ window.URUTAU_I18N = {
|
||||
'ago.d': '{n}d ago',
|
||||
'never': 'never',
|
||||
'yes': 'yes',
|
||||
'detail.title': 'IP details',
|
||||
'detail.close': 'Close',
|
||||
'detail.copyIp': 'Copy IP',
|
||||
'detail.score': 'Score',
|
||||
@@ -108,13 +202,14 @@ window.URUTAU_I18N = {
|
||||
'detail.jails': 'Active bans',
|
||||
'detail.counts': 'Events',
|
||||
'detail.notfound': 'This IP is no longer in memory.',
|
||||
'detail.loading': 'Loading.',
|
||||
'error.load': 'Could not load data. Retrying.',
|
||||
'error.rate': 'Too many requests. Retrying shortly.',
|
||||
'footer': 'Urutau · watches motionless all night.',
|
||||
'tab.threats': 'Threats',
|
||||
'tab.traffic': 'Traffic',
|
||||
'traffic.domain': 'Domain',
|
||||
'traffic.allDomains': 'All domains',
|
||||
'traffic.timeline': 'Requests and page views',
|
||||
'traffic.timeline.hint': 'Requests answered per time bucket; the darker bar is the share counted as page views.',
|
||||
'traffic.requests': 'Requests',
|
||||
'traffic.pages': 'Page views',
|
||||
'traffic.visitors': 'Visitors',
|
||||
@@ -129,8 +224,14 @@ window.URUTAU_I18N = {
|
||||
'traffic.devices': 'Devices',
|
||||
'traffic.status': 'Status codes',
|
||||
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
|
||||
'traffic.sub.visitors': 'distinct, hash per day',
|
||||
'traffic.sub.requests': 'incl. assets and bots',
|
||||
'traffic.sub.pages': 'of {n} requests',
|
||||
'traffic.sub.bots': 'of {n} requests',
|
||||
'map.attacks': 'Origin of attacks',
|
||||
'map.attacks.hint': 'Countries shaded by number of events; the list shows the largest.',
|
||||
'map.visitors': 'Visitors by country',
|
||||
'map.visitors.hint': 'Countries shaded by number of requests; the list shows the largest.',
|
||||
'col.origin': 'Origin',
|
||||
'detail.country': 'Country',
|
||||
'detail.city': 'City',
|
||||
@@ -149,18 +250,36 @@ window.URUTAU_I18N = {
|
||||
},
|
||||
'pt-BR': {
|
||||
'tagline': 'Inteligência de ameaças leve e sempre ativa para servidores próprios · local-first · uso autorizado.',
|
||||
'live.connecting': 'conectando',
|
||||
'live.on': 'ao vivo',
|
||||
'live.off': 'reconectando',
|
||||
'conn.connecting': 'conectando',
|
||||
'conn.on': 'ao vivo',
|
||||
'conn.off': 'reconectando',
|
||||
'host.label': 'Host',
|
||||
'host.all': 'Todos os hosts',
|
||||
'range.label': 'Período',
|
||||
'range.1h': '1 h',
|
||||
'range.24h': '24 h',
|
||||
'range.7d': '7 d',
|
||||
'range.long.1h': 'a última hora',
|
||||
'range.long.24h': 'as últimas 24 horas',
|
||||
'range.long.7d': 'os últimos 7 dias',
|
||||
'lang.toggle': 'Trocar idioma',
|
||||
'theme.toggle': 'Alternar tema claro/escuro',
|
||||
'logout': 'Sair',
|
||||
'nav.label': 'Navegação principal',
|
||||
'nav.skip': 'Ir para o conteúdo',
|
||||
'nav.more': 'Mais',
|
||||
'nav.overview': 'Visão geral',
|
||||
'nav.threats': 'Ameaças',
|
||||
'nav.traffic': 'Tráfego',
|
||||
'nav.ips': 'IPs',
|
||||
'nav.sources': 'Fontes e hosts',
|
||||
'slice.showing': 'Exibindo',
|
||||
'slice.allHosts': 'todos os hosts',
|
||||
'slice.host': 'host {name}',
|
||||
'slice.allDomains': 'todos os domínios',
|
||||
'slice.domain': 'domínio {name}',
|
||||
'slice.ips.one': '{n} IP',
|
||||
'slice.ips.other': '{n} IPs',
|
||||
'kpi.requests': 'Requisições',
|
||||
'kpi.malicious': 'Eventos maliciosos',
|
||||
'kpi.hostile': 'IPs hostis',
|
||||
@@ -168,14 +287,54 @@ window.URUTAU_I18N = {
|
||||
'kpi.bans': 'Bans ativos',
|
||||
'kpi.ips': 'IPs distintos',
|
||||
'kpi.monitoring': '{n} requisições de monitoramento filtradas.',
|
||||
'kpi.sub.hosts': 'hosts online: {n} de {m}',
|
||||
'kpi.sub.malicious': 'eventos HTTP e SSH',
|
||||
'kpi.sub.share': '{p} dos {n} IPs distintos',
|
||||
'kpi.sub.bans': 'informados pelo fail2ban',
|
||||
'kpi.sub.range': 'em {range}',
|
||||
'ov.lead.hostile': '{n} IPs hostis no recorte selecionado',
|
||||
'ov.lead.hostile.one': '1 IP hostil no recorte selecionado',
|
||||
'ov.lead.calm': 'Nenhum IP hostil no recorte selecionado',
|
||||
'ov.lead.empty': 'Nenhum evento registrado no recorte selecionado',
|
||||
'ov.lead.body': 'Eventos maliciosos: {m}; requisições: {r}; IPs distintos: {ips}; bans ativos: {b}.',
|
||||
'ov.lead.bodyEmpty': 'Recomenda-se ampliar o período ou escolher outro host. O estado das fontes está em Fontes e hosts.',
|
||||
'ov.countries': 'Principais países',
|
||||
'ov.countries.hint': 'Origem dos eventos do recorte, por número de eventos.',
|
||||
'ov.topips': 'IPs de maior pontuação',
|
||||
'ov.topips.hint': 'Maiores pontuações de ameaça do recorte. Selecione um IP para ver o histórico.',
|
||||
'ov.all': 'Ver todos',
|
||||
'ov.feed': 'Últimos eventos',
|
||||
'ov.feed.hint': 'Eventos mais recentes primeiro, atualizados ao vivo.',
|
||||
'th.lead.top': 'A maior parte da atividade é classificada como "{cat}"',
|
||||
'th.lead.none': 'Nenhuma atividade de ataque no recorte selecionado',
|
||||
'th.lead.noneBody': 'Nenhum evento de scanner, exploit, força bruta ou SSH foi classificado neste recorte.',
|
||||
'th.lead.body.one': '{n} de {m} evento classificado ({p}).',
|
||||
'th.lead.body.other': '{n} de {m} eventos classificados ({p}).',
|
||||
'th.lead.domain': 'Domínio mais visado: {name}.',
|
||||
'th.lead.origin': 'Origem principal: {name}.',
|
||||
'tr.lead.some': 'Visitantes: {n} · páginas vistas: {p}',
|
||||
'tr.lead.none': 'Nenhum tráfego registrado no recorte selecionado',
|
||||
'tr.lead.noneBody': 'A análise de tráfego conta apenas respostas bem-sucedidas a clientes que não são bots, nos domínios configurados.',
|
||||
'tr.lead.body': 'Requisições: {r}, das quais {b} de bots de busca e de IA; latência p50 de {a} ms e p95 de {c} ms.',
|
||||
'ips.lead.one': '{n} IP distinto: {h} hostis, {s} suspeitos',
|
||||
'ips.lead.other': '{n} IPs distintos: {h} hostis, {s} suspeitos',
|
||||
'ips.lead.body': 'IPs banidos: {b}. Selecione uma linha para ver o histórico completo do IP.',
|
||||
'src.lead.all.one': 'A única fonte está sendo acompanhada',
|
||||
'src.lead.all.other': 'As {n} fontes estão sendo acompanhadas',
|
||||
'src.lead.some': 'Fontes acompanhadas: {a} de {n}; exigem atenção: {x}',
|
||||
'src.lead.none': 'Nenhuma fonte de log informada',
|
||||
'src.lead.body': 'Hosts online: {h} de {m}; linhas lidas: {l}; malformadas: {f}.',
|
||||
'feed.forged': 'user-agent de monitor forjado',
|
||||
'timeline.title': 'Atividade por categoria',
|
||||
'timeline.hint': 'Eventos por intervalo de tempo, empilhados por categoria. Selecione um item da legenda para ocultá-lo.',
|
||||
'timeline.empty': 'Nenhuma atividade neste período.',
|
||||
'ips.title': 'Principais IPs',
|
||||
'ips.hint': 'Todos os IPs vistos no recorte. Ordene pelo título da coluna; selecione uma linha para os detalhes.',
|
||||
'ips.search': 'Filtrar por IP ou DNS reverso',
|
||||
'ips.level': 'Nível de ameaça',
|
||||
'ips.bannedOnly': 'Só banidos',
|
||||
'ips.empty': 'Nenhum IP corresponde.',
|
||||
'ips.perPage': 'Linhas por página',
|
||||
'ips.empty': 'Nenhum IP corresponde. Remova os filtros ou amplie o período.',
|
||||
'level.all': 'Todos os níveis',
|
||||
'level.hostile': 'Hostil',
|
||||
'level.suspicious': 'Suspeito',
|
||||
@@ -185,8 +344,11 @@ window.URUTAU_I18N = {
|
||||
'col.level': 'Nível',
|
||||
'col.cats': 'Categorias',
|
||||
'col.last': 'Visto por último',
|
||||
'col.first': 'Visto pela primeira vez',
|
||||
'col.events': 'Eventos',
|
||||
'col.banned': 'Banido',
|
||||
'col.host': 'Host',
|
||||
'col.hosts': 'Hosts',
|
||||
'col.source': 'Fonte',
|
||||
'col.state': 'Estado',
|
||||
'col.lines': 'Linhas',
|
||||
@@ -194,30 +356,51 @@ window.URUTAU_I18N = {
|
||||
'col.lastEvent': 'Último evento',
|
||||
'pager.prev': 'Anterior',
|
||||
'pager.next': 'Próxima',
|
||||
'pager.count': '{n} IPs',
|
||||
'pager.count.one': '{n} IP',
|
||||
'pager.count.other': '{n} IPs',
|
||||
'pager.page': 'Página {n} de {m}',
|
||||
'feed.title': 'Feed ao vivo',
|
||||
'feed.empty': 'Aguardando eventos.',
|
||||
'top.paths': 'Caminhos mais atacados',
|
||||
'top.domains': 'Domínios mais visados',
|
||||
'top.uas': 'Principais user-agents',
|
||||
'top.users': 'Usuários SSH tentados',
|
||||
'top.empty': 'Sem dados.',
|
||||
'top.empty': 'Sem dados no recorte selecionado. Recomenda-se ampliar o período.',
|
||||
'blocklist.title': 'Lista de bloqueio',
|
||||
'blocklist.help': 'Exporte os IPs a partir de uma pontuação como lista simples, um por linha, para firewall ou fail2ban.',
|
||||
'blocklist.help': 'Exporta os IPs a partir de uma pontuação como lista simples, um por linha, para firewall ou fail2ban. Somente IPs com evidência forte e endereço público são listados.',
|
||||
'blocklist.minScore': 'Pontuação mínima',
|
||||
'blocklist.family': 'Família de endereços',
|
||||
'blocklist.family.all': 'IPv4 e IPv6',
|
||||
'blocklist.family.4': 'Somente IPv4',
|
||||
'blocklist.family.6': 'Somente IPv6 /64',
|
||||
'blocklist.copy': 'Copiar lista',
|
||||
'blocklist.download': 'Baixar',
|
||||
'blocklist.copied': '{n} IPs copiados.',
|
||||
'blocklist.download': 'Baixar .txt',
|
||||
'blocklist.downloadJson': 'Baixar .json',
|
||||
'blocklist.copied.one': '{n} IP copiado.',
|
||||
'blocklist.copied.other': '{n} IPs copiados.',
|
||||
'blocklist.failed': 'Não foi possível copiar a lista.',
|
||||
'hosts.title': 'Hosts',
|
||||
'blocklist.count.one': '{n} IP seria listado (período selecionado).',
|
||||
'blocklist.count.other': '{n} IPs seriam listados (período selecionado).',
|
||||
'hosts.title': 'Hosts e pares',
|
||||
'hosts.hint': 'Esta instância e os pares com os quais ela se federa.',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.self': 'esta instância',
|
||||
'host.requests': 'Requisições',
|
||||
'host.malicious': 'Maliciosos',
|
||||
'host.hostile': 'IPs hostis',
|
||||
'host.bans': 'Bans',
|
||||
'host.latency': 'Latência',
|
||||
'sources.title': 'Fontes',
|
||||
'host.seen': 'Último contato',
|
||||
'sources.title': 'Fontes de log',
|
||||
'sources.hint': 'Arquivos que esta instância acompanha. Os estados aguardando e erro indicam que nenhum evento novo está sendo lido.',
|
||||
'sources.empty': 'Nenhuma fonte de log configurada nos hosts informantes.',
|
||||
'src.geo.title': 'Geolocalização',
|
||||
'src.geo.hint': 'País, cidade e rede de cada IP vêm de uma base local; nenhuma consulta é feita online.',
|
||||
'src.geo.known': 'IPs listados com origem conhecida: {n} de {m}',
|
||||
'src.geo.countries': 'Países no recorte: {n}',
|
||||
'src.geo.attrib': 'Atribuição dos dados',
|
||||
'src.geo.none': 'Nenhuma atribuição informada pela base de geolocalização.',
|
||||
'state.following': 'acompanhando',
|
||||
'state.waiting': 'aguardando arquivo',
|
||||
'state.backfill': 'lendo histórico',
|
||||
@@ -240,6 +423,7 @@ window.URUTAU_I18N = {
|
||||
'ago.d': 'há {n}d',
|
||||
'never': 'nunca',
|
||||
'yes': 'sim',
|
||||
'detail.title': 'Detalhes do IP',
|
||||
'detail.close': 'Fechar',
|
||||
'detail.copyIp': 'Copiar IP',
|
||||
'detail.score': 'Pontos',
|
||||
@@ -254,13 +438,14 @@ window.URUTAU_I18N = {
|
||||
'detail.jails': 'Bans ativos',
|
||||
'detail.counts': 'Eventos',
|
||||
'detail.notfound': 'Este IP não está mais na memória.',
|
||||
'detail.loading': 'Carregando.',
|
||||
'error.load': 'Não foi possível carregar os dados. Tentando de novo.',
|
||||
'error.rate': 'Requisições demais. Nova tentativa em instantes.',
|
||||
'footer': 'Urutau · vigia imóvel a noite toda.',
|
||||
'tab.threats': 'Ameaças',
|
||||
'tab.traffic': 'Tráfego',
|
||||
'traffic.domain': 'Domínio',
|
||||
'traffic.allDomains': 'Todos os domínios',
|
||||
'traffic.timeline': 'Requisições e páginas vistas',
|
||||
'traffic.timeline.hint': 'Requisições atendidas por intervalo; a barra mais escura é a parcela contada como página vista.',
|
||||
'traffic.requests': 'Requisições',
|
||||
'traffic.pages': 'Páginas vistas',
|
||||
'traffic.visitors': 'Visitantes',
|
||||
@@ -275,8 +460,14 @@ window.URUTAU_I18N = {
|
||||
'traffic.devices': 'Dispositivos',
|
||||
'traffic.status': 'Códigos de status',
|
||||
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
|
||||
'traffic.sub.visitors': 'distintos, hash diário',
|
||||
'traffic.sub.requests': 'inclui recursos e bots',
|
||||
'traffic.sub.pages': 'de {n} requisições',
|
||||
'traffic.sub.bots': 'de {n} requisições',
|
||||
'map.attacks': 'Origem dos ataques',
|
||||
'map.attacks.hint': 'Países sombreados pelo número de eventos; a lista mostra os maiores.',
|
||||
'map.visitors': 'Visitantes por país',
|
||||
'map.visitors.hint': 'Países sombreados pelo número de requisições; a lista mostra os maiores.',
|
||||
'col.origin': 'Origem',
|
||||
'detail.country': 'País',
|
||||
'detail.city': 'Cidade',
|
||||
|
||||
+45
-138
@@ -7,159 +7,66 @@
|
||||
<title>Urutau</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<link rel="stylesheet" href="/geo.css">
|
||||
<link rel="stylesheet" href="/live.css">
|
||||
<script src="/i18n.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header class="top">
|
||||
<div class="brand">
|
||||
<img src="/logo.png" alt="Urutau" width="44" height="44">
|
||||
<div><h1>Urutau</h1><small data-i18n="tagline"></small></div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<span class="live"><span class="dot" id="live-dot"></span><span id="live-text" data-i18n="live.connecting"></span></span>
|
||||
<select id="host" data-i18n-aria="host.label"></select>
|
||||
<div class="seg" id="range" role="group" data-i18n-aria="range.label">
|
||||
<button type="button" data-range="1h" data-i18n="range.1h"></button>
|
||||
<button type="button" data-range="24h" data-i18n="range.24h"></button>
|
||||
<button type="button" data-range="7d" data-i18n="range.7d"></button>
|
||||
<a class="skip" href="#view" data-i18n="nav.skip"></a>
|
||||
<div class="app" id="app">
|
||||
<aside class="rail" id="rail">
|
||||
<a class="rail-brand" href="#/overview">
|
||||
<img src="/logo.png" alt="" width="36" height="36">
|
||||
<span class="brand-name">Urutau</span>
|
||||
</a>
|
||||
<nav class="nav" id="nav" data-i18n-aria="nav.label"></nav>
|
||||
<div class="rail-foot"><span id="ver"></span></div>
|
||||
</aside>
|
||||
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<a class="top-brand" href="#/overview"><img src="/logo.png" alt="Urutau" width="30" height="30"></a>
|
||||
<h1 id="page-title"></h1>
|
||||
<div class="top-actions">
|
||||
<span class="conn" id="conn"><span class="dot" id="live-dot"></span><span id="live-text" data-i18n="conn.connecting"></span></span>
|
||||
<button type="button" class="btn" id="lang" data-i18n-aria="lang.toggle">EN</button>
|
||||
<button type="button" class="btn icon" id="theme" data-i18n-aria="theme.toggle" data-i18n-title="theme.toggle">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M12 4v16"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor"/></svg>
|
||||
</button>
|
||||
<form method="post" action="/logout"><button class="btn" type="submit" data-i18n="logout"></button></form>
|
||||
</div>
|
||||
<button type="button" class="btn" id="lang" data-i18n-aria="lang.toggle">EN</button>
|
||||
<button type="button" class="btn" id="theme" data-i18n-aria="theme.toggle" data-i18n-title="theme.toggle">◐</button>
|
||||
<form method="post" action="/logout"><button class="btn" type="submit" data-i18n="logout"></button></form>
|
||||
</div>
|
||||
</header>
|
||||
</header>
|
||||
|
||||
<nav class="tabs" role="tablist">
|
||||
<button type="button" role="tab" id="tab-btn-threats" data-tab="threats" aria-selected="true" data-i18n="tab.threats"></button>
|
||||
<button type="button" role="tab" id="tab-btn-traffic" data-tab="traffic" aria-selected="false" data-i18n="tab.traffic"></button>
|
||||
<select id="domain" hidden data-i18n-aria="traffic.domain"></select>
|
||||
</nav>
|
||||
|
||||
<div class="err-banner" id="err" hidden></div>
|
||||
|
||||
<div id="tab-threats">
|
||||
|
||||
<section class="grid kpis" id="kpis"></section>
|
||||
|
||||
<p class="empty mono" id="monitoring"></p>
|
||||
|
||||
<section class="panel">
|
||||
<h2 data-i18n="timeline.title"></h2>
|
||||
<div class="chart-wrap" id="chart"></div>
|
||||
<div class="legend" id="legend"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="map.attacks"></h2>
|
||||
<div class="mapbox"><div class="map" id="map-threats"></div><div class="maplist" id="maplist-threats"></div></div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-main mt">
|
||||
<div class="panel">
|
||||
<h2 data-i18n="ips.title"></h2>
|
||||
<div class="toolbar">
|
||||
<input type="text" id="q" data-i18n-ph="ips.search" data-i18n-aria="ips.search" autocomplete="off">
|
||||
<select id="level" data-i18n-aria="ips.level">
|
||||
<option value="" data-i18n="level.all"></option>
|
||||
<option value="hostile" data-i18n="level.hostile"></option>
|
||||
<option value="suspicious" data-i18n="level.suspicious"></option>
|
||||
<option value="low" data-i18n="level.low"></option>
|
||||
</select>
|
||||
<label class="live"><input type="checkbox" id="bannedOnly"> <span data-i18n="ips.bannedOnly"></span></label>
|
||||
</div>
|
||||
<table class="stack" id="ips">
|
||||
<thead><tr>
|
||||
<th><button type="button" data-sort="ip" data-i18n="col.ip"></button></th>
|
||||
<th><button type="button" data-sort="score" data-i18n="col.score"></button></th>
|
||||
<th data-i18n="col.level"></th>
|
||||
<th data-i18n="col.cats"></th>
|
||||
<th data-i18n="col.origin"></th>
|
||||
<th><button type="button" data-sort="last" data-i18n="col.last"></button></th>
|
||||
<th data-i18n="col.banned"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<div class="pager">
|
||||
<span id="count"></span>
|
||||
<span><button type="button" class="btn" id="prev" data-i18n="pager.prev"></button> <button type="button" class="btn" id="next" data-i18n="pager.next"></button></span>
|
||||
<div class="slice" id="slice">
|
||||
<div class="slice-ctl">
|
||||
<div class="seg" id="range" role="group" data-i18n-aria="range.label">
|
||||
<button type="button" data-range="1h" data-i18n="range.1h"></button>
|
||||
<button type="button" data-range="24h" data-i18n="range.24h"></button>
|
||||
<button type="button" data-range="7d" data-i18n="range.7d"></button>
|
||||
</div>
|
||||
<select id="host" data-i18n-aria="host.label"></select>
|
||||
<select id="domain" hidden data-i18n-aria="traffic.domain"></select>
|
||||
</div>
|
||||
<p class="slice-txt" id="slice-text" aria-live="polite"></p>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h2 data-i18n="feed.title"></h2>
|
||||
<ul class="feed" id="feed"></ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="top.paths"></h2><div id="top-paths"></div></div>
|
||||
<div class="panel"><h2 data-i18n="top.domains"></h2><div id="top-domains"></div></div>
|
||||
<div class="panel"><h2 data-i18n="top.uas"></h2><div id="top-uas"></div></div>
|
||||
</section>
|
||||
<div class="err-banner" id="err" role="alert" hidden></div>
|
||||
|
||||
<section class="grid cols-2 mt">
|
||||
<div class="panel"><h2 data-i18n="top.users"></h2><div id="top-users"></div></div>
|
||||
<div class="panel">
|
||||
<h2 data-i18n="blocklist.title"></h2>
|
||||
<p class="empty" data-i18n="blocklist.help"></p>
|
||||
<div class="toolbar">
|
||||
<label class="live"><span data-i18n="blocklist.minScore"></span> <input type="number" id="minScore" value="50" min="0" step="1"></label>
|
||||
<button type="button" class="btn primary" id="copyBl" data-i18n="blocklist.copy"></button>
|
||||
<a class="btn" id="dlBl" href="/api/v1/blocklist.txt?download=1" data-i18n="blocklist.download"></a>
|
||||
</div>
|
||||
<div class="empty" id="blMsg" role="status"></div>
|
||||
</div>
|
||||
</section>
|
||||
<main id="view" tabindex="-1"></main>
|
||||
|
||||
</div>
|
||||
<footer class="shell-foot"><span data-i18n="footer"></span><div id="attrib"></div></footer>
|
||||
</div>
|
||||
|
||||
<div id="tab-traffic" hidden>
|
||||
<section class="grid kpis" id="tkpis"></section>
|
||||
<section class="panel">
|
||||
<h2 data-i18n="traffic.timeline"></h2>
|
||||
<div class="chart-wrap" id="tchart"></div>
|
||||
<div class="legend"><span class="live"><span class="sw t-req"></span><span data-i18n="traffic.requests"></span></span> <span class="live"><span class="sw t-pages"></span><span data-i18n="traffic.pages"></span></span></div>
|
||||
</section>
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="map.visitors"></h2>
|
||||
<div class="mapbox"><div class="map" id="map-traffic"></div><div class="maplist" id="maplist-traffic"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.topPages"></h2><div id="t-pages"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.referrers"></h2><div id="t-refs"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.cities"></h2><div id="t-cities"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.browsers"></h2><div id="t-browsers"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.oses"></h2><div id="t-oses"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.devices"></h2><div id="t-devices"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-2 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.bots"></h2><div id="t-bots"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.status"></h2><div id="t-status"></div><p class="empty" data-i18n="traffic.privacy"></p></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="hosts.title"></h2>
|
||||
<div class="hosts" id="hosts"></div>
|
||||
<h2 class="mt" data-i18n="sources.title"></h2>
|
||||
<table class="stack" id="sources">
|
||||
<thead><tr>
|
||||
<th data-i18n="col.host"></th><th data-i18n="col.source"></th><th data-i18n="col.state"></th>
|
||||
<th data-i18n="col.lines"></th><th data-i18n="col.malformed"></th><th data-i18n="col.lastEvent"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<footer><span data-i18n="footer"></span> <span id="ver"></span><div id="attrib"></div></footer>
|
||||
<nav class="tabbar" id="tabbar" data-i18n-aria="nav.label"></nav>
|
||||
<div class="more-sheet" id="more" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="scrim" id="scrim" hidden></div>
|
||||
<aside id="detail" hidden aria-live="polite"></aside>
|
||||
<aside id="detail" role="dialog" aria-modal="true" data-i18n-aria="detail.title" hidden></aside>
|
||||
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/world.js"></script>
|
||||
<script src="/app.js"></script>
|
||||
<script src="/geo.js"></script>
|
||||
<script src="/live.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Urutau - AO VIVO page. Everything is prefixed lv- (the shell already owns .live, .panel, .btn...). */
|
||||
.lv {
|
||||
--lv-gap: 8px;
|
||||
position: relative; height: clamp(560px, calc(100dvh - 215px), 920px); overflow: hidden;
|
||||
border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow);
|
||||
background:
|
||||
radial-gradient(900px 420px at 50% 40%, color-mix(in srgb, var(--accent) 9%, transparent), transparent 70%),
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--bg) 94%, var(--accent)), var(--bg-2));
|
||||
}
|
||||
.lv-view { position: absolute; inset: 0; }
|
||||
.lv-cv { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: pan-y; outline-offset: -3px; }
|
||||
.lv-cv.lv-globe { cursor: grab; }
|
||||
.lv-cv.lv-grab { cursor: grabbing; }
|
||||
|
||||
/* toolbar */
|
||||
.lv-bar { position: absolute; top: 10px; left: 10px; display: flex; flex-wrap: wrap; gap: 6px; z-index: 2; }
|
||||
.lv-btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 6px; cursor: pointer;
|
||||
min-height: 36px; min-width: 36px; padding: 6px 12px; border-radius: 10px; font-size: 13px;
|
||||
background: var(--panel); color: var(--text); border: 1px solid var(--line);
|
||||
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
.lv-btn:hover { border-color: var(--accent); }
|
||||
.lv-btn[aria-pressed="true"].lv-pause, .lv-btn[aria-pressed="true"].lv-fs { border-color: var(--accent); color: var(--accent); }
|
||||
.lv-seg { display: inline-flex; border-radius: 10px; overflow: hidden; border: 1px solid var(--line); background: var(--panel); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); }
|
||||
.lv-seg .lv-btn { border: 0; border-radius: 0; background: transparent; backdrop-filter: none; -webkit-backdrop-filter: none; }
|
||||
.lv-seg .lv-btn[aria-pressed="true"] { background: var(--accent); color: var(--on-accent); font-weight: 600; }
|
||||
.lv-ic { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex: none; }
|
||||
|
||||
/* status notes */
|
||||
.lv-notes { position: absolute; top: 10px; right: 10px; display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; max-width: 52%; z-index: 2; pointer-events: none; }
|
||||
.lv-note {
|
||||
font-size: 12px; padding: 4px 10px; border-radius: 999px; color: var(--muted);
|
||||
background: var(--panel); border: 1px solid var(--line); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
.lv-note[hidden], .lv-hint[hidden] { display: none; }
|
||||
.lv-hint { position: absolute; left: 12px; top: 54px; font-size: 11px; color: var(--muted); pointer-events: none; z-index: 1; }
|
||||
|
||||
/* dock of panels */
|
||||
.lv-dock {
|
||||
position: absolute; left: 10px; right: 10px; bottom: 10px; z-index: 2;
|
||||
display: flex; align-items: flex-end; gap: var(--lv-gap); overflow-x: auto; overflow-y: hidden; padding-bottom: 2px;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.lv-nodock .lv-dock { display: none; }
|
||||
.lv-card {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px;
|
||||
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); min-width: 0; flex: 0 0 auto;
|
||||
}
|
||||
.lv-card-h {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%;
|
||||
background: none; border: 0; padding: 0 0 6px; cursor: pointer; color: var(--muted); text-align: left;
|
||||
}
|
||||
.lv-card-t { font-size: 11px; text-transform: uppercase; letter-spacing: .08em; font-weight: 600; }
|
||||
.lv-card-h .lv-ic { width: 14px; height: 14px; transition: transform .15s; }
|
||||
.lv-collapsed .lv-card-h { padding-bottom: 0; }
|
||||
.lv-collapsed .lv-card-h .lv-ic { transform: rotate(-90deg); }
|
||||
.lv-collapsed .lv-card-b { display: none; }
|
||||
.lv-card-b { max-height: 128px; overflow-y: auto; overflow-x: hidden; scrollbar-width: thin; }
|
||||
.lv-c-rate { width: 150px; }
|
||||
.lv-c-cats { width: 310px; }
|
||||
.lv-c-hosts { width: 160px; }
|
||||
.lv-c-cty { width: 200px; }
|
||||
.lv-c-rec { flex: 1 1 340px; min-width: 300px; }
|
||||
.lv-collapsed { width: auto; flex: 0 0 auto; min-width: 0; }
|
||||
.lv-c-rec.lv-collapsed { flex: 0 0 auto; min-width: 0; }
|
||||
|
||||
.lv-rate-v { font-size: 34px; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; color: var(--text); }
|
||||
.lv-rate-u { font-size: 11px; color: var(--muted); margin: 3px 0 6px; }
|
||||
.lv-spark { display: block; width: 100%; height: 28px; }
|
||||
|
||||
/* category and host chips (legend + filters) */
|
||||
.lv-k-notfound { --k: var(--cat-notfound); } .lv-k-scanner { --k: var(--cat-scanner); } .lv-k-bruteforce { --k: var(--cat-bruteforce); }
|
||||
.lv-k-exploit { --k: var(--cat-exploit); } .lv-k-ssh-fail { --k: var(--cat-ssh-fail); } .lv-k-ssh-probe { --k: var(--cat-ssh-probe); }
|
||||
.lv-k-ban { --k: var(--cat-ban); }
|
||||
.lv-chips { display: grid; grid-template-columns: 1fr 1fr; gap: 3px 8px; }
|
||||
.lv-hostchips { grid-template-columns: 1fr; }
|
||||
.lv-chip {
|
||||
display: flex; align-items: center; gap: 6px; min-width: 0; padding: 2px 4px; border-radius: 6px;
|
||||
background: none; border: 0; cursor: pointer; font-size: 12px; color: var(--text); text-align: left; min-height: 24px;
|
||||
}
|
||||
.lv-chip:hover { background: var(--field); }
|
||||
.lv-chip[aria-pressed="false"] { opacity: .4; }
|
||||
.lv-chip[aria-pressed="false"] .lv-chip-l { text-decoration: line-through; }
|
||||
.lv-sw { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }
|
||||
.lv-hot .lv-sw { box-shadow: 0 0 0 2px color-mix(in srgb, var(--k) 35%, transparent); }
|
||||
.lv-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--h, var(--accent)); flex: none; }
|
||||
.lv-chip-l { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
|
||||
.lv-chip-n { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 11px; }
|
||||
.lv-legend { font-size: 11px; color: var(--muted); margin-top: 5px; }
|
||||
|
||||
/* countries */
|
||||
.lv-cty, .lv-rec { list-style: none; margin: 0; padding: 0; }
|
||||
.lv-cty-i { position: relative; display: flex; justify-content: space-between; gap: 8px; font-size: 12px; padding: 2px 4px; min-height: 20px; }
|
||||
.lv-cty-n { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; position: relative; z-index: 1; }
|
||||
.lv-cty-v { font-variant-numeric: tabular-nums; color: var(--muted); position: relative; z-index: 1; }
|
||||
.lv-cty-b { position: absolute; left: 0; bottom: 0; height: 100%; width: var(--w, 0); border-radius: 4px; background: color-mix(in srgb, var(--accent) 18%, transparent); }
|
||||
|
||||
/* latest events (also the text alternative of the canvas) */
|
||||
.lv-ev { display: grid; grid-template-columns: auto auto auto minmax(0, 1fr); align-items: center; gap: 6px; font-size: 11.5px; padding: 2px 0; }
|
||||
.lv-ev-t { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.lv-tag {
|
||||
font-size: 10.5px; padding: 1px 6px; border-radius: 999px; white-space: nowrap;
|
||||
border: 1px solid var(--k, var(--line)); background: color-mix(in srgb, var(--k, transparent) 20%, transparent);
|
||||
}
|
||||
.lv-tag.lv-hot { font-weight: 700; }
|
||||
.lv-ip { background: none; border: 0; padding: 2px 0; cursor: pointer; color: var(--accent); font: inherit; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; text-decoration: underline dotted; white-space: nowrap; }
|
||||
.lv-ip:hover { text-decoration: underline; }
|
||||
.lv-ev-w { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
|
||||
.lv-empty { color: var(--muted); font-size: 12px; list-style: none; padding: 4px; }
|
||||
|
||||
.lv-btn:focus-visible, .lv-chip:focus-visible, .lv-card-h:focus-visible, .lv-ip:focus-visible, .lv-cv:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
|
||||
/* presentation mode */
|
||||
.lv-full { height: 100vh; border-radius: 0; border: 0; }
|
||||
|
||||
/* narrow screens: the panels become a strip below the map */
|
||||
@media (max-width: 720px) {
|
||||
.lv { height: auto; overflow: visible; display: flex; flex-direction: column; }
|
||||
.lv-full { height: 100vh; overflow: auto; }
|
||||
.lv-view { position: relative; inset: auto; height: 56vh; min-height: 340px; flex: none; }
|
||||
.lv-full .lv-view { flex: 1; height: auto; }
|
||||
.lv-dock { position: static; padding: 8px; border-top: 1px solid var(--line); align-items: stretch; }
|
||||
.lv-card { flex: 0 0 82vw; width: 82vw; }
|
||||
.lv-c-rate, .lv-c-cats, .lv-c-hosts, .lv-c-cty, .lv-c-rec { width: 82vw; min-width: 0; flex: 0 0 82vw; }
|
||||
.lv-collapsed, .lv-c-rec.lv-collapsed { width: 82vw; flex: 0 0 82vw; }
|
||||
.lv-card-b { max-height: 150px; }
|
||||
.lv-btn { min-height: 40px; min-width: 40px; }
|
||||
.lv-notes { top: auto; bottom: 8px; right: 8px; max-width: 80%; }
|
||||
.lv-hint { top: auto; bottom: 10px; left: 10px; }
|
||||
.lv-bar { gap: 4px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lv-card-h .lv-ic { transition: none; }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+392
-170
@@ -1,204 +1,426 @@
|
||||
/* Urutau design system.
|
||||
One vocabulary of surfaces, lines, text, status and chart colors. Every rule
|
||||
below consumes these tokens: no component invents its own color, its own
|
||||
font size or its own card. Dark is the identity theme (the original Urutau
|
||||
palette); light swaps the values only. The theme is chosen before the first
|
||||
paint by /i18n.js (loaded in <head>), never by a component. */
|
||||
|
||||
:root {
|
||||
--bg: #070d14; --bg-2: #0b1420; --panel: rgba(13, 25, 38, .82); --line: rgba(148, 188, 205, .16);
|
||||
--text: #e8f2f4; --muted: #8ea5b0; --accent: #38bdf8; --accent-2: #f0b35b;
|
||||
--sev-critical: #ef4444; --sev-high: #f97316; --sev-medium: #f59e0b; --sev-low: #10b981; --sev-info: #64748b;
|
||||
--radius: 16px; --field: rgba(148, 188, 205, .08); --shadow: 0 10px 30px rgba(0, 0, 0, .35);
|
||||
--c-ssh-probe: #a5b4fc; color-scheme: dark;
|
||||
/* surfaces, from the application background to the highest element */
|
||||
--surface-base: #070d14;
|
||||
--surface-sunken: #050a10;
|
||||
--surface-panel: #0d1926;
|
||||
--surface-raised: #13232f;
|
||||
--surface-overlay: #172b3b;
|
||||
/* lines and text */
|
||||
--line: #223546;
|
||||
--line-strong: #36506a;
|
||||
--ink: #e8f2f4;
|
||||
--ink-muted: #9db3bd;
|
||||
--ink-faint: #7f96a1;
|
||||
--heading: #f2f8fa;
|
||||
/* brand */
|
||||
--accent: #38bdf8;
|
||||
--accent-soft: #0f2f45;
|
||||
--on-accent: #04121c;
|
||||
--signal: #2ee27a;
|
||||
--rail: #060b11;
|
||||
--rail-ink: #c4d4db;
|
||||
--rail-ink-muted: #7f96a1;
|
||||
--rail-line: #16242f;
|
||||
--rail-active: #12303f;
|
||||
--lead-bg: #0c2a3d;
|
||||
--lead-bg-2: #0b1f30;
|
||||
--lead-ink: #eef7fa;
|
||||
--lead-ink-muted: #b4cdd6;
|
||||
/* status: color with meaning only (danger, warning, ok, info) */
|
||||
--ok: #34d399;
|
||||
--ok-soft: #0e3326;
|
||||
--warn: #f0b35b;
|
||||
--warn-soft: #3a2b0e;
|
||||
--danger: #f87171;
|
||||
--danger-soft: #3d1619;
|
||||
--info: #60a5fa;
|
||||
--info-soft: #112c4a;
|
||||
/* categorical palette for charts: fixed order, series n keeps its color */
|
||||
--viz-1: #58a6ff;
|
||||
--viz-2: #3fb950;
|
||||
--viz-3: #d29922;
|
||||
--viz-4: #f85149;
|
||||
--viz-5: #bc8cff;
|
||||
--viz-6: #39c5cf;
|
||||
--viz-7: #ff9b4a;
|
||||
--viz-8: #8b9eb0;
|
||||
/* event categories, mapped onto the palette */
|
||||
--cat-ok: var(--viz-2);
|
||||
--cat-ssh-ok: var(--viz-2);
|
||||
--cat-notfound: var(--viz-8);
|
||||
--cat-scanner: var(--viz-3);
|
||||
--cat-bruteforce: var(--viz-7);
|
||||
--cat-exploit: var(--viz-4);
|
||||
--cat-ssh-fail: var(--viz-1);
|
||||
--cat-ssh-probe: var(--viz-5);
|
||||
--cat-ban: var(--viz-6);
|
||||
/* type */
|
||||
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
--font-display: "Avenir Next", "Segoe UI Variable Display", "Segoe UI", system-ui, -apple-system, Roboto, sans-serif;
|
||||
--font-mono: ui-monospace, "SF Mono", "Cascadia Mono", Menlo, Consolas, "Liberation Mono", monospace;
|
||||
/* space and shape */
|
||||
--s-1: 4px; --s-2: 8px; --s-3: 12px; --s-4: 16px; --s-5: 20px; --s-6: 28px;
|
||||
--radius: 10px;
|
||||
--radius-sm: 7px;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, .35), 0 10px 28px rgba(0, 0, 0, .28);
|
||||
--scrim: rgba(2, 6, 10, .62);
|
||||
--rail-w: 232px;
|
||||
color-scheme: dark;
|
||||
|
||||
/* compatibility aliases for scripts written against the first version */
|
||||
--bg: var(--surface-base); --bg-2: var(--surface-sunken); --panel: var(--surface-panel); --text: var(--ink);
|
||||
--muted: var(--ink-muted); --field: var(--surface-raised); --accent-2: var(--warn);
|
||||
--sev-critical: var(--danger); --sev-high: var(--viz-7); --sev-medium: var(--warn); --sev-low: var(--ok); --sev-info: var(--ink-faint);
|
||||
}
|
||||
:root[data-theme="light"] {
|
||||
--bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13);
|
||||
--text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05);
|
||||
--shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light;
|
||||
--surface-base: #eff3f7;
|
||||
--surface-sunken: #e2eaf0;
|
||||
--surface-panel: #ffffff;
|
||||
--surface-raised: #f4f7fa;
|
||||
--surface-overlay: #ffffff;
|
||||
--line: #d6e0e7;
|
||||
--line-strong: #aebfcb;
|
||||
--ink: #0f1f26;
|
||||
--ink-muted: #46606b;
|
||||
--ink-faint: #5f747d;
|
||||
--heading: #08222d;
|
||||
--accent: #0369a1;
|
||||
--accent-soft: #dcecf7;
|
||||
--on-accent: #ffffff;
|
||||
--signal: #16a34a;
|
||||
--ok: #15803d;
|
||||
--ok-soft: #dcf3e4;
|
||||
--warn: #8f5600;
|
||||
--warn-soft: #fbefd0;
|
||||
--danger: #c01f2f;
|
||||
--danger-soft: #fbe4e6;
|
||||
--info: #1d62c9;
|
||||
--info-soft: #e1ecfb;
|
||||
--viz-1: #1f6feb;
|
||||
--viz-2: #1a7f37;
|
||||
--viz-3: #9a6700;
|
||||
--viz-4: #cf222e;
|
||||
--viz-5: #8250df;
|
||||
--viz-6: #1b7c83;
|
||||
--viz-7: #bc4c00;
|
||||
--viz-8: #6b7f8e;
|
||||
--shadow: 0 1px 2px rgba(15, 31, 38, .08), 0 8px 24px rgba(15, 31, 38, .07);
|
||||
--scrim: rgba(15, 31, 38, .45);
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root:not([data-theme="dark"]) {
|
||||
--bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13);
|
||||
--text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05);
|
||||
--shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light;
|
||||
:root:not([data-theme]) {
|
||||
--surface-base: #eff3f7; --surface-sunken: #e2eaf0; --surface-panel: #ffffff; --surface-raised: #f4f7fa; --surface-overlay: #ffffff;
|
||||
--line: #d6e0e7; --line-strong: #aebfcb; --ink: #0f1f26; --ink-muted: #46606b; --ink-faint: #5f747d; --heading: #08222d;
|
||||
--accent: #0369a1; --accent-soft: #dcecf7; --on-accent: #ffffff; --signal: #16a34a;
|
||||
--ok: #15803d; --ok-soft: #dcf3e4; --warn: #8f5600; --warn-soft: #fbefd0; --danger: #c01f2f; --danger-soft: #fbe4e6; --info: #1d62c9; --info-soft: #e1ecfb;
|
||||
--viz-1: #1f6feb; --viz-2: #1a7f37; --viz-3: #9a6700; --viz-4: #cf222e; --viz-5: #8250df; --viz-6: #1b7c83; --viz-7: #bc4c00; --viz-8: #6b7f8e;
|
||||
--shadow: 0 1px 2px rgba(15, 31, 38, .08), 0 8px 24px rgba(15, 31, 38, .07); --scrim: rgba(15, 31, 38, .45);
|
||||
color-scheme: light;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- base */
|
||||
* { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; min-height: 100%; background: var(--bg-2); }
|
||||
html { -webkit-text-size-adjust: 100%; font-size: 16px; background: var(--surface-base); }
|
||||
body {
|
||||
margin: 0; min-height: 100vh; color: var(--text); font: 14px/1.45 "Inter", "Segoe UI", system-ui, -apple-system, sans-serif;
|
||||
background: radial-gradient(1100px 500px at 15% 0, color-mix(in srgb, var(--accent) 14%, transparent), transparent 60%) no-repeat,
|
||||
linear-gradient(180deg, var(--bg), var(--bg-2));
|
||||
overflow-x: hidden;
|
||||
margin: 0; min-height: 100vh; background: var(--surface-base); color: var(--ink);
|
||||
font: 400 .9375rem/1.5 var(--font-sans); overflow-x: hidden;
|
||||
}
|
||||
a { color: var(--accent); }
|
||||
a { color: var(--accent); text-underline-offset: 2px; }
|
||||
button, select, input { font: inherit; color: inherit; }
|
||||
.wrap { max-width: 1280px; margin: 0 auto; padding: 16px; }
|
||||
header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding-bottom: 14px; }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-right: auto; min-width: 0; }
|
||||
.brand img { width: 44px; height: 44px; border-radius: 12px; flex: none; }
|
||||
.brand h1 { font-size: 20px; margin: 0; letter-spacing: .02em; }
|
||||
.brand small { display: block; color: var(--muted); font-size: 12px; max-width: 46ch; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.btn, select, .seg button, input[type="text"], input[type="number"], input[type="password"] {
|
||||
background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 7px 12px; min-height: 36px;
|
||||
h1, h2, h3, p, dl, dd, ul { margin: 0; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
|
||||
[hidden] { display: none !important; }
|
||||
.mono { font-family: var(--font-mono); font-size: .875rem; }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
.skip { position: absolute; left: -999px; top: 8px; background: var(--accent); color: var(--on-accent); padding: 8px 12px; border-radius: var(--radius-sm); z-index: 100; }
|
||||
.skip:focus { left: 8px; }
|
||||
|
||||
/* ---------------------------------------------------------------- controls */
|
||||
.btn, select, input[type="text"], input[type="number"], input[type="password"], input[type="search"] {
|
||||
background: var(--surface-raised); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 6px 12px; min-height: 36px;
|
||||
}
|
||||
.btn, .seg button { cursor: pointer; }
|
||||
.btn:hover, .seg button:hover { border-color: var(--accent); }
|
||||
.btn.primary { background: var(--accent); color: #04121c; border-color: transparent; font-weight: 600; }
|
||||
.seg { display: inline-flex; border-radius: 10px; overflow: hidden; border: 1px solid var(--line); }
|
||||
.seg button { border: 0; border-radius: 0; background: transparent; }
|
||||
.seg button[aria-pressed="true"] { background: var(--accent); color: #04121c; font-weight: 600; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.live { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--sev-info); display: inline-block; flex: none; }
|
||||
.dot.on { background: var(--sev-low); box-shadow: 0 0 8px var(--sev-low); }
|
||||
.dot.off { background: var(--sev-critical); }
|
||||
.grid { display: grid; gap: 14px; }
|
||||
.kpis { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); margin-bottom: 14px; }
|
||||
.panel {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px;
|
||||
box-shadow: var(--shadow); backdrop-filter: blur(10px); min-width: 0;
|
||||
.btn { cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; color: var(--ink); white-space: nowrap; }
|
||||
.btn:hover:not(:disabled), select:hover { border-color: var(--line-strong); background: var(--surface-overlay); }
|
||||
.btn:disabled { opacity: .45; cursor: default; }
|
||||
.btn.primary { background: var(--accent); color: var(--on-accent); border-color: transparent; font-weight: 600; }
|
||||
.btn.primary:hover:not(:disabled) { background: var(--accent); filter: brightness(1.08); }
|
||||
.btn.icon { width: 36px; padding: 0; }
|
||||
.btn svg { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: var(--radius-sm); overflow: hidden; background: var(--surface-raised); }
|
||||
.seg button { background: transparent; border: 0; padding: 6px 14px; min-height: 34px; cursor: pointer; color: var(--ink-muted); font-weight: 500; }
|
||||
.seg button + button { border-left: 1px solid var(--line); }
|
||||
.seg button:hover { color: var(--ink); background: var(--surface-overlay); }
|
||||
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--on-accent); font-weight: 600; }
|
||||
.check { display: inline-flex; align-items: center; gap: 8px; color: var(--ink-muted); min-height: 36px; }
|
||||
.check input { width: 16px; height: 16px; accent-color: var(--accent); }
|
||||
.linkish { color: var(--accent); cursor: pointer; background: none; border: 0; padding: 0; text-decoration: underline; text-underline-offset: 2px; text-align: left; }
|
||||
|
||||
/* ---------------------------------------------------------------- shell */
|
||||
.app { display: grid; grid-template-columns: var(--rail-w) minmax(0, 1fr); min-height: 100vh; background: linear-gradient(to right, var(--rail) calc(var(--rail-w) - 1px), var(--rail-line) calc(var(--rail-w) - 1px), var(--rail-line) var(--rail-w), transparent var(--rail-w)); }
|
||||
.rail {
|
||||
position: sticky; top: 0; height: 100vh; background: var(--rail); border-right: 1px solid var(--rail-line);
|
||||
display: flex; flex-direction: column; padding: var(--s-4) var(--s-3); gap: var(--s-4); overflow-y: auto;
|
||||
}
|
||||
.panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 10px; font-weight: 600; }
|
||||
.kpi .v { font-size: 28px; font-weight: 700; line-height: 1.1; font-variant-numeric: tabular-nums; }
|
||||
.kpi .l { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
||||
.kpi.hot .v { color: var(--sev-critical); }
|
||||
.kpi.warn .v { color: var(--sev-high); }
|
||||
.cols-2 { grid-template-columns: 1fr 1fr; }
|
||||
.cols-3 { grid-template-columns: repeat(3, 1fr); }
|
||||
.cols-main { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
|
||||
.mt { margin-top: 14px; }
|
||||
.rail-brand { display: flex; align-items: center; gap: var(--s-3); padding: 4px var(--s-2); color: var(--rail-ink); text-decoration: none; }
|
||||
.rail-brand img, .top-brand img { width: 36px; height: 36px; border-radius: 9px; flex: none; }
|
||||
.brand-name { font: 700 1.25rem/1 var(--font-display); letter-spacing: .02em; color: #f2f8fa; }
|
||||
.nav { display: flex; flex-direction: column; gap: 2px; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: var(--s-3); min-height: 40px; padding: 8px var(--s-3); border-radius: var(--radius-sm);
|
||||
color: var(--rail-ink); text-decoration: none; font-weight: 500; border-left: 3px solid transparent;
|
||||
}
|
||||
.nav-item:hover { background: var(--rail-line); }
|
||||
.nav-item[aria-current="page"] { background: var(--rail-active); color: #fff; border-left-color: var(--accent); }
|
||||
.nav-ico { width: 20px; height: 20px; flex: none; display: inline-flex; }
|
||||
.nav-ico svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.rail-foot { margin-top: auto; padding: var(--s-2); color: var(--rail-ink-muted); font-size: .8125rem; }
|
||||
.main { min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: var(--s-3); padding: var(--s-3) var(--s-6);
|
||||
background: var(--surface-base); border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.top-brand { display: none; }
|
||||
.topbar h1 { font: 700 1.375rem/1.2 var(--font-display); color: var(--heading); margin-right: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.top-actions { display: flex; align-items: center; gap: var(--s-2); flex: none; }
|
||||
.conn { display: inline-flex; align-items: center; gap: 6px; color: var(--ink-muted); font-size: .8125rem; margin-right: var(--s-2); }
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--ink-faint); display: inline-block; flex: none; }
|
||||
.dot.on { background: var(--signal); box-shadow: 0 0 0 3px color-mix(in srgb, var(--signal) 25%, transparent); }
|
||||
.dot.off { background: var(--danger); }
|
||||
.slice { padding: var(--s-3) var(--s-6) 0; display: flex; flex-direction: column; gap: var(--s-2); }
|
||||
.slice-ctl { display: flex; flex-wrap: wrap; gap: var(--s-2); align-items: center; }
|
||||
.slice-ctl select { max-width: 100%; }
|
||||
.slice-txt { color: var(--ink-muted); font-size: .875rem; }
|
||||
.slice-txt strong { color: var(--ink); font-weight: 600; }
|
||||
main#view { padding: var(--s-4) var(--s-6) var(--s-6); display: flex; flex-direction: column; gap: var(--s-5); max-width: 1480px; width: 100%; outline: none; }
|
||||
.err-banner { margin: var(--s-3) var(--s-6) 0; background: var(--danger-soft); border: 1px solid var(--danger); color: var(--ink); border-radius: var(--radius-sm); padding: 8px 12px; }
|
||||
.shell-foot { margin-top: auto; padding: var(--s-5) var(--s-6) var(--s-6); color: var(--ink-faint); font-size: .8125rem; text-align: center; }
|
||||
.shell-foot div { margin-top: 4px; }
|
||||
|
||||
.tabbar { display: none; }
|
||||
.more-sheet { display: none; }
|
||||
|
||||
/* ---------------------------------------------------------------- primitives */
|
||||
.lead {
|
||||
position: relative; overflow: hidden; border-radius: var(--radius); padding: 22px 26px; color: var(--lead-ink);
|
||||
background: linear-gradient(135deg, var(--lead-bg), var(--lead-bg-2)); border: 1px solid var(--line-strong);
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--s-5); align-items: center;
|
||||
}
|
||||
.lead::after { content: ""; position: absolute; right: -60px; top: -80px; width: 280px; height: 280px; border-radius: 50%; border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent); box-shadow: 0 0 0 44px color-mix(in srgb, var(--accent) 6%, transparent), 0 0 0 88px color-mix(in srgb, var(--accent) 4%, transparent); pointer-events: none; }
|
||||
.lead h2 { font: 700 1.5rem/1.2 var(--font-display); max-width: 44ch; color: var(--lead-ink); position: relative; z-index: 1; overflow-wrap: anywhere; }
|
||||
.lead p { margin-top: 8px; color: var(--lead-ink-muted); max-width: 70ch; position: relative; z-index: 1; overflow-wrap: anywhere; }
|
||||
.lead .pulse { width: 20px; height: 20px; border-radius: 50%; background: var(--signal); box-shadow: 0 0 0 9px color-mix(in srgb, var(--signal) 18%, transparent); position: relative; z-index: 1; }
|
||||
.lead.tone-danger .pulse { background: var(--danger); box-shadow: 0 0 0 9px color-mix(in srgb, var(--danger) 20%, transparent); }
|
||||
.lead.tone-neutral .pulse { background: var(--ink-faint); box-shadow: none; }
|
||||
|
||||
.panel { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); min-width: 0; display: flex; flex-direction: column; }
|
||||
.panel-h { display: flex; align-items: center; gap: var(--s-3); padding: var(--s-3) var(--s-4) 0; flex-wrap: wrap; }
|
||||
.panel-h h2 { font: 700 1rem/1.3 var(--font-display); color: var(--heading); margin-right: auto; }
|
||||
.panel-h .acts { display: flex; gap: var(--s-2); align-items: center; flex-wrap: wrap; }
|
||||
.panel .hint { padding: 2px var(--s-4) 0; color: var(--ink-muted); font-size: .875rem; }
|
||||
.panel-b { padding: var(--s-3) var(--s-4) var(--s-4); min-width: 0; flex: 1; }
|
||||
|
||||
.grid { display: grid; gap: var(--s-4); }
|
||||
.grid.kpis { grid-template-columns: repeat(auto-fit, minmax(176px, 1fr)); }
|
||||
.grid.g2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.grid.g3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.grid.main-side { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
|
||||
.grid > * { min-width: 0; }
|
||||
|
||||
.stat { background: var(--surface-panel); border: 1px solid var(--line); border-top: 3px solid var(--accent); border-radius: 0 0 var(--radius) var(--radius); padding: var(--s-3) var(--s-4) var(--s-4); box-shadow: var(--shadow); min-width: 0; }
|
||||
.stat .l { color: var(--ink-muted); font-size: .875rem; font-weight: 600; }
|
||||
.stat .v { font: 800 1.875rem/1.1 var(--font-display); color: var(--heading); margin-top: 6px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
|
||||
.stat .s { color: var(--ink-faint); font-size: .875rem; margin-top: 4px; }
|
||||
.stat.tone-danger { border-top-color: var(--danger); } .stat.tone-danger .v { color: var(--danger); }
|
||||
.stat.tone-warn { border-top-color: var(--warn); } .stat.tone-warn .v { color: var(--warn); }
|
||||
.stat.tone-ok { border-top-color: var(--ok); } .stat.tone-ok .v { color: var(--ok); }
|
||||
.stat.tone-info { border-top-color: var(--info); } .stat.tone-info .v { color: var(--info); }
|
||||
|
||||
.empty { color: var(--ink-muted); padding: var(--s-4) 0; }
|
||||
.empty strong { display: block; color: var(--ink); font-weight: 600; }
|
||||
.note { color: var(--ink-muted); font-size: .875rem; }
|
||||
|
||||
.badge { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .8125rem; font-weight: 600; border: 1px solid var(--line); white-space: nowrap; background: var(--surface-raised); color: var(--ink-muted); }
|
||||
.badge.tone-danger { background: var(--danger-soft); color: var(--danger); border-color: color-mix(in srgb, var(--danger) 55%, transparent); }
|
||||
.badge.tone-warn { background: var(--warn-soft); color: var(--warn); border-color: color-mix(in srgb, var(--warn) 55%, transparent); }
|
||||
.badge.tone-ok { background: var(--ok-soft); color: var(--ok); border-color: color-mix(in srgb, var(--ok) 55%, transparent); }
|
||||
.badge.tone-info { background: var(--info-soft); color: var(--info); border-color: color-mix(in srgb, var(--info) 55%, transparent); }
|
||||
.chip { display: inline-block; margin: 0 4px 2px 0; padding: 0 7px; border-radius: 6px; background: var(--surface-raised); border: 1px solid var(--line); font-size: .8125rem; white-space: nowrap; }
|
||||
.cat { display: inline-block; padding: 0 8px; border-radius: 6px; font-size: .8125rem; font-weight: 600; color: var(--on-accent); background: var(--ink-faint); white-space: nowrap; }
|
||||
.cat.c-notfound { background: var(--cat-notfound); } .cat.c-scanner { background: var(--cat-scanner); } .cat.c-bruteforce { background: var(--cat-bruteforce); }
|
||||
.cat.c-exploit { background: var(--cat-exploit); } .cat.c-ssh-fail { background: var(--cat-ssh-fail); } .cat.c-ssh-probe { background: var(--cat-ssh-probe); }
|
||||
.cat.c-ban { background: var(--cat-ban); } .cat.c-ssh-ok, .cat.c-ok { background: var(--cat-ok); }
|
||||
.t-banned { color: var(--warn); font-weight: 600; }
|
||||
|
||||
/* bars (top-N lists) */
|
||||
.bar-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 10px; padding: 7px 0; border-top: 1px solid var(--line); }
|
||||
.bar-row:first-child { border-top: 0; padding-top: 0; }
|
||||
.bar-row .k { overflow-wrap: anywhere; }
|
||||
.bar-row .n { color: var(--ink-muted); font-variant-numeric: tabular-nums; }
|
||||
.bar-row .sub { grid-column: 1 / -1; color: var(--ink-muted); font-size: .8125rem; overflow-wrap: anywhere; }
|
||||
.bar-row .bar { grid-column: 1 / -1; height: 4px; border-radius: 2px; background: var(--surface-raised); overflow: hidden; }
|
||||
.bar-row .bar i { display: block; height: 100%; background: var(--accent); }
|
||||
|
||||
/* charts */
|
||||
.chart-wrap { position: relative; }
|
||||
.chart-wrap svg { width: 100%; height: 230px; display: block; }
|
||||
.chart-wrap .tip {
|
||||
position: absolute; pointer-events: none; background: var(--bg-2); border: 1px solid var(--line); border-radius: 10px;
|
||||
padding: 8px 10px; font-size: 12px; z-index: 5; min-width: 130px; box-shadow: var(--shadow);
|
||||
}
|
||||
.tip[hidden] { display: none; }
|
||||
.chart-wrap svg { width: 100%; height: auto; display: block; }
|
||||
.tip { position: absolute; pointer-events: none; background: var(--surface-overlay); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); padding: 8px 10px; font-size: .8125rem; z-index: 5; min-width: 140px; box-shadow: var(--shadow); }
|
||||
.tip div { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.axis { fill: var(--muted); font-size: 10px; }
|
||||
.axis { fill: var(--ink-faint); font-size: 11px; font-family: var(--font-sans); }
|
||||
.gridline { stroke: var(--line); stroke-width: 1; }
|
||||
.hover-col { fill: transparent; }
|
||||
.hover-col:hover { fill: color-mix(in srgb, var(--text) 8%, transparent); }
|
||||
.b-notfound { fill: var(--sev-info); } .b-scanner { fill: var(--sev-medium); } .b-bruteforce { fill: var(--sev-high); }
|
||||
.b-exploit { fill: var(--sev-critical); } .b-ssh-fail { fill: var(--accent); } .b-ssh-probe { fill: var(--c-ssh-probe); }
|
||||
.b-ban { fill: var(--accent-2); }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 8px; }
|
||||
.legend button { background: none; border: 0; padding: 2px 0; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 12px; }
|
||||
.legend button[aria-pressed="false"] { opacity: .4; text-decoration: line-through; }
|
||||
.sw { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
|
||||
.sw.b-notfound { background: var(--sev-info); } .sw.b-scanner { background: var(--sev-medium); } .sw.b-bruteforce { background: var(--sev-high); }
|
||||
.sw.b-exploit { background: var(--sev-critical); } .sw.b-ssh-fail { background: var(--accent); } .sw.b-ssh-probe { background: var(--c-ssh-probe); }
|
||||
.sw.b-ban { background: var(--accent-2); }
|
||||
.hover-col:hover { fill: color-mix(in srgb, var(--ink) 8%, transparent); }
|
||||
.b-notfound { fill: var(--cat-notfound); } .b-scanner { fill: var(--cat-scanner); } .b-bruteforce { fill: var(--cat-bruteforce); }
|
||||
.b-exploit { fill: var(--cat-exploit); } .b-ssh-fail { fill: var(--cat-ssh-fail); } .b-ssh-probe { fill: var(--cat-ssh-probe); } .b-ban { fill: var(--cat-ban); }
|
||||
.b-treq { fill: var(--accent); fill-opacity: .38; } .b-tpages { fill: var(--accent); }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: 4px 14px; margin-top: var(--s-2); }
|
||||
.legend button, .legend span.li { background: none; border: 0; padding: 4px 0; display: inline-flex; align-items: center; gap: 6px; color: var(--ink); font-size: .875rem; }
|
||||
.legend button { cursor: pointer; }
|
||||
.legend button[aria-pressed="false"] { opacity: .45; text-decoration: line-through; }
|
||||
.sw { width: 11px; height: 11px; border-radius: 3px; display: inline-block; background: var(--ink-faint); }
|
||||
.sw.b-notfound { background: var(--cat-notfound); } .sw.b-scanner { background: var(--cat-scanner); } .sw.b-bruteforce { background: var(--cat-bruteforce); }
|
||||
.sw.b-exploit { background: var(--cat-exploit); } .sw.b-ssh-fail { background: var(--cat-ssh-fail); } .sw.b-ssh-probe { background: var(--cat-ssh-probe); } .sw.b-ban { background: var(--cat-ban); }
|
||||
.sw.b-treq { background: color-mix(in srgb, var(--accent) 38%, transparent); } .sw.b-tpages { background: var(--accent); }
|
||||
|
||||
/* map */
|
||||
.mapbox { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 1fr); gap: var(--s-4); align-items: start; }
|
||||
.map svg { width: 100%; height: auto; display: block; }
|
||||
.mapc { fill: var(--surface-raised); stroke: var(--line); stroke-width: .6; }
|
||||
.mapc.hit { fill: var(--danger); }
|
||||
.map.good .mapc.hit { fill: var(--accent); }
|
||||
|
||||
/* tables */
|
||||
.tbl-wrap { overflow-x: auto; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; padding: 6px 8px; white-space: nowrap; }
|
||||
th { text-align: left; font: 600 .75rem/1.2 var(--font-mono); text-transform: uppercase; letter-spacing: .08em; color: var(--ink-muted); padding: 8px 10px; white-space: nowrap; border-bottom: 2px solid var(--line-strong); }
|
||||
th button { background: none; border: 0; padding: 0; cursor: pointer; color: inherit; font: inherit; text-transform: inherit; letter-spacing: inherit; }
|
||||
td { padding: 8px; border-top: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
|
||||
th button:hover { color: var(--ink); }
|
||||
th[aria-sort="ascending"] button::after { content: " \25B2"; font-size: .7em; }
|
||||
th[aria-sort="descending"] button::after { content: " \25BC"; font-size: .7em; }
|
||||
td { padding: 7px 10px; border-top: 1px solid var(--line); vertical-align: middle; overflow-wrap: anywhere; }
|
||||
tr.row { cursor: pointer; }
|
||||
tr.row:hover td, tr.row:focus-visible td { background: var(--field); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
.mono { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 12.5px; }
|
||||
.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; border: 1px solid transparent; white-space: nowrap; }
|
||||
.lv-hostile { background: color-mix(in srgb, var(--sev-critical) 22%, transparent); color: var(--sev-critical); border-color: var(--sev-critical); }
|
||||
.lv-suspicious { background: color-mix(in srgb, var(--sev-medium) 20%, transparent); color: var(--sev-medium); border-color: var(--sev-medium); }
|
||||
.lv-low { background: color-mix(in srgb, var(--sev-low) 16%, transparent); color: var(--sev-low); border-color: var(--sev-low); }
|
||||
.chip { display: inline-block; margin: 0 4px 2px 0; padding: 0 6px; border-radius: 6px; background: var(--field); font-size: 11px; white-space: nowrap; }
|
||||
.banned { color: var(--accent-2); font-weight: 600; }
|
||||
.bar-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 10px; padding: 5px 0; border-top: 1px solid var(--line); }
|
||||
.bar-row:first-of-type { border-top: 0; }
|
||||
.bar-row .k { overflow-wrap: anywhere; }
|
||||
.bar-row .n { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.bar-row .bar { grid-column: 1 / -1; height: 3px; border-radius: 2px; background: var(--field); overflow: hidden; }
|
||||
.bar-row .bar i { display: block; height: 100%; background: var(--accent); }
|
||||
.empty { color: var(--muted); padding: 8px 0; }
|
||||
.feed { list-style: none; margin: 0; padding: 0; max-height: 380px; overflow-y: auto; }
|
||||
.feed li { padding: 6px 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: auto auto minmax(0, 1fr); gap: 2px 8px; align-items: baseline; }
|
||||
.feed li:first-child { border-top: 0; }
|
||||
.feed .t { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.feed .what { grid-column: 1 / -1; color: var(--muted); font-size: 12.5px; overflow-wrap: anywhere; }
|
||||
.feed a, .linkish { color: var(--accent); cursor: pointer; background: none; border: 0; padding: 0; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.cat { display: inline-block; padding: 0 7px; border-radius: 6px; font-size: 11px; font-weight: 600; color: #04121c; }
|
||||
.cat.b-notfound { background: var(--sev-info); color: #fff; } .cat.b-scanner { background: var(--sev-medium); } .cat.b-bruteforce { background: var(--sev-high); }
|
||||
.cat.b-exploit { background: var(--sev-critical); color: #fff; } .cat.b-ssh-fail { background: var(--accent); } .cat.b-ssh-probe { background: var(--c-ssh-probe); }
|
||||
.cat.b-ban { background: var(--accent-2); } .cat.b-ssh-ok { background: var(--sev-low); } .cat.b-ok { background: var(--sev-low); }
|
||||
.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; }
|
||||
.toolbar input[type="text"] { flex: 1 1 140px; min-width: 0; }
|
||||
.toolbar input[type="number"] { width: 84px; }
|
||||
.pager { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 10px; color: var(--muted); font-size: 12px; }
|
||||
.hosts { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }
|
||||
.host { border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; }
|
||||
.host h3 { margin: 0 0 4px; font-size: 14px; display: flex; align-items: center; gap: 8px; }
|
||||
.host .meta { color: var(--muted); font-size: 12px; }
|
||||
.host dl { display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; margin: 8px 0 0; font-size: 12.5px; }
|
||||
.host dd { margin: 0; font-variant-numeric: tabular-nums; text-align: right; }
|
||||
.host dt { color: var(--muted); }
|
||||
.st-following, .st-ok { color: var(--sev-low); } .st-waiting, .st-backfill { color: var(--sev-medium); } .st-error { color: var(--sev-critical); }
|
||||
tr.row:hover td, tr.row:focus-visible td { background: var(--surface-raised); }
|
||||
td.nw, td.nw * { white-space: nowrap; overflow-wrap: normal; }
|
||||
.origin { display: block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
td small { display: block; color: var(--ink-muted); font-size: .8125rem; overflow-wrap: anywhere; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; gap: var(--s-2); align-items: center; margin-bottom: var(--s-3); }
|
||||
.toolbar input[type="text"], .toolbar input[type="search"] { flex: 1 1 180px; min-width: 0; }
|
||||
.toolbar input[type="number"] { width: 90px; }
|
||||
.pager { display: flex; justify-content: space-between; align-items: center; gap: var(--s-2); margin-top: var(--s-3); color: var(--ink-muted); font-size: .875rem; flex-wrap: wrap; }
|
||||
.pager .btns { display: flex; gap: var(--s-2); align-items: center; }
|
||||
|
||||
/* feed */
|
||||
.feed { list-style: none; padding: 0; max-height: 420px; overflow-y: auto; }
|
||||
.feed li { padding: 7px 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: auto auto minmax(0, 1fr); gap: 2px 8px; align-items: baseline; }
|
||||
.feed li:first-child { border-top: 0; padding-top: 0; }
|
||||
.feed .t { color: var(--ink-muted); font-size: .8125rem; font-variant-numeric: tabular-nums; }
|
||||
.feed .what { grid-column: 1 / -1; color: var(--ink-muted); font-size: .875rem; overflow-wrap: anywhere; }
|
||||
.feed li.empty { display: block; }
|
||||
|
||||
/* hosts and sources */
|
||||
.hosts { display: grid; gap: var(--s-3); grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
|
||||
.host { border: 1px solid var(--line); border-radius: var(--radius); padding: var(--s-3) var(--s-4); background: var(--surface-raised); }
|
||||
.host h3 { font: 700 1rem/1.3 var(--font-display); display: flex; align-items: center; gap: 8px; color: var(--heading); overflow-wrap: anywhere; }
|
||||
.host .meta { color: var(--ink-muted); font-size: .875rem; margin-top: 2px; overflow-wrap: anywhere; }
|
||||
.host dl { display: grid; grid-template-columns: 1fr auto; gap: 3px 8px; margin: 10px 0 0; font-size: .875rem; }
|
||||
.host dd { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.host dt { color: var(--ink-muted); }
|
||||
.st-following { color: var(--ok); } .st-waiting, .st-backfill { color: var(--warn); } .st-error { color: var(--danger); } .st-disabled { color: var(--ink-muted); }
|
||||
.kv { display: grid; grid-template-columns: minmax(120px, auto) minmax(0, 1fr); gap: 6px var(--s-4); }
|
||||
.kv dt { color: var(--ink-muted); } .kv dd { overflow-wrap: anywhere; }
|
||||
|
||||
/* drawer */
|
||||
.scrim { position: fixed; inset: 0; background: var(--scrim); z-index: 40; }
|
||||
aside#detail {
|
||||
position: fixed; top: 0; right: 0; bottom: 0; width: min(460px, 100vw); background: var(--bg-2); border-left: 1px solid var(--line);
|
||||
box-shadow: var(--shadow); z-index: 20; padding: 18px 16px; overflow-y: auto; overflow-x: hidden;
|
||||
position: fixed; top: 0; right: 0; bottom: 0; width: min(480px, 100vw); background: var(--surface-panel); border-left: 1px solid var(--line-strong);
|
||||
box-shadow: var(--shadow); z-index: 50; padding: var(--s-4); overflow-y: auto; overflow-x: hidden;
|
||||
}
|
||||
aside#detail[hidden] { display: none; }
|
||||
aside#detail h2 { font-size: 18px; text-transform: none; letter-spacing: 0; color: var(--text); margin: 0; overflow-wrap: anywhere; }
|
||||
aside#detail dl { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 6px 10px; margin: 14px 0; }
|
||||
aside#detail dt { color: var(--muted); }
|
||||
aside#detail dd { margin: 0; overflow-wrap: anywhere; }
|
||||
aside#detail ul { margin: 0; padding-left: 16px; }
|
||||
.scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 15; }
|
||||
.scrim[hidden] { display: none; }
|
||||
footer { color: var(--muted); font-size: 12px; text-align: center; padding: 20px 0 6px; }
|
||||
.err-banner { background: color-mix(in srgb, var(--sev-critical) 18%, transparent); border: 1px solid var(--sev-critical); border-radius: 10px; padding: 8px 12px; margin-bottom: 12px; }
|
||||
.err-banner[hidden] { display: none; }
|
||||
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
|
||||
aside#detail .dh { display: flex; align-items: center; gap: var(--s-2); flex-wrap: wrap; margin-bottom: var(--s-3); }
|
||||
aside#detail h2 { font: 700 1.25rem/1.2 var(--font-mono); color: var(--heading); margin-right: auto; overflow-wrap: anywhere; }
|
||||
aside#detail .kv { margin: var(--s-3) 0; grid-template-columns: 112px minmax(0, 1fr); }
|
||||
aside#detail ul { padding-left: 16px; }
|
||||
aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
|
||||
/* ---------------------------------------------------------------- login */
|
||||
.login { min-height: 100vh; display: grid; place-items: center; padding: var(--s-4); }
|
||||
.login .panel { width: min(400px, 100%); padding: 26px 22px; text-align: center; }
|
||||
.login img { width: 84px; height: 84px; border-radius: 20px; }
|
||||
.login h1 { margin: 10px 0 2px; }
|
||||
.login p { color: var(--muted); margin: 0 0 16px; }
|
||||
.login img { width: 84px; height: 84px; border-radius: 20px; margin: 0 auto; }
|
||||
.login h1 { margin: 10px 0 2px; font: 700 1.5rem/1.2 var(--font-display); color: var(--heading); }
|
||||
.login p { color: var(--ink-muted); margin: 0 0 16px; }
|
||||
.login form { display: grid; gap: 10px; }
|
||||
.login .msg { color: var(--sev-critical); min-height: 1.4em; }
|
||||
.login .controls { justify-content: center; margin-top: 14px; }
|
||||
.login .msg { color: var(--danger); min-height: 1.4em; }
|
||||
.login .controls { display: flex; justify-content: center; gap: var(--s-2); margin-top: 14px; }
|
||||
|
||||
/* ---------------------------------------------------------------- responsive */
|
||||
@media (max-width: 1180px) {
|
||||
.app { --rail-w: 68px; }
|
||||
.rail { padding: var(--s-3) var(--s-2); align-items: center; }
|
||||
.brand-name, .nav-label, .rail-foot { display: none; }
|
||||
.nav-item { justify-content: center; padding: 8px; border-left: 0; width: 44px; }
|
||||
.nav-item[aria-current="page"] { box-shadow: inset 3px 0 0 var(--accent); }
|
||||
.grid.g3 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 960px) {
|
||||
.cols-main, .cols-3 { grid-template-columns: 1fr; }
|
||||
.cols-2 { grid-template-columns: 1fr; }
|
||||
.grid.g2, .grid.g3, .grid.main-side, .mapbox { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.wrap { padding: 12px; }
|
||||
.brand small { display: none; }
|
||||
.kpi .v { font-size: 24px; }
|
||||
.app { display: block; padding-bottom: 68px; }
|
||||
.rail { display: none; }
|
||||
.app { background: none; }
|
||||
.topbar { padding: var(--s-2) var(--s-4); gap: var(--s-2); }
|
||||
.top-brand { display: inline-flex; }
|
||||
.top-brand img { width: 30px; height: 30px; }
|
||||
.topbar h1 { font-size: 1.125rem; }
|
||||
.conn span:not(.dot) { display: none; }
|
||||
.conn { margin-right: 0; }
|
||||
.slice { padding: var(--s-3) var(--s-4) 0; }
|
||||
main#view { padding: var(--s-3) var(--s-4) var(--s-5); gap: var(--s-4); }
|
||||
.err-banner { margin: var(--s-3) var(--s-4) 0; }
|
||||
.shell-foot { padding: var(--s-4); }
|
||||
.lead { padding: 18px; grid-template-columns: 1fr; }
|
||||
.lead .pulse { display: none; }
|
||||
.lead h2 { font-size: 1.25rem; }
|
||||
.grid.kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--s-3); }
|
||||
.stat { padding: var(--s-3); } .stat .v { font-size: 1.5rem; }
|
||||
.tabbar {
|
||||
display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); position: fixed; left: 0; right: 0; bottom: 0; z-index: 30;
|
||||
background: var(--rail); border-top: 1px solid var(--rail-line); padding: 4px 4px max(4px, env(safe-area-inset-bottom));
|
||||
}
|
||||
.tab { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: 56px; border: 0; background: none; color: var(--rail-ink); text-decoration: none; font-size: .75rem; border-radius: var(--radius-sm); cursor: pointer; padding: 4px 2px; }
|
||||
.tab .nav-ico svg { width: 22px; height: 22px; }
|
||||
.tab span:last-child { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab[aria-current="page"], .tab[aria-expanded="true"] { background: var(--rail-active); color: #fff; }
|
||||
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); }
|
||||
.more-sheet:not([hidden]) { display: block; }
|
||||
.more-sheet a { display: flex; align-items: center; gap: var(--s-3); min-height: 48px; padding: 8px var(--s-3); color: var(--ink); text-decoration: none; border-radius: var(--radius-sm); }
|
||||
.more-sheet a[aria-current="page"] { background: var(--accent-soft); }
|
||||
.more-sheet .nav-ico { color: var(--accent); }
|
||||
.tbl-wrap { overflow: visible; }
|
||||
table.stack thead { display: none; }
|
||||
table.stack, table.stack tbody, table.stack tr, table.stack td { display: block; width: 100%; }
|
||||
table.stack tr { border-top: 1px solid var(--line); padding: 8px 0; }
|
||||
table.stack tr:first-child { border-top: 0; }
|
||||
table.stack td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; }
|
||||
table.stack td::before { content: attr(data-label); color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .05em; text-align: left; flex: none; }
|
||||
table.stack td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; }
|
||||
table.stack td > * { min-width: 0; }
|
||||
.chart-wrap svg { height: 190px; }
|
||||
table.stack td.nw, table.stack td.nw * { white-space: normal; }
|
||||
table.stack tr.row { display: grid; grid-template-columns: 1fr 1fr; gap: 2px 12px; padding: 8px 10px; margin: 6px 0; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); }
|
||||
table.stack tr.row td { display: block; text-align: left; min-width: 0; padding: 0; }
|
||||
table.stack tr.row td::before { display: block; margin-bottom: 0; }
|
||||
table.stack tr.row td:first-child { grid-column: 1 / -1; font-weight: 600; }
|
||||
table.stack tr.row td:first-child::before { display: none; }
|
||||
table.stack tr.row td:nth-child(4), table.stack tr.row td:nth-child(5) { grid-column: 1 / -1; }
|
||||
.origin { max-width: none; white-space: normal; }
|
||||
.kv { grid-template-columns: 1fr; gap: 0; }
|
||||
.kv dt { margin-top: 8px; }
|
||||
aside#detail .kv { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
|
||||
#ips td:first-child, #ips td:nth-child(2), #sources td:nth-child(-n+2), #sources td:nth-child(n+4) { white-space: nowrap; overflow-wrap: normal; }
|
||||
@media (max-width: 720px) {
|
||||
#ips td, #sources td { white-space: normal !important; max-width: none !important; }
|
||||
#ips td:first-child { font-weight: 600; }
|
||||
}
|
||||
.tabs { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 14px; }
|
||||
.tabs button[role="tab"] { background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 8px 18px; cursor: pointer; font-weight: 600; }
|
||||
.tabs button[aria-selected="true"] { background: var(--accent); color: #04121c; border-color: transparent; }
|
||||
.tabs select { margin-left: auto; max-width: 100%; }
|
||||
.tabs select[hidden] { display: none; }
|
||||
.mapbox { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 1fr); gap: 14px; align-items: start; }
|
||||
.map svg { width: 100%; height: auto; display: block; }
|
||||
.mapc { fill: var(--field); stroke: var(--line); stroke-width: .6; }
|
||||
.mapc.hit { fill: var(--sev-critical); stroke: var(--line); }
|
||||
.map.good .mapc.hit { fill: var(--accent); }
|
||||
.maplist .bar-row { padding: 4px 0; }
|
||||
.sw.t-req { background: color-mix(in srgb, var(--accent) 38%, transparent); }
|
||||
.sw.t-pages { background: var(--accent); }
|
||||
.b-treq { fill: color-mix(in srgb, var(--accent) 38%, transparent); }
|
||||
.b-tpages { fill: var(--accent); }
|
||||
.bar-row .sub { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
.origin { display: block; }
|
||||
.origin small, td small { display: block; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
footer #attrib { margin-top: 4px; opacity: .8; }
|
||||
@media (max-width: 960px) { .mapbox { grid-template-columns: 1fr; } }
|
||||
|
||||
/* compact IP table: one line per IP on desktop */
|
||||
#ips td { padding: 5px 8px; }
|
||||
#ips .origin { display: block; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#ips td:nth-child(4) { white-space: nowrap; }
|
||||
#ips td:nth-child(4) .chip { margin-bottom: 0; }
|
||||
@media (max-width: 720px) {
|
||||
#ips .origin { max-width: none; white-space: normal; }
|
||||
}
|
||||
@@ -97,6 +97,7 @@ func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
}
|
||||
for i := range s.Hosts {
|
||||
s.Hosts[i].Version, s.Hosts[i].Error = clipS(s.Hosts[i].Version, 32), clipS(s.Hosts[i].Error, 160)
|
||||
s.Hosts[i].Location = sanitizeLocation(s.Hosts[i].Location)
|
||||
}
|
||||
// timeline: the grid is fixed by the range
|
||||
nb := int(rg.Dur.Seconds()) / int(rg.Step)
|
||||
@@ -148,7 +149,7 @@ func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
x.Domains, x.Samples = clipList(x.Domains, maxDomain, 120), clipList(x.Samples, maxSample, 300)
|
||||
x.UAs, x.UALabels = clipList(x.UAs, maxUAs, 200), clipList(x.UALabels, maxUAs, 120)
|
||||
x.Jails = clipList(x.Jails, maxJails, 40)
|
||||
x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), clipS(x.CC, 2), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120)
|
||||
x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), validCC2(clipS(x.CC, 2)), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120)
|
||||
ips = append(ips, x)
|
||||
}
|
||||
s.IPs = ips
|
||||
@@ -169,8 +170,15 @@ func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
r := &s.Recent[i]
|
||||
r.IP, r.Cat, r.Source = clipS(r.IP, 45), clipS(r.Cat, 20), clipS(r.Source, 20)
|
||||
r.Domain, r.Method, r.Path = clipS(r.Domain, 100), clipS(r.Method, 12), clipS(r.Path, 240)
|
||||
r.User, r.Jail, r.CC = clipS(r.User, 64), clipS(r.Jail, 40), clipS(r.CC, 2)
|
||||
r.User, r.Jail = clipS(r.User, 64), clipS(r.Jail, 40)
|
||||
}
|
||||
kept := s.Recent[:0]
|
||||
for _, r := range s.Recent {
|
||||
if SanitizeFeed(&r) {
|
||||
kept = append(kept, r)
|
||||
}
|
||||
}
|
||||
s.Recent = kept
|
||||
if len(s.Sources) > 16 {
|
||||
s.Sources = s.Sources[:16]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// Location is where an instance lives (the destination of its live arcs).
|
||||
type Location struct {
|
||||
Lat float64 `json:"lat"`
|
||||
Lon float64 `json:"lon"`
|
||||
Label string `json:"label,omitempty"`
|
||||
}
|
||||
|
||||
// ParseLocation parses "lat,lon" or "lat,lon,Label" (strict, for configuration).
|
||||
func ParseLocation(s string) (*Location, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil, nil
|
||||
}
|
||||
p := strings.SplitN(s, ",", 3)
|
||||
if len(p) < 2 {
|
||||
return nil, errors.New("location: expected lat,lon or lat,lon,label")
|
||||
}
|
||||
lat, e1 := strconv.ParseFloat(strings.TrimSpace(p[0]), 64)
|
||||
lon, e2 := strconv.ParseFloat(strings.TrimSpace(p[1]), 64)
|
||||
if e1 != nil || e2 != nil || !validLatLon(lat, lon) {
|
||||
return nil, errors.New("location: lat must be within [-90,90] and lon within [-180,180]")
|
||||
}
|
||||
l := &Location{Lat: lat, Lon: lon}
|
||||
if len(p) == 3 {
|
||||
l.Label = strings.TrimSpace(p[2])
|
||||
if utf8.RuneCountInString(l.Label) > 64 || !utf8.ValidString(l.Label) || clipS(l.Label, 1<<20) != l.Label {
|
||||
return nil, errors.New("location: label must have at most 64 characters and no control characters")
|
||||
}
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func validLatLon(lat, lon float64) bool {
|
||||
return !math.IsNaN(lat) && !math.IsNaN(lon) && lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180
|
||||
}
|
||||
|
||||
// sanitizeLocation returns a safe copy or nil (the value may come from a peer).
|
||||
func sanitizeLocation(l *Location) *Location {
|
||||
if l == nil || !validLatLon(l.Lat, l.Lon) {
|
||||
return nil
|
||||
}
|
||||
return &Location{Lat: l.Lat, Lon: l.Lon, Label: clipS(l.Label, 64)}
|
||||
}
|
||||
|
||||
// GeoPoint is where an event came from.
|
||||
type GeoPoint struct {
|
||||
Lat float64 `json:"lat"`
|
||||
Lon float64 `json:"lon"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
City string `json:"city,omitempty"`
|
||||
}
|
||||
|
||||
// LiveEvent is a feed event with the geography of its two ends.
|
||||
type LiveEvent struct {
|
||||
FeedEvent
|
||||
Src *GeoPoint `json:"src,omitempty"`
|
||||
Dst *Location `json:"dst,omitempty"`
|
||||
}
|
||||
|
||||
// Location is the configured location of this instance (nil when unset).
|
||||
func (s *Store) Location() *Location { return sanitizeLocation(s.cfg.Location) }
|
||||
|
||||
// GeoOf resolves the geography of an address or IPv6 /64 key (zero without an enricher).
|
||||
func (s *Store) GeoOf(ip string) core.GeoInfo {
|
||||
if s.enr == nil {
|
||||
return core.GeoInfo{}
|
||||
}
|
||||
if p, err := netip.ParsePrefix(ip); err == nil {
|
||||
ip = p.Addr().String()
|
||||
}
|
||||
if a, err := netip.ParseAddr(ip); err != nil || a.Zone() != "" {
|
||||
return core.GeoInfo{}
|
||||
}
|
||||
return s.enr.Geo(ip)
|
||||
}
|
||||
|
||||
// Live decorates a local feed event with its source geography and this
|
||||
// instance's location.
|
||||
func (s *Store) Live(fe FeedEvent) LiveEvent {
|
||||
le := LiveEvent{FeedEvent: fe, Dst: s.Location()}
|
||||
g := s.GeoOf(fe.IP)
|
||||
if le.CC == "" {
|
||||
le.CC = g.CC
|
||||
}
|
||||
if (g.Lat != 0 || g.Lon != 0) && validLatLon(g.Lat, g.Lon) {
|
||||
le.Src = &GeoPoint{Lat: g.Lat, Lon: g.Lon, CC: g.CC, City: g.City}
|
||||
}
|
||||
return le
|
||||
}
|
||||
|
||||
// LiveRecent returns the newest malicious local events, decorated, newest first.
|
||||
func (s *Store) LiveRecent(n int) []LiveEvent {
|
||||
out := make([]LiveEvent, 0, n)
|
||||
for _, fe := range s.Recent(FeedSize) {
|
||||
if len(out) >= n {
|
||||
break
|
||||
}
|
||||
if core.Category(fe.Cat).IsMalicious() {
|
||||
out = append(out, s.Live(fe))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Sanitize validates an event received from a peer; it returns false when the
|
||||
// event must be dropped. Everything is bounded and stripped of control characters.
|
||||
func (e *LiveEvent) Sanitize(now int64) bool {
|
||||
a, err := netip.ParseAddr(e.IP)
|
||||
if err != nil || a.Zone() != "" {
|
||||
return false
|
||||
}
|
||||
e.IP = a.Unmap().String()
|
||||
if !core.Category(e.Cat).IsMalicious() {
|
||||
return false
|
||||
}
|
||||
if e.T <= 0 || e.T > now+300 || e.T < now-7*24*3600 {
|
||||
e.T = now
|
||||
}
|
||||
e.Source = clipS(e.Source, 20)
|
||||
e.Domain, e.Method, e.Path = clipS(e.Domain, 100), clipS(e.Method, 12), clipS(e.Path, 240)
|
||||
e.User, e.Jail = clipS(e.User, 64), clipS(e.Jail, 40)
|
||||
if e.Status < 0 || e.Status > 999 {
|
||||
e.Status = 0
|
||||
}
|
||||
e.Unban, e.Forged = false, false
|
||||
e.CC = validCC2(clipS(e.CC, 2))
|
||||
if e.Src != nil {
|
||||
if !validLatLon(e.Src.Lat, e.Src.Lon) {
|
||||
e.Src = nil
|
||||
} else {
|
||||
e.Src = &GeoPoint{Lat: e.Src.Lat, Lon: e.Src.Lon, CC: validCC2(clipS(e.Src.CC, 2)), City: clipS(e.Src.City, 80)}
|
||||
}
|
||||
}
|
||||
e.Dst = sanitizeLocation(e.Dst)
|
||||
return true
|
||||
}
|
||||
|
||||
func validCC2(cc string) string {
|
||||
if len(cc) != 2 || cc[0] < 'A' || cc[0] > 'Z' || cc[1] < 'A' || cc[1] > 'Z' {
|
||||
return ""
|
||||
}
|
||||
return cc
|
||||
}
|
||||
|
||||
// String is for debugging.
|
||||
func (l Location) String() string { return fmt.Sprintf("%.4f,%.4f %s", l.Lat, l.Lon, l.Label) }
|
||||
|
||||
// SanitizeFeed validates a feed row that came from a peer's summary; false drops it.
|
||||
func SanitizeFeed(r *FeedEvent) bool {
|
||||
a, err := netip.ParseAddr(r.IP)
|
||||
if err != nil || a.Zone() != "" {
|
||||
return false
|
||||
}
|
||||
r.IP = a.Unmap().String()
|
||||
r.CC = validCC2(clipS(r.CC, 2))
|
||||
r.Unban, r.Forged = false, false
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseLocation(t *testing.T) {
|
||||
l, err := ParseLocation("-8.05, -34.9, Recife, PE")
|
||||
if err != nil || l.Lat != -8.05 || l.Lon != -34.9 || l.Label != "Recife, PE" {
|
||||
t.Fatal(l, err)
|
||||
}
|
||||
if l, err := ParseLocation(""); l != nil || err != nil {
|
||||
t.Fatal("empty is unset")
|
||||
}
|
||||
for _, bad := range []string{"1", "a,b", "91,0", "0,181", "NaN,0", "0,0,x\x01y", "0,0," + strings.Repeat("a", 65)} {
|
||||
if _, err := ParseLocation(bad); err == nil {
|
||||
t.Errorf("%q must be refused", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerLocationAndLiveSanitize(t *testing.T) {
|
||||
e := PeerExport{V: ExportVersion, Summary: Summary{Hosts: []HostInfo{{Name: "x", Location: &Location{Lat: 95, Lon: 0}}}}}
|
||||
if e.Sanitize("24h"); e.Summary.Hosts[0].Location != nil {
|
||||
t.Fatal("invalid location must be dropped")
|
||||
}
|
||||
e = PeerExport{V: ExportVersion, Summary: Summary{Hosts: []HostInfo{{Name: "x", Location: &Location{Lat: 1, Lon: 2, Label: "a\x00" + strings.Repeat("b", 100)}}}}}
|
||||
e.Sanitize("24h")
|
||||
if l := e.Summary.Hosts[0].Location; l == nil || len(l.Label) != 64 || strings.ContainsRune(l.Label, 0) {
|
||||
t.Fatalf("%+v", l)
|
||||
}
|
||||
le := LiveEvent{FeedEvent: FeedEvent{IP: "::ffff:1.2.3.4", Cat: "scanner", T: 1}}
|
||||
if !le.Sanitize(1_800_000_000) || le.IP != "1.2.3.4" || le.T != 1_800_000_000 {
|
||||
t.Fatalf("%+v", le)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerRowsAreSanitized(t *testing.T) {
|
||||
le := LiveEvent{FeedEvent: FeedEvent{IP: "1.2.3.4", Cat: "scanner", T: 1, Forged: true, Unban: true, CC: "<s"}}
|
||||
if !le.Sanitize(1_800_000_000) || le.Forged || le.Unban || le.CC != "" {
|
||||
t.Fatalf("%+v", le)
|
||||
}
|
||||
e := PeerExport{V: ExportVersion, Summary: Summary{
|
||||
Recent: []FeedEvent{{IP: "<script>", Cat: "scanner"}, {IP: "5.6.7.8", Cat: "scanner", CC: "<s", Forged: true}},
|
||||
IPs: []IPSummary{{IP: "9.9.9.9", CC: "<s", Score: 1}},
|
||||
}}
|
||||
if err := e.Sanitize("24h"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := e.Summary.Recent
|
||||
if len(r) != 1 || r[0].IP != "5.6.7.8" || r[0].CC != "" || r[0].Forged {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
if e.Summary.IPs[0].CC != "" {
|
||||
t.Fatal("cc must be validated")
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ type Config struct {
|
||||
// AdminUsers, when not empty, limits the admin immunity to successful SSH
|
||||
// logins of these users (wired to --admin-users / URUTAU_ADMIN_USERS).
|
||||
AdminUsers []string
|
||||
// Location is where this instance lives (--location); nil when unset.
|
||||
Location *Location
|
||||
}
|
||||
|
||||
// AdminWindow is how long a successful SSH login keeps an address immune.
|
||||
|
||||
@@ -107,6 +107,9 @@ type HostInfo struct {
|
||||
HostileIPs int `json:"hostile_ips"`
|
||||
ActiveBans int `json:"active_bans"`
|
||||
LatencyMS int64 `json:"latency_ms,omitempty"`
|
||||
// Live: this instance is streaming events (always true for the local one).
|
||||
Live bool `json:"live"`
|
||||
Location *Location `json:"location,omitempty"`
|
||||
}
|
||||
|
||||
// Summary is the mergeable dashboard payload.
|
||||
@@ -404,7 +407,8 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
return Summary{
|
||||
Version: s.cfg.Version, Host: s.cfg.Name, Range: rg.Name, Generated: nowU,
|
||||
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
|
||||
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans}},
|
||||
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
|
||||
Live: true, Location: s.Location()}},
|
||||
Totals: tot, Timeline: tl, IPs: ips,
|
||||
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
|
||||
Recent: recent, Sources: srcs, Attribution: s.attrib,
|
||||
|
||||
+104
-39
@@ -1,11 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
// Verifies the dashboard translations: both dictionaries (en, pt-BR) must have
|
||||
// exactly the same keys, every key used by the HTML and the JS must exist, and
|
||||
// the HTML must not carry visible text outside a data-i18n element.
|
||||
// Verifies the dashboard translations. The core dictionary (i18n.js) and every
|
||||
// registerI18n({...}) block found in web/*.js must define the same keys in en
|
||||
// and pt-BR; every key used by the HTML and by the scripts (t('...'),
|
||||
// data-i18n*, titleKey) must exist; the HTML must not carry visible text
|
||||
// outside a data-i18n element.
|
||||
//
|
||||
// Usage: node scripts/check-ui-i18n.mjs
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import vm from 'node:vm';
|
||||
@@ -13,42 +15,90 @@ import vm from 'node:vm';
|
||||
const root = join(fileURLToPath(new URL('.', import.meta.url)), '..');
|
||||
const web = join(root, 'internal/server/web');
|
||||
const read = (f) => readFileSync(join(web, f), 'utf8');
|
||||
|
||||
const sandbox = { window: {} };
|
||||
vm.runInNewContext(read('i18n.js'), sandbox);
|
||||
const dict = sandbox.window.URUTAU_I18N;
|
||||
const langs = Object.keys(dict);
|
||||
const errors = [];
|
||||
const LANGS = ['en', 'pt-BR'];
|
||||
|
||||
// duplicate keys silently collapse in an object literal: look at the source
|
||||
for (const lang of langs) {
|
||||
const block = read('i18n.js').split(new RegExp(`\\n\\s*['"]?${lang}['"]?:\\s*\\{`))[1] ?? '';
|
||||
const seen = new Set();
|
||||
for (const m of block.split(/\n\s*\},?\s*\n/)[0].matchAll(/^\s*'([^']+)':/gm)) {
|
||||
if (seen.has(m[1])) errors.push(`duplicate key in ${lang}: ${m[1]}`);
|
||||
seen.add(m[1]);
|
||||
// dictionaries: name -> {source file, en: {}, pt-BR: {}}
|
||||
const dicts = [];
|
||||
|
||||
// the core dictionary
|
||||
const sandbox = { window: {}, document: { documentElement: { setAttribute() {} } }, localStorage: { getItem: () => null }, navigator: { language: 'en' } };
|
||||
vm.runInNewContext(read('i18n.js'), sandbox);
|
||||
dicts.push({ file: 'i18n.js', core: true, data: sandbox.window.URUTAU_I18N });
|
||||
|
||||
// registerI18n({...}) blocks: find the balanced object literal, skipping strings
|
||||
function balanced(src, start) {
|
||||
let depth = 0, q = null;
|
||||
for (let i = start; i < src.length; i++) {
|
||||
const c = src[i];
|
||||
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
|
||||
if (c === "'" || c === '"' || c === '`') { q = c; continue; }
|
||||
if (c === '/' && src[i + 1] === '/') { while (i < src.length && src[i] !== '\n') i++; continue; }
|
||||
if (c === '/' && src[i + 1] === '*') { i = src.indexOf('*/', i + 2) + 1; continue; }
|
||||
if (c === '{') depth++;
|
||||
else if (c === '}' && --depth === 0) return src.slice(start, i + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const jsFiles = readdirSync(web).filter((f) => f.endsWith('.js') && f !== 'world.js');
|
||||
// comments may mention registerI18n({...}) or t('...') as documentation
|
||||
const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/^\s*\/\/.*$/gm, '');
|
||||
for (const f of jsFiles) {
|
||||
const src = stripComments(read(f));
|
||||
if (f === 'i18n.js') continue;
|
||||
for (const m of src.matchAll(/registerI18n\s*\(\s*(?=\{)/g)) {
|
||||
const lit = balanced(src, m.index + m[0].length);
|
||||
if (!lit) { errors.push(`${f}: unbalanced registerI18n literal`); continue; }
|
||||
try {
|
||||
const data = vm.runInNewContext('(' + lit + ')', {});
|
||||
dicts.push({ file: f, core: false, data, literal: lit });
|
||||
} catch (e) { errors.push(`${f}: registerI18n literal is not static data (${e.message})`); }
|
||||
}
|
||||
}
|
||||
|
||||
const all = new Set(langs.flatMap((l) => Object.keys(dict[l])));
|
||||
for (const lang of langs) {
|
||||
for (const k of all) if (!(k in dict[lang])) errors.push(`missing in ${lang}: ${k}`);
|
||||
for (const [k, v] of Object.entries(dict[lang])) if (typeof v !== 'string' || !v.trim()) errors.push(`empty in ${lang}: ${k}`);
|
||||
}
|
||||
// placeholders must match across languages
|
||||
for (const k of all) {
|
||||
const ph = langs.map((l) => (dict[l][k]?.match(/\{n\}/g) ?? []).length);
|
||||
if (new Set(ph).size > 1) errors.push(`placeholder mismatch: ${k}`);
|
||||
const defined = new Map(); // key -> files
|
||||
const ph = (s) => [...new Set((s.match(/\{(\w+)\}/g) ?? []))].sort().join(',');
|
||||
for (const d of dicts) {
|
||||
for (const lang of LANGS) if (!d.data[lang]) errors.push(`${d.file}: missing language ${lang}`);
|
||||
const keys = new Set(LANGS.flatMap((l) => Object.keys(d.data[l] ?? {})));
|
||||
for (const k of keys) {
|
||||
if (!defined.has(k)) defined.set(k, []);
|
||||
defined.get(k).push(d.file);
|
||||
for (const lang of LANGS) {
|
||||
const v = d.data[lang]?.[k];
|
||||
if (v === undefined) errors.push(`${d.file}: missing in ${lang}: ${k}`);
|
||||
else if (typeof v !== 'string' || !v.trim()) errors.push(`${d.file}: empty in ${lang}: ${k}`);
|
||||
}
|
||||
if (new Set(LANGS.map((l) => ph(d.data[l]?.[k] ?? ''))).size > 1) errors.push(`${d.file}: placeholder mismatch: ${k}`);
|
||||
}
|
||||
// duplicate keys silently collapse in an object literal: look at the source
|
||||
const text = d.core ? read(d.file) : d.literal;
|
||||
for (const lang of LANGS) {
|
||||
const block = text.split(new RegExp(`\\n\\s*['"]?${lang}['"]?:\\s*\\{`))[1] ?? '';
|
||||
const seen = new Set();
|
||||
for (const m of block.split(/\n\s*\},?\s*(?:\n|$)/)[0].matchAll(/^\s*['"]([^'"]+)['"]:/gm)) {
|
||||
if (seen.has(m[1])) errors.push(`${d.file}: duplicate key in ${lang}: ${m[1]}`);
|
||||
seen.add(m[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [k, files] of defined) if (files.length > 1) errors.push(`key defined in more than one file: ${k} (${files.join(', ')})`);
|
||||
|
||||
// keys used
|
||||
const used = new Set();
|
||||
for (const f of ['index.html', 'login.html']) {
|
||||
for (const m of read(f).matchAll(/data-i18n(?:-ph|-aria|-title)?="([^"]+)"/g)) used.add(m[1]);
|
||||
}
|
||||
for (const f of ['app.js', 'login.js']) {
|
||||
for (const m of read(f).matchAll(/\bt\(\s*'([^']+)'/g)) used.add(m[1]);
|
||||
for (const m of read(f).matchAll(/\[\s*'((?:host|kpi)\.[a-z]+)'\s*,/g)) used.add(m[1]);
|
||||
const used = new Map(); // key -> file
|
||||
const literals = new Set();
|
||||
const use = (k, f) => { if (!used.has(k)) used.set(k, f); };
|
||||
const htmlFiles = readdirSync(web).filter((f) => f.endsWith('.html'));
|
||||
for (const f of htmlFiles) for (const m of read(f).matchAll(/data-i18n(?:-ph|-aria|-title)?="([^"]+)"/g)) use(m[1], f);
|
||||
for (const f of jsFiles) {
|
||||
if (f === 'i18n.js') continue;
|
||||
let src = stripComments(read(f));
|
||||
// do not treat the dictionaries themselves as usage
|
||||
for (const d of dicts) if (d.file === f && d.literal) src = src.replace(d.literal, '');
|
||||
for (const m of src.matchAll(/\bt\(\s*'([^']+)'/g)) use(m[1], f);
|
||||
for (const m of src.matchAll(/\bpl\(\s*'([^']+)'/g)) { use(m[1] + '.one', f); use(m[1] + '.other', f); }
|
||||
for (const m of src.matchAll(/\b(?:titleKey|labelKey)\s*:\s*'([^']+)'/g)) use(m[1], f);
|
||||
for (const m of src.matchAll(/'([A-Za-z][A-Za-z0-9-]*(?:\.[A-Za-z0-9-]+)*\.?)'/g)) literals.add(m[1]);
|
||||
}
|
||||
// keys built at runtime
|
||||
const families = {
|
||||
@@ -56,28 +106,43 @@ const families = {
|
||||
'level.': ['all', 'hostile', 'suspicious', 'low'],
|
||||
'device.': ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown'],
|
||||
'state.': ['following', 'waiting', 'backfill', 'error', 'disabled'],
|
||||
'range.long.': ['1h', '24h', '7d'],
|
||||
'blocklist.family.': ['all', '4', '6'],
|
||||
};
|
||||
for (const [p, names] of Object.entries(families)) for (const n of names) used.add(p + n);
|
||||
for (const k of used) if (!k.endsWith('.') && !all.has(k)) errors.push(`used but not defined: ${k}`);
|
||||
for (const k of all) if (!used.has(k) && !k.startsWith('ago.') && !['live.on', 'live.off', 'feed.unban', 'yes', 'never', 'blocklist.copied', 'blocklist.failed', 'pager.count'].includes(k)) {
|
||||
errors.push(`defined but unused: ${k}`);
|
||||
for (const [p, names] of Object.entries(families)) for (const n of names) use(p + n, 'runtime');
|
||||
for (const [k, f] of used) if (!k.endsWith('.') && !defined.has(k)) errors.push(`${f}: used but not defined: ${k}`);
|
||||
const exempt = ['live.on', 'live.off', 'feed.unban', 'yes', 'never', 'blocklist.copied', 'blocklist.failed', 'pager.count', 'ov.lead.hostile.one', 'ov.lead.hostile'];
|
||||
for (const [k, files] of defined) {
|
||||
// keys a script registers itself may be built dynamically, so only the core dictionary is checked for dead keys
|
||||
if (!files.includes('i18n.js')) continue;
|
||||
const byLiteral = literals.has(k) || [...literals].some((l) => l.endsWith('.') && k.startsWith(l));
|
||||
if (!used.has(k) && !byLiteral && !k.startsWith('ago.') && !exempt.includes(k)) errors.push(`defined but unused: ${k}`);
|
||||
}
|
||||
|
||||
// no visible text outside data-i18n in the HTML
|
||||
for (const f of ['index.html', 'login.html']) {
|
||||
for (const f of htmlFiles) {
|
||||
const html = read(f).replace(/<script[\s\S]*?<\/script>/g, '').replace(/<!--[\s\S]*?-->/g, '').replace(/<title>[\s\S]*?<\/title>/g, '');
|
||||
for (const m of html.matchAll(/<([a-z0-9]+)([^>]*)>([^<]+)</gi)) {
|
||||
const text = m[3].replace(/&[a-z#0-9]+;/g, '').trim();
|
||||
if (!/[A-Za-zÀ-ÿ]{2,}/.test(text)) continue;
|
||||
if (/data-i18n="/.test(m[2])) continue;
|
||||
if (['h1', 'button'].includes(m[1]) && /^(Urutau|EN|PT)$/.test(text)) continue;
|
||||
if (/^(Urutau|EN|PT)$/.test(text)) continue; // brand name and the language toggle label
|
||||
if (m[1] === 'span' && /id="(ver|live-text)"/.test(m[2])) continue;
|
||||
errors.push(`${f}: hard-coded text <${m[1]}>${text}`);
|
||||
}
|
||||
// CSP: no inline style or event handler attributes
|
||||
if (/\sstyle\s*=/.test(html)) errors.push(`${f}: inline style attribute (blocked by the CSP)`);
|
||||
if (/\son[a-z]+\s*=/.test(html)) errors.push(`${f}: inline event handler (blocked by the CSP)`);
|
||||
}
|
||||
// scripts must never write markup
|
||||
for (const f of jsFiles) {
|
||||
if (f === 'world.js') continue;
|
||||
if (/\.(innerHTML|outerHTML)\s*=|insertAdjacentHTML|document\.write/.test(read(f))) errors.push(`${f}: writes markup (innerHTML/outerHTML/insertAdjacentHTML/document.write)`);
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
console.error('UI i18n problems:\n ' + errors.join('\n '));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`ui i18n ok: ${all.size} keys in ${langs.join(', ')}`);
|
||||
const total = defined.size;
|
||||
console.log(`ui i18n ok: ${total} keys in ${LANGS.join(', ')} (${dicts.length} dictionar${dicts.length === 1 ? 'y' : 'ies'}, ${jsFiles.length} scripts)`);
|
||||
Reference in new issue
Block a user