diff --git a/CHANGELOG.md b/CHANGELOG.md index fad7282..fe4704b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ 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. +- Static files are served from the embedded directory by a strict name pattern. + ## [1.0.0] - 2026-11-14 First release. diff --git a/CHANGELOG.pt-BR.md b/CHANGELOG.pt-BR.md index 6a93302..64a8396 100644 --- a/CHANGELOG.pt-BR.md +++ b/CHANGELOG.pt-BR.md @@ -6,6 +6,18 @@ 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. +- 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. diff --git a/SECURITY.md b/SECURITY.md index 30f51c8..6e5129a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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_` 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_` 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, 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). 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. diff --git a/SECURITY.pt-BR.md b/SECURITY.pt-BR.md index 86da597..cb3d7af 100644 --- a/SECURITY.pt-BR.md +++ b/SECURITY.pt-BR.md @@ -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_` 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_` 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, 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). 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. diff --git a/docs/cli.md b/docs/cli.md index e87c4df..bf468dc 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -32,7 +32,8 @@ 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_` | | `--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 | +| `--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 | diff --git a/docs/configuration.md b/docs/configuration.md index c1e74b9..e120127 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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_` and `...__FILE` | The client credential a hub sends to that one peer; it must equal the peer's own `URUTAU_PEER_TOKEN`. `` 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,8 @@ 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` | `/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_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 | diff --git a/docs/docker.md b/docs/docker.md index e856f5d..c56e331 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -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 diff --git a/docs/interface.md b/docs/interface.md index 8f020ce..e74c361 100644 --- a/docs/interface.md +++ b/docs/interface.md @@ -43,6 +43,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 +53,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 `. The peer token is accepted only by `/api/v1/peer/export`; every other route answers 403 to it. +API clients send `Authorization: Bearer `. The peer token is accepted only by `/api/v1/peer/export` and `/api/v1/peer/stream`; every other route answers 403 to it. diff --git a/docs/pt-BR/cli.md b/docs/pt-BR/cli.md index 357fc92..71ca1c1 100644 --- a/docs/pt-BR/cli.md +++ b/docs/pt-BR/cli.md @@ -32,7 +32,8 @@ 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_` | | `--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 | +| `--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 | diff --git a/docs/pt-BR/configuracao.md b/docs/pt-BR/configuracao.md index 7b4cc5b..b9b3873 100644 --- a/docs/pt-BR/configuracao.md +++ b/docs/pt-BR/configuracao.md @@ -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_` e `...__FILE` | A credencial de cliente que um hub envia àquele peer; deve ser igual ao `URUTAU_PEER_TOKEN` do próprio peer. `` é 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,8 @@ 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` | `/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_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 | diff --git a/docs/pt-BR/docker.md b/docs/pt-BR/docker.md index 27dba6f..f4c1849 100644 --- a/docs/pt-BR/docker.md +++ b/docs/pt-BR/docker.md @@ -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 diff --git a/docs/pt-BR/interface.md b/docs/pt-BR/interface.md index e80c91e..2759b0c 100644 --- a/docs/pt-BR/interface.md +++ b/docs/pt-BR/interface.md @@ -43,6 +43,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 +53,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 `. 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 `. O token de peer só é aceito por `/api/v1/peer/export` e `/api/v1/peer/stream`; todas as outras rotas respondem 403 a ele. diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 1bf4715..c967079 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -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) + } + } +} diff --git a/internal/app/config.go b/internal/app/config.go index 324c70a..efd9985 100644 --- a/internal/app/config.go +++ b/internal/app/config.go @@ -14,6 +14,7 @@ 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`. @@ -36,6 +37,7 @@ type Config struct { GeoUpdate time.Duration Peers []string PeerToken string + Location string // "lat,lon" or "lat,lon,label" (--location) 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 @@ -115,6 +117,7 @@ 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.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 +171,9 @@ 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 + } var peers []fed.Peer seen := map[string]bool{} envSeen := map[string]string{} diff --git a/internal/app/serve.go b/internal/app/serve.go index 6a033c5..88cac71 100644 --- a/internal/app/serve.go +++ b/internal/app/serve.go @@ -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) diff --git a/internal/app/version.go b/internal/app/version.go index fe78227..885886f 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -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" diff --git a/internal/fed/fed.go b/internal/fed/fed.go index e532961..a6bdf35 100644 --- a/internal/fed/fed.go +++ b/internal/fed/fed.go @@ -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,10 @@ type Hub struct { Token string Interval time.Duration client *http.Client + stream *http.Client // long-lived SSE: no overall timeout, no redirects + + lmu sync.Mutex + live liveState mu sync.RWMutex state map[string]*peerState @@ -78,6 +83,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 +194,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 +215,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) } diff --git a/internal/fed/live.go b/internal/fed/live.go new file mode 100644 index 0000000..7757c7f --- /dev/null +++ b/internal/fed/live.go @@ -0,0 +1,190 @@ +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 + liveBackoff0 = time.Second + liveBackoffTo = 60 * 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 { + go 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) + 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) + 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 = "" + } + } +} diff --git a/internal/fed/live_test.go b/internal/fed/live_test.go new file mode 100644 index 0000000..74ddee2 --- /dev/null +++ b/internal/fed/live_test.go @@ -0,0 +1,155 @@ +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":" -
-
-
- Urutau -

Urutau

-
-
- - -
- - - + +
+ + +
+
+ Urutau +

+
+ + + +
- - -
-
-
+ - - - - -
- -
- -

- -
-

-
-
-
- -
-

-
-
- -
-
-

-
- - - -
- - - - - - - - - - - -
-
- - +
+
+
+ + + +
+ +
+

-
-

-
    -
    -
    -
    -

    -

    -

    -
    + -
    -

    -
    -

    -

    -
    - - - -
    -
    -
    -
    +
    -
    +
    +
    - - -
    -

    -
    -

    - - - - - - -
    -
    - -
    + + - + - + + diff --git a/internal/server/web/live.css b/internal/server/web/live.css new file mode 100644 index 0000000..f6654e4 --- /dev/null +++ b/internal/server/web/live.css @@ -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; } +} diff --git a/internal/server/web/live.js b/internal/server/web/live.js new file mode 100644 index 0000000..0a90345 --- /dev/null +++ b/internal/server/web/live.js @@ -0,0 +1,1195 @@ +/* Urutau - AO VIVO page: attacks arriving at the monitored servers, drawn as + animated arcs on a flat map or a 3D globe (canvas 2D, no libraries). + Every string coming from logs is written with textContent / fillText only, + and CSS classes come from a whitelist of known categories. */ +(function () { + 'use strict'; + + // category -> design token (same palette as the rest of the dashboard) + var CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban']; + var TOKEN = { notfound: '--cat-notfound', scanner: '--cat-scanner', bruteforce: '--cat-bruteforce', exploit: '--cat-exploit', 'ssh-fail': '--cat-ssh-fail', 'ssh-probe': '--cat-ssh-probe', ban: '--cat-ban' }; + var FALLBACK = { notfound: '#64748b', scanner: '#f59e0b', bruteforce: '#f97316', exploit: '#ef4444', 'ssh-fail': '#38bdf8', 'ssh-probe': '#a5b4fc', ban: '#f0b35b' }; + var HOSTILE = { exploit: 1, ban: 1 }; + var CAT_OK = {}; + CATS.forEach(function (c) { CAT_OK[c] = 1; }); + + var MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 6000, RING_TRIM = 1000; + var WORLD_W = 2000, WORLD_H = 789, LAT_TOP = 84, LAT_BOT = -58; + var DEFAULT_DST = { lat: -23.55, lon: -46.63 }; + var RAD = Math.PI / 180, TAU = Math.PI * 2; + var HOST_COLORS = ['#38bdf8', '#f0b35b', '#10b981', '#a5b4fc', '#f97316']; + + var inst = null; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + U.registerI18n({ + en: { + 'live.title': 'Live', + 'live.mode': 'View', + 'live.mode.flat': 'Flat map', + 'live.mode.globe': 'Globe', + 'live.pause': 'Pause animation', + 'live.resume': 'Resume animation', + 'live.paused': 'paused', + 'live.fullscreen': 'Presentation mode (full screen)', + 'live.exitfs': 'Leave presentation mode', + 'live.panels': 'Show or hide the panels', + 'live.collapse': 'Collapse panel', + 'live.expand': 'Expand panel', + 'live.rate': 'events / min', + 'live.rate.title': 'Rate', + 'live.cats': 'Categories', + 'live.hosts': 'Servers', + 'live.countries': 'Origins (5 min)', + 'live.recent': 'Latest events', + 'live.empty': 'Waiting for events...', + 'live.more': '+{n} not drawn individually', + 'live.est': 'Destination estimated (server without coordinates)', + 'live.alt': 'Live map of attacks arriving at the servers. The list of latest events is the text alternative.', + 'live.hostile': 'highlighted: exploit and ban · click to filter', + 'live.filtered': 'filter active', + 'live.drag': 'Drag to rotate' + }, + 'pt-BR': { + 'live.title': 'Ao vivo', + 'live.mode': 'Visualização', + 'live.mode.flat': 'Mapa plano', + 'live.mode.globe': 'Globo', + 'live.pause': 'Pausar animação', + 'live.resume': 'Retomar animação', + 'live.paused': 'pausado', + 'live.fullscreen': 'Modo apresentação (tela cheia)', + 'live.exitfs': 'Sair do modo apresentação', + 'live.panels': 'Mostrar ou ocultar os painéis', + 'live.collapse': 'Recolher painel', + 'live.expand': 'Expandir painel', + 'live.rate': 'eventos / min', + 'live.rate.title': 'Ritmo', + 'live.cats': 'Categorias', + 'live.hosts': 'Servidores', + 'live.countries': 'Origens (5 min)', + 'live.recent': 'Últimos eventos', + 'live.empty': 'Aguardando eventos...', + 'live.more': '+{n} sem arco individual', + 'live.est': 'Destino estimado (servidor sem coordenadas)', + 'live.alt': 'Mapa ao vivo dos ataques que chegam aos servidores. A lista dos últimos eventos é a alternativa em texto.', + 'live.hostile': 'destaque: exploit e ban · clique filtra', + 'live.filtered': 'filtro ativo', + 'live.drag': 'Arraste para girar' + } + }); + U.registerPage({ + id: 'live', + icon: '', + titleKey: 'live.title', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Live(U, el, ctx); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); + return true; + } + + // ------------------------------------------------------------------ world geometry (parsed once) + var geo = null; + function worldGeo(world) { + if (geo) return geo; + var rings = [], total = 0; + var re = /([MmLlHhVvZz])|(-?\d*\.?\d+)/g; + Object.keys(world.paths).forEach(function (cc) { + var d = world.paths[cc], m, cmd = '', nums = [], cur = null, x = 0, y = 0; + function flush() { + if (!cmd) return; + var up = cmd.toUpperCase(), rel = cmd !== up, i; + if (up === 'M' || up === 'L') { + for (i = 0; i + 1 < nums.length; i += 2) { + x = rel ? x + nums[i] : nums[i]; y = rel ? y + nums[i + 1] : nums[i + 1]; + if (up === 'M' && i === 0) { cur = [[x, y]]; rings.push(cur); } else if (cur) cur.push([x, y]); + } + } else if (up === 'H') { nums.forEach(function (n) { x = rel ? x + n : n; if (cur) cur.push([x, y]); }); } + else if (up === 'V') { nums.forEach(function (n) { y = rel ? y + n : n; if (cur) cur.push([x, y]); }); } + nums = []; + } + re.lastIndex = 0; + while ((m = re.exec(d))) { + if (m[1]) { flush(); cmd = m[1]; if (cmd === 'z' || cmd === 'Z') cmd = ''; } + else nums.push(parseFloat(m[2])); + } + flush(); + }); + var out = []; + rings.forEach(function (r) { + var pts = [], last = null; + r.forEach(function (p) { + if (last && Math.abs(p[0] - last[0]) + Math.abs(p[1] - last[1]) < 1.1) return; + pts.push(p); last = p; + }); + if (pts.length < 3) return; + var n = pts.length, v = new Float32Array(n * 3), edge = new Uint8Array(n); + for (var i = 0; i < n; i++) { + var lon = pts[i][0] / WORLD_W * 360 - 180, lat = LAT_TOP - pts[i][1] / WORLD_H * (LAT_TOP - LAT_BOT); + var cl = Math.cos(lat * RAD); + v[i * 3] = cl * Math.sin(lon * RAD); v[i * 3 + 1] = Math.sin(lat * RAD); v[i * 3 + 2] = cl * Math.cos(lon * RAD); + var q = pts[(i + n - 1) % n]; + // segments lying on the map border (antimeridian cut) or on the clipped + // southern edge are not borders: they are not stroked on the globe + if ((pts[i][0] < 1.5 && q[0] < 1.5) || (pts[i][0] > WORLD_W - 1.5 && q[0] > WORLD_W - 1.5) || + (pts[i][1] > WORLD_H - 1.5 && q[1] > WORLD_H - 1.5)) edge[i] = 1; + } + out.push({ v: v, edge: edge, n: n }); + total += n; + }); + geo = { rings: out, total: total, scratch: new Float32Array(total * 3) }; + return geo; + } + + // ------------------------------------------------------------------ helpers + function clamp(x, a, b) { return x < a ? a : x > b ? b : x; } + function isNum(x) { return typeof x === 'number' && isFinite(x); } + function validLL(lat, lon) { return isNum(lat) && isNum(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180; } + function vec(lat, lon) { + var cl = Math.cos(lat * RAD); + return [cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD)]; + } + function ease(x) { return x < 0.5 ? 2 * x * x : 1 - 2 * (1 - x) * (1 - x); } + function cc2(s) { return typeof s === 'string' && /^[A-Za-z]{2}$/.test(s) ? s.toUpperCase() : ''; } + function str(s, n) { return typeof s === 'string' ? s.slice(0, n) : ''; } + + var colorProbe = null; + function parseColor(s, fb) { + var m; + if (typeof s !== 'string') s = ''; + s = s.trim(); + try { + if (!colorProbe) colorProbe = document.createElement('canvas').getContext('2d'); + colorProbe.fillStyle = '#000000'; colorProbe.fillStyle = s || fb; s = colorProbe.fillStyle; + } catch (x) { s = fb; } + if ((m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(s))) return [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)]; + if ((m = /rgba?\(\s*(\d+)[ ,]+(\d+)[ ,]+(\d+)/.exec(s))) return [+m[1], +m[2], +m[3]]; + return fb === '#888888' ? [136, 136, 136] : parseColor(fb, '#888888'); + } + function rgba(c, a) { return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')'; } + + // local DOM helper (the shell's Urutau.el takes an attrs object); textContent only + function mk(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text !== undefined && text !== null) e.textContent = text; + return e; + } + + // ------------------------------------------------------------------ the page + function Live(U, root, ctx) { + var self = this; + this.U = U; this.root = root; this.ctx = ctx || {}; + this.alive = true; + this.t = U.t; this.el = mk; this.lang = (ctx && ctx.lang) || ''; + this.world = window.URUTAU_WORLD || U.world || null; + this.geo = this.world ? worldGeo(this.world) : null; + + this.mode = 'flat'; this.target = 0; this.m = 0; + var pref = ''; + try { pref = localStorage.getItem('urutau.live.mode') || ''; } catch (x) { /* storage blocked */ } + if (pref === 'globe' || (!pref && (root.clientWidth || window.innerWidth) < 560)) { this.mode = 'globe'; this.target = 1; this.m = 1; } + this.lon0 = -45; this.lat0 = 16; this.vlon = 0; this.vlat = 0; this.dragging = false; this.idleAt = 0; + this.paused = false; this.hidden = document.hidden; + this.reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches); + this.offCats = {}; this.offHosts = {}; + this.T = 0; this.last = 0; this.raf = 0; this.dirty = true; + this.arcs = []; this.free = []; this.pending = []; this.frameKey = {}; + this.ring = []; this.hostsSeen = {}; this.hostLoc = {}; this.dests = {}; this.destList = []; + this.dots = []; this.more = []; + this.frameAvg = 16; this.quality = 1; + this.W = 0; this.H = 0; this.dpr = 1; this.reserve = 0; + this.flatCache = null; this.cacheKey = ''; + this.listDirty = true; this.hoverList = false; + this.listeners = []; this.timers = []; + this.colors = {}; this.dn = null; this.dnLang = ''; + + this.build(); + this.readTheme(); + this.resize(); + + this.unsub = U.onEvent ? U.onEvent(function (e) { self.ingest(e); }) : null; + this.listen(document, 'visibilitychange', function () { self.onVisibility(); }); + this.listen(document, 'fullscreenchange', function () { self.onFullscreen(); }); + if (window.matchMedia) { + var mq = matchMedia('(prefers-reduced-motion: reduce)'); + var fn = function () { self.reduced = mq.matches; self.dirty = true; self.kick(); }; + if (mq.addEventListener) this.listen(mq, 'change', fn); + } + if (window.ResizeObserver) { + this.ro = new ResizeObserver(function () { self.resize(); }); + this.ro.observe(this.view); this.ro.observe(this.dock); + } else this.listen(window, 'resize', function () { self.resize(); }); + + this.timers.push(setInterval(function () { self.tick(); }, 500)); + this.loadSummary(); + this.timers.push(setInterval(function () { self.loadSummary(); }, 120000)); + this.loadRecent(); + this.kick(); + } + + var P = Live.prototype; + + P.listen = function (target, type, fn, opt) { + target.addEventListener(type, fn, opt); + this.listeners.push([target, type, fn, opt]); + }; + + P.destroy = function () { + this.alive = false; + if (this.raf) cancelAnimationFrame(this.raf); + this.raf = 0; + if (this.unsub) { try { this.unsub(); } catch (x) { /* ignore */ } this.unsub = null; } + this.timers.forEach(clearInterval); this.timers = []; + this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } }); + this.listeners = []; + if (this.ro) { this.ro.disconnect(); this.ro = null; } + if (document.fullscreenElement === this.stage && document.exitFullscreen) { try { document.exitFullscreen(); } catch (x) { /* ignore */ } } + this.arcs = []; this.free = []; this.pending = []; this.ring = []; this.dots = []; this.flatCache = null; + while (this.root.firstChild) this.root.removeChild(this.root.firstChild); + }; + + P.update = function (ctx) { + this.ctx = ctx || this.ctx; + if (this.ctx.lang !== this.lang) { this.lang = this.ctx.lang; this.rebuild(); } + this.readTheme(); + this.listDirty = true; this.dirty = true; + this.tick(true); + this.kick(); + }; + + // language changed: rebuild the DOM keeping filters and the paused/panel state + P.rebuild = function () { + var hosts = Object.keys(this.hostsSeen), self = this, paused = this.paused; + this.hostsSeen = {}; this.hostChips = {}; + if (this.ro) this.ro.disconnect(); + this.listeners = this.listeners.filter(function (l) { + if (l[0] === self.cv) { l[0].removeEventListener(l[1], l[2]); return false; } + return true; + }); + this.build(); + hosts.forEach(function (h) { self.noteHost(h); }); + if (this.ro) { this.ro.observe(this.view); this.ro.observe(this.dock); } + if (paused) this.setPaused(true); + this.dn = null; this.readTheme(); this.filtersChanged(); this.resize(); + }; + + // ------------------------------------------------------------------ DOM + P.icon = function (d) { + var ns = 'http://www.w3.org/2000/svg', s = document.createElementNS(ns, 'svg'); + s.setAttribute('viewBox', '0 0 24 24'); s.setAttribute('aria-hidden', 'true'); s.setAttribute('class', 'lv-ic'); + var p = document.createElementNS(ns, 'path'); p.setAttribute('d', d); s.appendChild(p); + return s; + }; + + P.btn = function (cls, label, svg, onclick) { + var b = document.createElement('button'); + b.type = 'button'; b.className = 'lv-btn ' + cls; + b.setAttribute('aria-label', label); b.title = label; + b.appendChild(this.icon(svg)); + b.addEventListener('click', onclick); + return b; + }; + + P.card = function (cls, titleKey, collapsed) { + var self = this, t = this.t; + var c = this.el('section', 'lv-card ' + cls); + var h = document.createElement('button'); + h.type = 'button'; h.className = 'lv-card-h'; + h.appendChild(this.el('span', 'lv-card-t', t(titleKey))); + h.appendChild(this.icon('M6 9l6 6 6-6')); + var body = this.el('div', 'lv-card-b'); + function set(col) { + c.classList.toggle('lv-collapsed', col); + h.setAttribute('aria-expanded', col ? 'false' : 'true'); + h.setAttribute('aria-label', t(col ? 'live.expand' : 'live.collapse') + ': ' + t(titleKey)); + self.dirty = true; + } + h.addEventListener('click', function () { set(!c.classList.contains('lv-collapsed')); }); + set(!!collapsed); + c.appendChild(h); c.appendChild(body); + c.body = body; + return c; + }; + + P.build = function () { + var self = this, t = this.t, el = this.el, root = this.root; + while (root.firstChild) root.removeChild(root.firstChild); + var narrow = (root.clientWidth || window.innerWidth) < 1300; + + var stage = el('div', 'lv'); this.stage = stage; + var view = el('div', 'lv-view'); this.view = view; + var cv = document.createElement('canvas'); + cv.className = 'lv-cv'; cv.tabIndex = 0; cv.setAttribute('role', 'img'); cv.setAttribute('aria-label', t('live.alt')); + this.cv = cv; this.g = cv.getContext('2d'); + view.appendChild(cv); + + var bar = el('div', 'lv-bar'); + var seg = el('div', 'lv-seg'); seg.setAttribute('role', 'group'); seg.setAttribute('aria-label', t('live.mode')); + this.segFlat = el('button', 'lv-btn', t('live.mode.flat')); this.segGlobe = el('button', 'lv-btn', t('live.mode.globe')); + [['flat', this.segFlat], ['globe', this.segGlobe]].forEach(function (p) { + p[1].type = 'button'; + p[1].addEventListener('click', function () { self.setMode(p[0]); }); + seg.appendChild(p[1]); + }); + bar.appendChild(seg); + this.bPause = this.btn('lv-pause', t('live.pause'), 'M8 5v14M16 5v14', function () { self.setPaused(!self.paused); }); + this.bPause.setAttribute('aria-pressed', 'false'); + this.bPan = this.btn('lv-pan', t('live.panels'), 'M4 6h16M4 12h16M4 18h16', function () { + var off = !self.stage.classList.contains('lv-nodock'); + self.stage.classList.toggle('lv-nodock', off); + self.bPan.setAttribute('aria-pressed', off ? 'false' : 'true'); + self.resize(); + }); + this.bPan.setAttribute('aria-pressed', 'true'); + bar.appendChild(this.bPause); bar.appendChild(this.bPan); + if (document.fullscreenEnabled && stage.requestFullscreen) { + this.bFs = this.btn('lv-fs', t('live.fullscreen'), 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', function () { self.toggleFs(); }); + this.bFs.setAttribute('aria-pressed', 'false'); + bar.appendChild(this.bFs); + } + view.appendChild(bar); + + var note = el('div', 'lv-notes'); + this.nPaused = el('span', 'lv-note', t('live.paused')); this.nPaused.hidden = true; + this.nMore = el('span', 'lv-note', ''); this.nMore.hidden = true; + this.nEst = el('span', 'lv-note', t('live.est')); this.nEst.hidden = true; + this.nFilter = el('span', 'lv-note', t('live.filtered')); this.nFilter.hidden = true; + note.appendChild(this.nPaused); note.appendChild(this.nFilter); note.appendChild(this.nMore); note.appendChild(this.nEst); + view.appendChild(note); + this.hint = el('div', 'lv-hint', t('live.drag')); view.appendChild(this.hint); + stage.appendChild(view); + + var dock = el('div', 'lv-dock'); this.dock = dock; + var cRate = this.card('lv-c-rate', 'live.rate.title', false); + this.rateV = el('div', 'lv-rate-v', '0'); this.rateU = el('div', 'lv-rate-u', t('live.rate')); + this.spark = document.createElement('canvas'); this.spark.className = 'lv-spark'; this.spark.setAttribute('aria-hidden', 'true'); + this.spark.width = 360; this.spark.height = 56; + cRate.body.appendChild(this.rateV); cRate.body.appendChild(this.rateU); cRate.body.appendChild(this.spark); + + var cCats = this.card('lv-c-cats', 'live.cats', false); + this.catBox = el('div', 'lv-chips'); this.catChips = {}; + CATS.forEach(function (c) { + var b = document.createElement('button'); + b.type = 'button'; b.className = 'lv-chip lv-k-' + c + (HOSTILE[c] ? ' lv-hot' : ''); b.setAttribute('aria-pressed', self.offCats[c] ? 'false' : 'true'); + b.appendChild(el('span', 'lv-sw')); + b.appendChild(el('span', 'lv-chip-l', t('cat.' + c))); + var n = el('span', 'lv-chip-n', '0'); b.appendChild(n); b.num = n; + b.addEventListener('click', function () { + self.offCats[c] = !self.offCats[c]; + b.setAttribute('aria-pressed', self.offCats[c] ? 'false' : 'true'); + self.filtersChanged(); + }); + self.catBox.appendChild(b); self.catChips[c] = b; + }); + cCats.body.appendChild(this.catBox); + cCats.body.appendChild(el('div', 'lv-legend', t('live.hostile'))); + + var cHosts = this.card('lv-c-hosts', 'live.hosts', false); + this.hostBox = el('div', 'lv-chips lv-hostchips'); this.hostChips = {}; + cHosts.body.appendChild(this.hostBox); + + var cCty = this.card('lv-c-cty', 'live.countries', narrow); + this.ctyList = el('ol', 'lv-cty'); cCty.body.appendChild(this.ctyList); + + var cRec = this.card('lv-c-rec', 'live.recent', false); + this.recList = el('ul', 'lv-rec'); + this.recList.addEventListener('pointerenter', function () { self.hoverList = true; }); + this.recList.addEventListener('pointerleave', function () { self.hoverList = false; self.listDirty = true; }); + this.recList.addEventListener('focusin', function () { self.hoverList = true; }); + this.recList.addEventListener('focusout', function () { self.hoverList = false; self.listDirty = true; }); + cRec.body.appendChild(this.recList); + [cRate, cCats, cHosts, cCty, cRec].forEach(function (c) { dock.appendChild(c); }); + stage.appendChild(dock); + root.appendChild(stage); + + this.updateModeButtons(); + this.listen(cv, 'pointerdown', function (e) { self.onDown(e); }); + this.listen(cv, 'pointermove', function (e) { self.onMove(e); }); + this.listen(cv, 'pointerup', function (e) { self.onUp(e); }); + this.listen(cv, 'pointercancel', function (e) { self.onUp(e); }); + this.listen(cv, 'keydown', function (e) { self.onKey(e); }); + }; + + P.updateModeButtons = function () { + this.segFlat.setAttribute('aria-pressed', this.mode === 'flat' ? 'true' : 'false'); + this.segGlobe.setAttribute('aria-pressed', this.mode === 'globe' ? 'true' : 'false'); + this.hint.hidden = this.mode !== 'globe'; + this.cv.classList.toggle('lv-globe', this.mode === 'globe'); + }; + + P.setMode = function (m) { + this.mode = m; this.target = m === 'globe' ? 1 : 0; + try { localStorage.setItem('urutau.live.mode', m); } catch (x) { /* storage blocked */ } + this.updateModeButtons(); this.dirty = true; this.kick(); + }; + + P.setPaused = function (p) { + this.paused = p; + var lab = this.t(p ? 'live.resume' : 'live.pause'); + this.bPause.setAttribute('aria-label', lab); this.bPause.title = lab; + this.bPause.setAttribute('aria-pressed', p ? 'true' : 'false'); + this.bPause.firstChild.firstChild.setAttribute('d', p ? 'M7 5l12 7-12 7z' : 'M8 5v14M16 5v14'); + this.nPaused.hidden = !p; + if (p) this.pending.length = 0; + this.last = 0; this.dirty = true; this.kick(); + }; + + P.toggleFs = function () { + try { + if (document.fullscreenElement) document.exitFullscreen(); + else this.stage.requestFullscreen(); + } catch (x) { /* ignore */ } + }; + P.onFullscreen = function () { + if (!this.bFs) return; + var on = document.fullscreenElement === this.stage; + this.stage.classList.toggle('lv-full', on); + var lab = this.t(on ? 'live.exitfs' : 'live.fullscreen'); + this.bFs.setAttribute('aria-label', lab); this.bFs.title = lab; this.bFs.setAttribute('aria-pressed', on ? 'true' : 'false'); + this.resize(); + }; + + P.filtersChanged = function () { + var any = false, k; + for (k in this.offCats) if (this.offCats[k]) any = true; + for (k in this.offHosts) if (this.offHosts[k]) any = true; + this.nFilter.hidden = !any; + this.listDirty = true; this.dirty = true; this.tick(true); + }; + + // ------------------------------------------------------------------ theme + P.readTheme = function () { + var U = this.U, css = U.css ? function (n) { return U.css(n); } : function () { return ''; }; + var text = parseColor(css('--text'), '#e8f2f4'), bg = parseColor(css('--bg'), '#070d14'); + var cols = {}; + CATS.forEach(function (c) { + var rgb = parseColor(css(TOKEN[c]), FALLBACK[c]); + cols[c] = { rgb: rgb, c0: rgba(rgb, 0), c1: rgba(rgb, 1), css: rgba(rgb, 1) }; + }); + this.colors = cols; + this.dark = (bg[0] * 299 + bg[1] * 587 + bg[2] * 114) / 1000 < 128; + this.pal = { text: text, bg: bg, accent: parseColor(css('--accent'), '#38bdf8') }; + this.cacheKey = ''; + if (this.catChips) CATS.forEach(function (c) { this.catChips[c].style.setProperty('--k', cols[c].css); }, this); + this.dirty = true; + }; + + // ------------------------------------------------------------------ data + P.loadRecent = function () { + var self = this; + if (!this.U.api) return; + var p; + try { p = this.U.api('/api/v1/live/recent', { limit: 200 }); } catch (x) { return; } + if (!p || !p.then) return; + p.then(function (res) { + var arr = Array.isArray(res) ? res : res && Array.isArray(res.events) ? res.events : null; + if (!self.alive || !arr) return; + var have = {}, seed = []; + self.ring.forEach(function (r) { have[r.key] = 1; }); + arr.slice(0, 200).reverse().forEach(function (e) { // oldest first + var r = self.record(e, true, have); + if (r) seed.push(r); + }); + // the latest part of the history plays back as arcs, whatever its age and + // spread over ~20 s, so the map never opens still on a quiet server; the + // timer lives in this.timers and dies with the page (destroy) + var replay = seed.slice(-40), id = setInterval(function () { + if (!self.alive || !replay.length) { clearInterval(id); return; } + if (!self.paused && !self.hidden) self.enqueue(replay.shift()); + }, 500); + self.timers.push(id); + self.ring.sort(function (a, b) { return a.ts - b.ts; }); + self.listDirty = true; self.tick(true); + }).catch(function () { /* endpoint not available yet */ }); + }; + + P.loadSummary = function () { + var self = this; + if (!this.U.api || this.hidden) return; + var p; + try { p = this.U.api('/api/v1/summary', { range: '1h', host: 'all' }); } catch (x) { return; } + if (!p || !p.then) return; + p.then(function (s) { + if (!self.alive || !s || !Array.isArray(s.hosts)) return; + s.hosts.forEach(function (h) { + if (!h || typeof h.name !== 'string') return; + var name = h.name.slice(0, 64), l = h.location; + self.noteHost(name); + if (l && validLL(l.lat, l.lon)) { + self.hostLoc[name] = { lat: l.lat, lon: l.lon, label: str(l.label, 48) }; + var d = self.dests[name]; + if (d && d.est) self.setDest(name, self.hostLoc[name], false); + } + }); + }).catch(function () { /* summary unavailable: keep what the events tell */ }); + }; + + P.noteHost = function (h) { + if (!h || this.hostsSeen[h]) return; + var self = this, order = Object.keys(this.hostsSeen).length; + this.hostsSeen[h] = 1; + var b = document.createElement('button'); + b.type = 'button'; b.className = 'lv-chip lv-host'; b.setAttribute('aria-pressed', this.offHosts[h] ? 'false' : 'true'); + b.appendChild(this.el('span', 'lv-dot')); + b.appendChild(this.el('span', 'lv-chip-l', h)); + var n = this.el('span', 'lv-chip-n', '0'); b.appendChild(n); b.num = n; + b.style.setProperty('--h', HOST_COLORS[order % HOST_COLORS.length]); + b.addEventListener('click', function () { + self.offHosts[h] = !self.offHosts[h]; + b.setAttribute('aria-pressed', self.offHosts[h] ? 'false' : 'true'); + self.filtersChanged(); + }); + this.hostBox.appendChild(b); this.hostChips[h] = b; + }; + + P.setDest = function (host, d, est) { + var cur = this.dests[host]; + if (!cur) { + cur = this.dests[host] = { host: host, est: est, jit: this.destList.length }; + this.destList.push(cur); + } + var lat = d.lat, lon = d.lon; + if (est) { lat += cur.jit * 1.4; lon += cur.jit * 1.8; } + cur.lat = lat; cur.lon = lon; cur.est = est; + cur.label = str(d.label, 48) || host || ''; + cur.v = vec(lat, lon); + cur.u0 = (lon + 180) / 360; cur.v0 = (LAT_TOP - clamp(lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT); + if (this.destList.length === 1 && !this.centred) { this.centred = true; this.lon0 = lon; this.lat0 = clamp(lat * 0.5, -30, 40); } + return cur; + }; + + P.destFor = function (host, d) { + if (d && validLL(d.lat, d.lon)) { + var cur = this.dests[host]; + if (!cur || cur.est || cur.lat !== d.lat || cur.lon !== d.lon) this.setDest(host, d, false); + return this.dests[host]; + } + if (this.dests[host]) return this.dests[host]; + var l = this.hostLoc[host]; + return l ? this.setDest(host, l, false) : this.setDest(host, DEFAULT_DST, true); + }; + + // normalises one event into a ring entry; null for events that are not attacks + P.record = function (e, fromHistory, have) { + if (!e || typeof e !== 'object' || e.unban || !CAT_OK[e.cat]) return null; + var host = str(e.host, 64) || 'local'; + var s = e.src && typeof e.src === 'object' ? e.src : null; + var tsec = isNum(e.t) ? e.t : Date.now() / 1000; + var what = '', ip = str(e.ip, 64); + if (e.source === 'traefik') what = (str(e.method, 8) + ' ' + str(e.path, 90)).trim(); + else if (e.source === 'ssh') what = e.user ? 'ssh ' + str(e.user, 40) : 'ssh'; + else if (e.source === 'fail2ban') what = 'fail2ban [' + str(e.jail, 40) + ']'; + var key = tsec + '|' + ip + '|' + e.cat + '|' + what; + if (have) { if (have[key]) return null; have[key] = 1; } + var r = { + ts: fromHistory ? tsec * 1000 : Date.now(), t: tsec, key: key, cat: e.cat, host: host, ip: ip, what: what, + cc: cc2(s && s.cc) || cc2(e.cc), city: str(s && s.city, 48), + slat: s ? s.lat : NaN, slon: s ? s.lon : NaN, + dst: e.dst && typeof e.dst === 'object' ? { lat: e.dst.lat, lon: e.dst.lon, label: e.dst.label } : null + }; + this.noteHost(host); + this.ring.push(r); + if (this.ring.length > RING_MAX) this.ring.splice(0, RING_TRIM); + this.listDirty = true; + return r; + }; + + P.ingest = function (e) { + if (!this.alive) return; + var r = this.record(e, false); + if (!r || this.paused || this.hidden) return; + this.enqueue(r); + }; + + P.visible = function (r) { + if (this.offCats[r.cat] || this.offHosts[r.host]) return false; + var h = this.ctx && this.ctx.host; + return !h || h === 'all' || h === r.host; + }; + + P.originOf = function (r) { + if (validLL(r.slat, r.slon)) return { lat: r.slat, lon: r.slon }; + var c = this.world && this.world.centroids && this.world.centroids[r.cc]; + if (c) return { lat: LAT_TOP - c[1] / WORLD_H * (LAT_TOP - LAT_BOT), lon: c[0] / WORLD_W * 360 - 180 }; + return null; + }; + + P.enqueue = function (r) { + if (!this.visible(r)) return; + var o = this.originOf(r); + if (!o) return; + var d = this.destFor(r.host, r.dst); + if (this.reduced) { + this.dots.push({ lat: o.lat, lon: o.lon, v: vec(o.lat, o.lon), cat: r.cat }); + if (this.dots.length > 160) this.dots.shift(); + this.dirty = true; this.kick(); + return; + } + if (this.pending.length >= MAX_PENDING) { + var drop = this.pending.length - 300; + this.pending.splice(0, drop); + this.addMore(drop); + } + this.pending.push({ o: o, d: d, cat: r.cat }); + this.kick(); + }; + + P.addMore = function (n) { + var s = Math.floor(Date.now() / 1000), m = this.more; + if (m.length && m[m.length - 1][0] === s) m[m.length - 1][1] += n; else m.push([s, n]); + while (m.length && m[0][0] < s - 10) m.shift(); + }; + + // ------------------------------------------------------------------ arcs + P.spawn = function (it) { + var a = this.free.pop() || {}; + var o = it.o, d = it.d, hostile = !!HOSTILE[it.cat]; + a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d; + a.born = this.T; + a.u0 = (o.lon + 180) / 360; a.v0 = (LAT_TOP - clamp(o.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT); + a.a = vec(o.lat, o.lon); a.b = d.v; + a.w = Math.acos(clamp(a.a[0] * a.b[0] + a.a[1] * a.b[1] + a.a[2] * a.b[2], -1, 1)); + a.D = hostile ? 1.35 : 1.0; + a.hold = hostile ? 1.4 : 0.2; + a.pl = hostile ? 1.9 : 1.1; + a.life = Math.max(a.D + a.pl, a.D + a.hold + a.D); + this.arcs.push(a); + return a; + }; + + P.stepSpawn = function () { + var q = this.pending; + if (!q.length) return; + var budget = q.length > 80 ? 48 : q.length > 24 ? 14 : 6; + var maxArcs = Math.round(MAX_ARCS * this.quality); + var keys = this.frameKey, n = 0, merged = 0, k; + for (k in keys) delete keys[k]; + while (q.length && n < budget && this.arcs.length < maxArcs) { + var it = q.shift(); n++; + var key = Math.round(it.o.lat / 2) + ',' + Math.round(it.o.lon / 2) + '|' + it.d.host + '|' + it.cat; + if (q.length > 24 && keys[key]) { keys[key].n++; merged++; continue; } + keys[key] = this.spawn(it); + } + if (merged) this.addMore(merged); + }; + + // ------------------------------------------------------------------ geometry / layout + P.resize = function () { + if (!this.alive) return; + var r = this.view.getBoundingClientRect(); + var w = Math.max(10, Math.round(r.width)), h = Math.max(10, Math.round(r.height)); + var dpr = Math.min(window.devicePixelRatio || 1, 2); + var overlay = getComputedStyle(this.dock).position === 'absolute' && !this.stage.classList.contains('lv-nodock'); + this.reserve = overlay ? this.dock.offsetHeight + 20 : 0; + if (w !== this.W || h !== this.H || dpr !== this.dpr) { + this.W = w; this.H = h; this.dpr = dpr; + this.cv.width = Math.round(w * dpr); this.cv.height = Math.round(h * dpr); + } + var top = w < 560 ? 50 : 54; + var availH = Math.max(80, h - top - this.reserve - 6), availW = w - 16; + var s = Math.min(availW / WORLD_W, availH / WORLD_H); + this.mw = WORLD_W * s; this.mh = WORLD_H * s; + this.ox = (w - this.mw) / 2; this.oy = top + (availH - this.mh) / 2; + this.cx = w / 2; this.cy = top + (h - top - this.reserve) / 2; + this.R = Math.max(40, Math.min(availW / 2 - 4, (h - top - this.reserve) / 2 - 8)); + this.cacheKey = ''; + this.dirty = true; this.kick(); + }; + + P.buildFlatCache = function () { + var key = [Math.round(this.mw), Math.round(this.mh), this.dpr, this.dark ? 1 : 0, this.pal.text.join()].join('|'); + if (this.cacheKey === key && this.flatCache) return; + this.cacheKey = key; + var cv = this.flatCache || document.createElement('canvas'); + this.flatCache = cv; + var d = this.dpr, w = Math.ceil(this.mw), h = Math.ceil(this.mh); + cv.width = Math.ceil(w * d); cv.height = Math.ceil(h * d); + var g = cv.getContext('2d'); + g.setTransform(d, 0, 0, d, 0, 0); + g.clearRect(0, 0, w, h); + var tx = this.pal.text, lon, lat; + g.strokeStyle = rgba(tx, this.dark ? 0.06 : 0.09); g.lineWidth = 1; g.beginPath(); + for (lon = -150; lon <= 150; lon += 30) { var x = (lon + 180) / 360 * w; g.moveTo(x, 0); g.lineTo(x, h); } + for (lat = -30; lat <= 60; lat += 30) { var y = (LAT_TOP - lat) / (LAT_TOP - LAT_BOT) * h; g.moveTo(0, y); g.lineTo(w, y); } + g.stroke(); + if (this.world) { + var s = w / WORLD_W; + g.save(); g.scale(s, s); + g.fillStyle = rgba(tx, 0.13); + g.strokeStyle = rgba(tx, this.dark ? 0.26 : 0.32); + g.lineWidth = 0.7 / s; + var paths = this.world.paths; + Object.keys(paths).forEach(function (cc) { + var p = new Path2D(paths[cc]); + g.fill(p); g.stroke(p); + }); + g.restore(); + } + }; + + // ------------------------------------------------------------------ input (globe) + P.onDown = function (e) { + if (this.mode !== 'globe') return; + this.dragging = true; this.px = e.clientX; this.py = e.clientY; this.vlon = 0; this.vlat = 0; + try { this.cv.setPointerCapture(e.pointerId); } catch (x) { /* ignore */ } + this.cv.classList.add('lv-grab'); + }; + P.onMove = function (e) { + if (!this.dragging) return; + var k = 57.3 / this.R, dx = e.clientX - this.px, dy = e.clientY - this.py; + this.px = e.clientX; this.py = e.clientY; + this.lon0 -= dx * k; this.lat0 = clamp(this.lat0 + dy * k, -75, 75); + this.vlon = -dx * k * 40; this.vlat = dy * k * 40; + this.dirty = true; this.kick(); + }; + P.onUp = function (e) { + if (!this.dragging) return; + this.dragging = false; this.idleAt = this.T + 2.5; + this.cv.classList.remove('lv-grab'); + try { this.cv.releasePointerCapture(e.pointerId); } catch (x) { /* ignore */ } + this.dirty = true; this.kick(); + }; + P.onKey = function (e) { + var k = e.key, used = true; + if (k === 'ArrowLeft') this.lon0 -= 10; + else if (k === 'ArrowRight') this.lon0 += 10; + else if (k === 'ArrowUp') this.lat0 = clamp(this.lat0 + 10, -75, 75); + else if (k === 'ArrowDown') this.lat0 = clamp(this.lat0 - 10, -75, 75); + else used = false; + if (used) { e.preventDefault(); this.idleAt = this.T + 4; this.dirty = true; this.kick(); } + }; + + // ------------------------------------------------------------------ loop + P.onVisibility = function () { + this.hidden = document.hidden; + if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; } + else { this.last = 0; this.dirty = true; this.kick(); this.loadSummary(); this.tick(true); } + }; + + P.kick = function () { + var self = this; + if (!this.alive || this.raf || this.hidden) return; + this.raf = requestAnimationFrame(function (now) { self.frame(now); }); + }; + + P.frame = function (now) { + this.raf = 0; + if (!this.alive || this.hidden) return; + var raw = this.last ? now - this.last : 16; + var dt = this.last ? Math.min(0.1, raw / 1000) : 0.016; + this.last = now; + var wasDirty = this.dirty; + var still = this.paused || this.reduced; + if (!this.paused) { + this.T += this.reduced ? 0.2 : dt; + if (!this.reduced) { + // adaptive quality: shed arcs when frames get slow, recover when they are cheap again + this.frameAvg += (raw - this.frameAvg) * 0.05; + if (this.frameAvg > 26) this.quality = Math.max(0.35, this.quality - 0.02); + else if (this.frameAvg < 20) this.quality = Math.min(1, this.quality + 0.01); + } + this.stepSpawn(); + } + var df = this.target - this.m, morph = false; + if (Math.abs(df) > 0.003) { this.m += df * (this.reduced ? 1 : Math.min(1, dt * 6.5)); morph = true; } else this.m = this.target; + if (this.m > 0.01 && !this.paused && !this.dragging) { + if (Math.abs(this.vlon) > 0.05 || Math.abs(this.vlat) > 0.05) { + this.lon0 += this.vlon * dt; this.lat0 = clamp(this.lat0 + this.vlat * dt, -75, 75); + var f = Math.pow(0.04, dt); this.vlon *= f; this.vlat *= f; + } else if (!this.reduced && this.T > this.idleAt) { + this.lon0 += 4.5 * dt; + } + } + if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle + this.dirty = false; + this.draw(); + var arcs = this.arcs; + for (var i = arcs.length - 1; i >= 0; i--) { + if (this.T - arcs[i].born > arcs[i].life) { + this.free.push(arcs[i]); + arcs[i] = arcs[arcs.length - 1]; arcs.pop(); + } + } + if (!still || morph || this.dirty) this.kick(); + }; + + // ------------------------------------------------------------------ drawing + P.draw = function () { + var g = this.g, d = this.dpr, W = this.W, H = this.H, m = this.m; + g.setTransform(d, 0, 0, d, 0, 0); + g.globalCompositeOperation = 'source-over'; + g.globalAlpha = 1; + g.clearRect(0, 0, W, H); + this.buildFlatCache(); + var add = this.dark ? 'lighter' : 'source-over'; + if (m < 0.995) { + g.globalAlpha = 1 - m; + g.drawImage(this.flatCache, this.ox, this.oy, this.mw, this.mh); + this.drawFlatLayer(g, 1 - m, add); + } + if (m > 0.005) { + this.prepGlobe(m); + this.drawGlobeBase(g, m); + this.drawGlobeLayer(g, m, add); + } + g.globalAlpha = 1; g.globalCompositeOperation = 'source-over'; + }; + + P.drawLabel = function (g, text, x, y, alpha) { + g.font = '600 11px system-ui, -apple-system, "Segoe UI", sans-serif'; + g.textBaseline = 'middle'; + var w = g.measureText(text).width; + var left = x + 10 + w > this.W - 6; + var tx = left ? x - 10 : x + 10; + g.textAlign = left ? 'right' : 'left'; + g.globalAlpha = alpha; + g.lineWidth = 3; g.lineJoin = 'round'; + g.strokeStyle = rgba(this.pal.bg, 0.85); g.strokeText(text, tx, y); + g.fillStyle = rgba(this.pal.text, 0.95); g.fillText(text, tx, y); + }; + + P.drawDestDot = function (g, x, y, alpha, ang, zz, est) { + var acc = this.pal.accent; + var br = (Math.sin(this.T * 2.2) + 1) / 2, rr = 7 + br * 5; + g.globalAlpha = alpha * (0.25 + 0.2 * br); + g.strokeStyle = rgba(acc, 1); g.lineWidth = 1.2; + g.beginPath(); + if (ang === null) g.arc(x, y, rr, 0, TAU); else g.ellipse(x, y, rr * zz, rr, ang, 0, TAU); + g.stroke(); + g.globalAlpha = alpha; + g.fillStyle = rgba(this.pal.bg, 1); + g.beginPath(); g.arc(x, y, 5, 0, TAU); g.fill(); + g.fillStyle = rgba(acc, 1); + g.beginPath(); g.arc(x, y, 3.4, 0, TAU); g.fill(); + if (est) { + g.strokeStyle = rgba(this.pal.text, 0.8); g.lineWidth = 1; + g.setLineDash([2, 2]); g.beginPath(); g.arc(x, y, 6, 0, TAU); g.stroke(); g.setLineDash([]); + } + }; + + P.drawPulse = function (g, x, y, a, age, col, ang, zz, fade) { + var pa = (age - a.D) / a.pl; + if (pa < 0 || pa >= 1) return; + var rmax = a.hostile ? 30 : 17, n = a.hostile ? 2 : 1, i; + g.lineWidth = a.hostile ? 2 : 1.4; g.strokeStyle = col.css; + for (i = 0; i < n; i++) { + var q = pa - i * 0.22; + if (q <= 0) continue; + var r = 3 + (1 - (1 - q) * (1 - q)) * rmax; + g.globalAlpha = fade * (1 - q) * 0.9; + g.beginPath(); + if (ang === null) g.arc(x, y, r, 0, TAU); else g.ellipse(x, y, r * zz, r, ang, 0, TAU); + g.stroke(); + } + if (pa < 0.35) { + g.globalAlpha = fade * (1 - pa / 0.35); + g.fillStyle = col.css; + g.beginPath(); g.arc(x, y, 3 + pa * 6 + (a.n > 1 ? Math.min(3, Math.log(a.n)) : 0), 0, TAU); g.fill(); + } + }; + + P.drawFlatLayer = function (g, layerAlpha, add) { + var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.arcs, i; + g.globalCompositeOperation = 'source-over'; + for (i = 0; i < this.dots.length; i++) { // reduced motion: static dots instead of arcs + var dd = this.dots[i]; + g.globalAlpha = layerAlpha * 0.75; g.fillStyle = this.colors[dd.cat].css; + g.beginPath(); g.arc(ox + (dd.lon + 180) / 360 * mw, oy + (LAT_TOP - clamp(dd.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT) * mh, 2.6, 0, TAU); g.fill(); + } + g.globalCompositeOperation = add; + g.lineCap = 'round'; + for (i = 0; i < arcs.length; i++) { + var a = arcs[i], age = T - a.born; + if (age < 0) continue; + var col = this.colors[a.cat]; + var x0 = ox + a.u0 * mw, y0 = oy + a.v0 * mh, x1 = ox + a.dest.u0 * mw, y1 = oy + a.dest.v0 * mh; + var dx = x1 - x0, dy = y1 - y0, dist = Math.sqrt(dx * dx + dy * dy); + var cx = (x0 + x1) / 2, cy = (y0 + y1) / 2 - Math.min(dist * 0.42, mh * 0.5) - 4; + var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1)); + var fade = layerAlpha * (1 - 0.75 * tail); + if (tail < 1 && head > tail) { + // exact sub-curve of the quadratic Bezier between parameters tail..head + var ut = 1 - tail, uh = 1 - head; + var ax = ut * ut * x0 + 2 * tail * ut * cx + tail * tail * x1, ay = ut * ut * y0 + 2 * tail * ut * cy + tail * tail * y1; + var bx = uh * uh * x0 + 2 * head * uh * cx + head * head * x1, by = uh * uh * y0 + 2 * head * uh * cy + head * head * y1; + var kx = ax + (head - tail) * (ut * (cx - x0) + tail * (x1 - cx)); + var ky = ay + (head - tail) * (ut * (cy - y0) + tail * (y1 - cy)); + var gr = g.createLinearGradient(ax, ay, bx, by); + gr.addColorStop(0, col.c0); gr.addColorStop(1, col.c1); + g.strokeStyle = gr; + g.beginPath(); g.moveTo(ax, ay); g.quadraticCurveTo(kx, ky, bx, by); + if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); } + g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); + g.stroke(); + if (head < 1) { + g.fillStyle = col.css; + g.beginPath(); g.arc(bx, by, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); + } + } + if (age < 0.7) { + g.globalAlpha = layerAlpha * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1; + g.beginPath(); g.arc(x0, y0, 2 + age * 9, 0, TAU); g.stroke(); + } + this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha); + } + g.globalCompositeOperation = 'source-over'; + for (i = 0; i < this.destList.length; i++) { + var ds = this.destList[i], x = ox + ds.u0 * mw, y = oy + ds.v0 * mh; + this.drawDestDot(g, x, y, layerAlpha, null, 1, ds.est); + this.drawLabel(g, ds.label, x, y + (i % 2 ? 15 : -15), layerAlpha); + } + }; + + // ---- globe + P.prepGlobe = function (m) { + var l0 = this.lon0 * RAD, p0 = this.lat0 * RAD; + this.cl = Math.cos(l0); this.sl = Math.sin(l0); this.cp = Math.cos(p0); this.sp = Math.sin(p0); + this.gR = this.R * (0.9 + 0.1 * m); + }; + // rotates a vector into the view: screen x (rx), screen y up (ry), depth (rz, > 0 faces the viewer) + P.rot = function (x, y, z) { + var x1 = x * this.cl - z * this.sl, z1 = x * this.sl + z * this.cl; + this.rx = x1; this.ry = y * this.cp - z1 * this.sp; this.rz = y * this.sp + z1 * this.cp; + }; + + P.drawGlobeBase = function (g, m) { + var cx = this.cx, cy = this.cy, R = this.gR, acc = this.pal.accent, tx = this.pal.text, dark = this.dark; + var lat, lon, k, up, cl; + g.globalCompositeOperation = 'source-over'; + g.globalAlpha = m; + var ga = g.createRadialGradient(cx, cy, R * 0.98, cx, cy, R * 1.16); + ga.addColorStop(0, rgba(acc, dark ? 0.28 : 0.2)); ga.addColorStop(1, rgba(acc, 0)); + g.fillStyle = ga; g.beginPath(); g.arc(cx, cy, R * 1.16, 0, TAU); g.fill(); + var go = g.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R); + go.addColorStop(0, rgba(acc, dark ? 0.22 : 0.16)); go.addColorStop(1, rgba(acc, dark ? 0.05 : 0.05)); + g.fillStyle = rgba(this.pal.bg, 0.6); g.beginPath(); g.arc(cx, cy, R, 0, TAU); g.fill(); + g.fillStyle = go; g.fill(); + g.save(); + g.beginPath(); g.arc(cx, cy, R, 0, TAU); g.clip(); + g.strokeStyle = rgba(tx, dark ? 0.07 : 0.1); g.lineWidth = 1; g.beginPath(); + for (lat = -60; lat <= 60; lat += 30) { + up = false; cl = Math.cos(lat * RAD); + for (k = 0; k <= 72; k++) { + lon = k * 5 - 180; + this.rot(cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD)); + if (this.rz > 0) { if (up) g.lineTo(cx + this.rx * R, cy - this.ry * R); else g.moveTo(cx + this.rx * R, cy - this.ry * R); up = true; } else up = false; + } + } + for (lon = -180; lon < 180; lon += 30) { + up = false; + for (k = 0; k <= 36; k++) { + lat = k * 5 - 90; cl = Math.cos(lat * RAD); + this.rot(cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD)); + if (this.rz > 0) { if (up) g.lineTo(cx + this.rx * R, cy - this.ry * R); else g.moveTo(cx + this.rx * R, cy - this.ry * R); up = true; } else up = false; + } + } + g.stroke(); + if (this.geo) { + var rings = this.geo.rings, sc = this.geo.scratch, o = 0, i, j; + g.beginPath(); + for (i = 0; i < rings.length; i++) { + var r = rings[i], v = r.v, n = r.n; + for (j = 0; j < n; j++) { + this.rot(v[j * 3], v[j * 3 + 1], v[j * 3 + 2]); + var sx = this.rx, sy = this.ry, z = this.rz; + if (z < 0) { var hl = Math.sqrt(sx * sx + sy * sy) || 1; sx /= hl; sy /= hl; } // hidden side: pinned to the limb + sc[o] = cx + sx * R; sc[o + 1] = cy - sy * R; sc[o + 2] = z; + if (j === 0) g.moveTo(sc[o], sc[o + 1]); else g.lineTo(sc[o], sc[o + 1]); + o += 3; + } + g.closePath(); + } + g.fillStyle = rgba(tx, 0.2); g.fill(); + g.strokeStyle = rgba(tx, dark ? 0.38 : 0.45); g.lineWidth = 0.8; g.beginPath(); + o = 0; + for (i = 0; i < rings.length; i++) { + var e = rings[i].edge, n2 = rings[i].n; + for (j = 1; j <= n2; j++) { + var p = (j - 1) * 3 + o, q = (j % n2) * 3 + o; + if (sc[p + 2] > 0 && sc[q + 2] > 0 && !e[j % n2]) { g.moveTo(sc[p], sc[p + 1]); g.lineTo(sc[q], sc[q + 1]); } + } + o += n2 * 3; + } + g.stroke(); + } + var gs = g.createRadialGradient(cx, cy, R * 0.6, cx, cy, R); + gs.addColorStop(0, rgba(this.pal.bg, 0)); gs.addColorStop(1, rgba(this.pal.bg, dark ? 0.55 : 0.25)); + g.fillStyle = gs; g.fillRect(cx - R, cy - R, R * 2, R * 2); + g.restore(); + g.strokeStyle = rgba(acc, dark ? 0.5 : 0.6); g.lineWidth = 1.2; + g.beginPath(); g.arc(cx, cy, R, 0, TAU); g.stroke(); + }; + + P.drawGlobeLayer = function (g, m, add) { + var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.arcs, i, k; + g.globalCompositeOperation = 'source-over'; + for (i = 0; i < this.dots.length; i++) { + var dd = this.dots[i]; + this.rot(dd.v[0], dd.v[1], dd.v[2]); + if (this.rz <= 0.02) continue; + g.globalAlpha = m * 0.8; g.fillStyle = this.colors[dd.cat].css; + g.beginPath(); g.arc(cx + this.rx * R, cy - this.ry * R, 2.6, 0, TAU); g.fill(); + } + g.globalCompositeOperation = add; + g.lineCap = 'round'; + for (i = 0; i < arcs.length; i++) { + var a = arcs[i], age = T - a.born; + if (age < 0) continue; + var col = this.colors[a.cat]; + var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1)); + var fade = m * (1 - 0.75 * tail); + var A = a.a, B = a.b, w = a.w, sw = Math.sin(w); + if (tail < 1 && head > tail) { + var lift = 0.05 + 0.22 * w / Math.PI; + var N = Math.max(4, Math.min(Math.round(22 * this.quality), Math.ceil((head - tail) * 24) + 2)); + var cnt = 0, run = false, fx = 0, fy = 0, lx = 0, ly = 0; + g.beginPath(); + for (k = 0; k <= N; k++) { + var f = tail + (head - tail) * k / N, s1, s2; + if (sw < 1e-4) { s1 = 1 - f; s2 = f; } else { s1 = Math.sin((1 - f) * w) / sw; s2 = Math.sin(f * w) / sw; } + var h = 1 + lift * Math.sin(Math.PI * f); + this.rot((A[0] * s1 + B[0] * s2) * h, (A[1] * s1 + B[1] * s2) * h, (A[2] * s1 + B[2] * s2) * h); + if (this.rz > 0 || (this.rx * this.rx + this.ry * this.ry) > 1) { + var px = cx + this.rx * R, py = cy - this.ry * R; + if (run) g.lineTo(px, py); else g.moveTo(px, py); + if (!cnt) { fx = px; fy = py; } + run = true; lx = px; ly = py; cnt++; + } else run = false; + } + if (cnt > 1) { + var gr = g.createLinearGradient(fx, fy, lx, ly); + gr.addColorStop(0, col.c0); gr.addColorStop(1, col.c1); + g.strokeStyle = gr; + if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); } + g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); + g.stroke(); + if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(lx, ly, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); } + } + } + if (age >= a.D) { + this.rot(B[0], B[1], B[2]); + if (this.rz > 0.02) this.drawPulse(g, cx + this.rx * R, cy - this.ry * R, a, age, col, Math.atan2(-this.ry, this.rx), this.rz, m); + } + if (age < 0.7) { + this.rot(A[0], A[1], A[2]); + if (this.rz > 0.02) { + g.globalAlpha = m * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1; + g.beginPath(); g.arc(cx + this.rx * R, cy - this.ry * R, 2 + age * 9, 0, TAU); g.stroke(); + } + } + } + g.globalCompositeOperation = 'source-over'; + for (i = 0; i < this.destList.length; i++) { + var ds = this.destList[i]; + this.rot(ds.v[0], ds.v[1], ds.v[2]); + if (this.rz <= 0.05) continue; + var x = cx + this.rx * R, y = cy - this.ry * R, al = m * clamp(this.rz * 3, 0, 1); + this.drawDestDot(g, x, y, al, Math.atan2(-this.ry, this.rx), this.rz, ds.est); + this.drawLabel(g, ds.label, x, y + (i % 2 ? 15 : -15), al); + } + }; + + // ------------------------------------------------------------------ panels + P.regionName = function (cc) { + if (this.U.fmt && this.U.fmt.country) { var n = this.U.fmt.country(cc); if (n) return n; } + var lang = this.ctx.lang || undefined; + try { + if (!this.dn || this.dnLang !== lang) { this.dn = new Intl.DisplayNames([lang || 'en'], { type: 'region' }); this.dnLang = lang; } + return this.dn.of(cc) || cc; + } catch (x) { return cc; } + }; + + P.tick = function (force) { + if (!this.alive || (this.hidden && !force)) return; + var now = Date.now(), ring = this.ring, i, r, b, self = this; + // The ring is bounded by RING_MAX, not by age: the 5 min window only applies + // to the statistics, so the latest-events list still shows something on a + // quiet server. + var cut5 = now - 300000; + var cut1 = now - 60000, perMin = 0, cats = {}, hosts = {}, ctys = {}, bins = []; + for (b = 0; b < 60; b++) bins.push(0); + for (i = 0; i < ring.length; i++) { + r = ring[i]; + if (r.ts < cut5) continue; + if (r.cc && this.visible(r)) ctys[r.cc] = (ctys[r.cc] || 0) + 1; + if (r.ts >= cut1) { + perMin++; + cats[r.cat] = (cats[r.cat] || 0) + 1; + hosts[r.host] = (hosts[r.host] || 0) + 1; + b = 59 - Math.floor((now - r.ts) / 1000); + if (b >= 0 && b < 60) bins[b]++; + } + } + var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String; + var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; }; + this.rateV.textContent = fmtN(perMin); + CATS.forEach(function (c) { self.catChips[c].num.textContent = fmtN(cats[c] || 0); }); + Object.keys(this.hostChips).forEach(function (h) { self.hostChips[h].num.textContent = fmtN(hosts[h] || 0); }); + this.drawSpark(bins); + + var s = Math.floor(now / 1000), more = 0; + this.more.forEach(function (x) { if (x[0] >= s - 10) more += x[1]; }); + this.nMore.hidden = more <= 0; + if (more > 0) this.nMore.textContent = this.t('live.more', fmtN(more)); + var est = false; + this.destList.forEach(function (d) { if (d.est) est = true; }); + this.nEst.hidden = !est; + + var top = Object.keys(ctys).sort(function (a, c) { return ctys[c] - ctys[a]; }).slice(0, 6); + var box = this.ctyList, max = top.length ? ctys[top[0]] : 1; + while (box.firstChild) box.removeChild(box.firstChild); + if (!top.length) box.appendChild(this.el('li', 'lv-empty', this.t('live.empty'))); + top.forEach(function (cc) { + var li = self.el('li', 'lv-cty-i'); + li.appendChild(self.el('span', 'lv-cty-n', fl(cc) + ' ' + self.regionName(cc))); + li.appendChild(self.el('span', 'lv-cty-v', fmtN(ctys[cc]))); + var bar = self.el('span', 'lv-cty-b'); bar.style.setProperty('--w', Math.round(ctys[cc] / max * 100) + '%'); + li.appendChild(bar); + box.appendChild(li); + }); + this.renderList(force); + }; + + P.drawSpark = function (bins) { + var c = this.spark, g = c.getContext('2d'), w = c.width, h = c.height, max = 1, i; + for (i = 0; i < bins.length; i++) if (bins[i] > max) max = bins[i]; + g.clearRect(0, 0, w, h); + var col = this.pal.accent, bw = w / bins.length; + for (i = 0; i < bins.length; i++) { + var bh = bins[i] ? Math.max(3, bins[i] / max * (h - 4)) : 1.5; + g.fillStyle = rgba(col, bins[i] ? 0.4 + 0.55 * (i / bins.length) : 0.2); + g.fillRect(i * bw + 0.5, h - bh, bw - 1.5, bh); + } + }; + + P.renderList = function (force) { + if (!this.listDirty && !force) return; + if (this.hoverList && !force) return; + this.listDirty = false; + var box = this.recList, ring = this.ring, n = 0, self = this, i, r; + var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; }; + while (box.firstChild) box.removeChild(box.firstChild); + for (i = ring.length - 1; i >= 0 && n < 30; i--) { + r = ring[i]; + if (!this.visible(r)) continue; + n++; + var li = this.el('li', 'lv-ev'); + li.appendChild(this.el('time', 'lv-ev-t', new Date(r.t * 1000).toLocaleTimeString(this.ctx.lang || undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' }))); + li.appendChild(this.el('span', 'lv-tag lv-k-' + r.cat + (HOSTILE[r.cat] ? ' lv-hot' : ''), this.t('cat.' + r.cat))); + var b = this.el('button', 'lv-ip', (r.cc ? fl(r.cc) + ' ' : '') + r.ip); + b.type = 'button'; + (function (ip) { b.addEventListener('click', function () { if (self.U.openIP) self.U.openIP(ip); }); })(r.ip); + li.appendChild(b); + li.appendChild(this.el('span', 'lv-ev-w', (r.city ? r.city + ' · ' : '') + '[' + r.host + '] ' + r.what)); + box.appendChild(li); + } + if (!n) box.appendChild(this.el('li', 'lv-empty', this.t('live.empty'))); + }; + + // ------------------------------------------------------------------ bootstrap + if (!boot()) document.addEventListener('DOMContentLoaded', boot, { once: true }); +})(); diff --git a/internal/server/web/style.css b/internal/server/web/style.css index 25ca992..221c540 100644 --- a/internal/server/web/style.css +++ b/internal/server/web/style.css @@ -1,204 +1,420 @@ +/* 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 ), 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; } + .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; } -} diff --git a/internal/store/export.go b/internal/store/export.go index 203ff7d..f9a29de 100644 --- a/internal/store/export.go +++ b/internal/store/export.go @@ -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) diff --git a/internal/store/live.go b/internal/store/live.go new file mode 100644 index 0000000..0c00fdd --- /dev/null +++ b/internal/store/live.go @@ -0,0 +1,160 @@ +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 = 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) } diff --git a/internal/store/live_test.go b/internal/store/live_test.go new file mode 100644 index 0000000..f5c4f29 --- /dev/null +++ b/internal/store/live_test.go @@ -0,0 +1,37 @@ +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) + } +} diff --git a/internal/store/store.go b/internal/store/store.go index 27aebcf..1e7d329 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -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. diff --git a/internal/store/summary.go b/internal/store/summary.go index e9f100e..5a4e4f6 100644 --- a/internal/store/summary.go +++ b/internal/store/summary.go @@ -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, diff --git a/scripts/check-ui-i18n.mjs b/scripts/check-ui-i18n.mjs index 0208700..b425d84 100755 --- a/scripts/check-ui-i18n.mjs +++ b/scripts/check-ui-i18n.mjs @@ -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,89 @@ 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(/\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 +105,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(//g, '').replace(//g, '').replace(/[\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)`);