Compare commits

..
13 Commits
Author SHA1 Message Date
lucasrguerra 4143bf599e Merge pull request 'fix(egress): container map refreshed on start; no new_geo for anycast CDNs (2.2.2)' (#4) from fix/egress-attribution-anycast into main
Release / ci (push) Skipped
CI / Format and vet (push) Successful in 1m21s
CI / Dependency audit (push) Successful in 47s
CI / Tests (Linux, race detector) (push) Successful in 2m26s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (probe) (push) Successful in 21s
Release / Publish tags (hub) (push) Successful in 21s
Release / Gitea release (push) Successful in 4s
2026-11-19 18:43:51 +00:00
Lucas RayanandClaude Opus 5.5 65015158dc fix(egress): container map refreshed on start; no new_geo for anycast CDNs (2.2.2)
CI / Format and vet (pull_request) Successful in 1m43s
CI / Dependency audit (pull_request) Successful in 39s
CI / Tests (Linux, race detector) (pull_request) Successful in 2m37s
A LambdaMail redeploy swapped rspamd and clamav addresses and the hub judged
the next minute with the stale containers.map, filing SURBL/DNS traffic under
clamav and freshclam under dns. The host kit now runs urutau-containers-watch
(docker events -> map rewrite) and the probe polls the file every 2 s.

new_geo is skipped for large CDNs/clouds: anycast addresses carry a
meaningless database country (1.1.1.1 in AU, Cloudflare edges in CA).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:25:23 -03:00
Lucas RayanandClaude Opus 5.5 87178dbc94 fix: head fingerprint covers the whole first line; hub no longer drops traefik generations whose first 64 bytes repeat (2.2.1)
CI / Format and vet (push) Successful in 1m15s
CI / Dependency audit (push) Successful in 36s
CI / Tests (Linux, race detector) (push) Successful in 2m7s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 18s
Release / Gitea release (push) Successful in 4s
Release / Publish tags (probe) (push) Successful in 18s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:57:25 -03:00
Lucas RayanandClaude Opus 5.5 c2bee81bc1 fix: back to all hosts in the filter; release 2.2.0
Release / Plan (reuse the published image?) (push) Successful in 7s
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 17s
Release / Publish tags (probe) (push) Successful in 16s
Release / Gitea release (push) Successful in 5s
CI / Format and vet (push) Successful in 1m9s
CI / Dependency audit (push) Successful in 38s
CI / Tests (Linux, race detector) (push) Successful in 2m6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:32:25 -03:00
Lucas Rayan 551b0ebc40 Merge branch 'fix/traffic-hosts' 2026-11-16 20:27:36 -03:00
Lucas RayanandClaude Sonnet 5.5 7b90d9e40f fix: host filter accepts all and comma lists; hub no longer drops traefik lines after a copytruncate rotation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:27:18 -03:00
Lucas RayanandClaude Sonnet 5.5 0db50c05c4 fix(ip): show egress destination view instead of ambiguous 404
Add GET /api/v1/ip/{ip}/egress and Engine.Dst; the IP page renders who
connected, findings and linked incidents, or a definitive never-seen message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:22:20 -03:00
Lucas RayanandClaude Opus 5.5 19afd221e2 fix: keep probe files across hub restarts; phone filter sheet above the tab bar (2.1.2)
CI / Format and vet (push) Successful in 1m4s
CI / Dependency audit (push) Successful in 33s
CI / Tests (Linux, race detector) (push) Successful in 2m10s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 16s
Release / Publish tags (probe) (push) Successful in 16s
Release / Gitea release (push) Successful in 5s
The hub kept a probe's resolv.conf and containers.map only in memory, so
after a restart the egress lines replayed on reconnect were judged with
the hub's own resolvers (false dns_bypass, hostinger/INC-8). They are now
saved in the node directory and loaded at start.

Phone: the global filter sheet opens above the bottom tab bar, the tab
bar closes it, and the sticky filter bar no longer covers the More menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:41:28 -03:00
Lucas RayanandClaude Opus 5.5 fb2dfa3fb2 fix(ui): incidents status tabs had a 1 px vertical micro-scroll (2.1.1)
CI / Format and vet (pull_request) Successful in 1m1s
CI / Dependency audit (pull_request) Successful in 31s
CI / Tests (Linux, race detector) (pull_request) Successful in 1m50s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 15s
Release / Publish tags (probe) (push) Successful in 15s
Release / Gitea release (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:41:27 -03:00
Lucas RayanandClaude Opus 5.5 77bea54fb3 test(probeagent): wait for Run to return before TempDir cleanup
CI / Format and vet (push) Successful in 59s
CI / Dependency audit (push) Successful in 31s
CI / Tests (Linux, race detector) (push) Successful in 1m39s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 15s
Release / Publish tags (probe) (push) Successful in 16s
Release / Gitea release (push) Successful in 5s
Tests started probes with a deferred cancel and never waited for Run, so a
final state write could race t.TempDir's RemoveAll ('directory not empty').
startRun now registers a cleanup that cancels and waits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:26:39 -03:00
Lucas RayanandClaude Opus 5.5 fa31cd2ccb ci(release): build when the skipped ci is a reusable workflow
Release / Plan (reuse the published image?) (push) Successful in 5s
CI / Format and vet (push) Successful in 1m2s
CI / Dependency audit (push) Successful in 29s
CI / Tests (Linux, race detector) (push) Failing after 1m34s
Release / ci (push) Failing after 1m34s
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Skipped
Release / Publish tags (probe) (push) Skipped
Release / Gitea release (push) Skipped
Gitea does not report result == 'skipped' for a skipped 'uses:' job, so the
builds were skipped with it and v2.1.0 published nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:22:13 -03:00
Lucas RayanandClaude Opus 5.5 00c4ab6d4a feat: 2.1.0 incidents, filter bar and IP analysis redesign; probe egress files fix
CI / Format and vet (pull_request) Successful in 1m1s
CI / Dependency audit (pull_request) Successful in 32s
CI / Tests (Linux, race detector) (pull_request) Successful in 1m55s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Skipped
Release / Publish tags (probe) (push) Skipped
Release / Gitea release (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:18:38 -03:00
Lucas RayanandClaude Opus 5.5 7c92d4b359 ci: build and test each tree once
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (probe) (push) Successful in 16s
Release / Publish tags (hub) (push) Successful in 17s
Release / Gitea release (push) Skipped
The release ran per ref, so main and a tag pushed together both planned
before any image existed and built everything twice; it also re-ran the
whole CI that the pull request had already passed on the same commit, and
the PR CI built the images a third time. Now: one release queue (the tag
waits for main and only re-points tags), the release skips CI when the
pull request already passed for this commit, and the PR CI no longer
builds images (the release builds once per input hash and smoke-tests
before publishing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:47:18 -03:00
51 changed files with 2032 additions and 376 deletions

No files matched your search

+2 -17
View File
@@ -80,20 +80,5 @@ jobs:
export PATH="$PATH:$(go env GOPATH)/bin"
govulncheck ./...
image:
name: Docker images (build and smoke test)
if: ${{ gitea.event_name == 'pull_request' }}
runs-on: linux-arm64
steps:
- uses: actions/checkout@v7
- name: Build hub
run: docker build --target hub -t "urutau-ci:${{ gitea.run_id }}" .
- name: Build probe
run: docker build --target probe -t "urutau-probe-ci:${{ gitea.run_id }}" .
- name: Smoke test (hub)
run: scripts/smoke-image.sh "urutau-ci:${{ gitea.run_id }}"
- name: Smoke test (probe, under 15 MB)
run: scripts/smoke-probe.sh "urutau-probe-ci:${{ gitea.run_id }}"
- name: Clean up
if: always()
run: docker rmi -f "urutau-ci:${{ gitea.run_id }}" "urutau-probe-ci:${{ gitea.run_id }}" >/dev/null 2>&1 || true
# No image build here: the release builds each image once per input hash,
# natively per architecture, and smoke-tests it before publishing any tag.
+25 -3
View File
@@ -12,8 +12,11 @@ on:
tags: ['v*']
workflow_dispatch:
# One queue for main and tags: a tag pushed together with main waits for the
# main run, then finds the images already published and only re-points tags.
# (A per-ref group let both runs plan at once, see nothing, and build twice.)
concurrency:
group: release-${{ gitea.ref }}
group: release
cancel-in-progress: false
env:
@@ -29,6 +32,7 @@ jobs:
outputs:
inputs: ${{ steps.plan.outputs.inputs }}
reuse: ${{ steps.plan.outputs.reuse }}
tested: ${{ steps.tested.outputs.tested }}
image: ${{ steps.plan.outputs.image }}
probe_image: ${{ steps.plan.outputs.probe_image }}
steps:
@@ -56,10 +60,25 @@ jobs:
echo "reuse=$reuse" >> "$GITHUB_OUTPUT"
echo "image=$REGISTRY/$ns" >> "$GITHUB_OUTPUT"
echo "probe_image=$REGISTRY/$ns-probe" >> "$GITHUB_OUTPUT"
# The pull request already ran the whole CI on this exact commit (the
# merge is a fast-forward): do not run the same tests again here.
- id: tested
env:
REPO: ${{ gitea.repository }}
SHA: ${{ gitea.sha }}
# The job token reads this repository's runs; on any error the answer
# is false and the CI simply runs (never skips tests by mistake).
TOKEN: ${{ gitea.token }}
run: |
tested=$(curl -fsS -H "Authorization: token $TOKEN" "https://$REGISTRY/api/v1/repos/$REPO/actions/runs?limit=50" \
| jq -r --arg sha "$SHA" '[.workflow_runs[] | select(.head_sha == $sha and (.path | startswith("ci.yml")) and .conclusion == "success")] | length > 0' 2>/dev/null) || tested=false
[ "$tested" = true ] || tested=false
echo "CI already passed for $SHA: $tested"
echo "tested=$tested" >> "$GITHUB_OUTPUT"
ci:
needs: plan
if: ${{ needs.plan.outputs.reuse != 'true' }}
if: ${{ needs.plan.outputs.reuse != 'true' && needs.plan.outputs.tested != 'true' }}
uses: ./.gitea/workflows/ci.yml
# Each architecture of each image is built on a native runner (no QEMU) and
@@ -67,7 +86,10 @@ jobs:
build:
name: Build ${{ matrix.target }} image (${{ matrix.arch }})
needs: [plan, ci]
if: ${{ needs.plan.outputs.reuse != 'true' }}
# ci is skipped (not failed) when the pull request already tested this commit.
# A skipped reusable-workflow job does not report result == 'skipped' on
# Gitea, so test for "did not fail and was not cancelled" instead.
if: ${{ !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.reuse != 'true' && needs.ci.result != 'failure' && needs.ci.result != 'cancelled' }}
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
+55 -1
View File
@@ -6,6 +6,58 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [2.2.2] - 2026-11-19
### Fixed
- Outbound traffic: a redeploy that swapped addresses between containers (LambdaMail's rspamd and clamav traded 172.19.0.2 and .5) was judged with the previous minute's `containers.map`, so findings landed on the wrong workload (rspamd's SURBL and DNS traffic as `clamav`, freshclam as `dns`). The host kit now also runs `urutau-containers-watch`, which rewrites the map on every container start or network attach, and the probe checks the file every 2 seconds instead of 10. Reinstall the host kit (`deploy/host/install.sh`) and update the probes.
- Outbound traffic: `new_geo` no longer fires for large CDNs and clouds (Cloudflare, Google, AWS, Azure, Akamai, Fastly, Telegram): their addresses are anycast or global, and the database country (1.1.1.1 in Australia, a Cloudflare edge in Canada) says nothing about where the traffic goes. Test `TestNewGeoSkipsAnycastCDN`.
## [2.2.1] - 2026-11-16
### Fixed
- Traffic on probe-fed hosts kept disappearing after Traefik's copytruncate rotation even with 2.2.0: the head fingerprint covered only 64 bytes, and Traefik's first line of every generation starts with the same keep-alive client address and port, so every generation looked like the same file and the hub dropped every line below the previous high-water mark. The fingerprint now covers up to 1024 bytes (the whole first line, with its nanosecond timestamp), and the hub treats fingerprints of different lengths as different generations. Update the probes too. Tests `TestHeadCoversFirstLine` and `TestSameHeadCopytruncate`.
## [2.2.0] - 2026-11-16
### Added
- IP analysis: an address that never attacked but is an egress destination (for example the IP of an egress incident) now opens a "Destination" view: which hosts and workloads connected to it, ports, connections, ASN/country, findings and linked incidents. New endpoint `GET /api/v1/ip/{ip}/egress`. When nothing exists the page says definitively that the IP was never seen; if it was seen inbound outside the period it shows the last date and a 30-day button.
- Global host filter: several probes can be selected at once (`host=oracle,hostinger` in the URL and the API); selecting all of them, or "All hosts", means every probe.
### Fixed
- Traffic: the hub dropped Traefik lines after every copytruncate rotation of `access.log` (it compared only inode and offset and ignored the head fingerprint the probe sends), so legitimate traffic on the Oracle host vanished for hours after each rotation. Regression test `TestSameHeadCopytruncate`.
- Global host filter: going back to "All hosts" did nothing, because the URL without `host=` kept the previous host.
## [2.1.2] - 2026-11-16
### Fixed
- Egress, false `dns_bypass` right after a hub restart: the files a probe sends (`resolv.conf`, `containers.map`) lived only in the hub's memory, so after a restart the egress lines the probe replayed on reconnect were judged before the probe sent them again (Hostinger `coolify-sentinel` → its upstream resolver 153.92.2.6, hostinger/INC-8). The hub now keeps the last copy of each file in the node's data directory (`probe-resolv.conf`, `probe-containers.map`) and loads it at start. Regression test `TestProbeFilesSurviveRestart`.
- Phone layout: the global filter sheet (period and host) opens above the bottom tab bar instead of covering it, tapping the tab bar closes it, and the sticky filter bar no longer sits on top of the "More" menu.
## [2.1.1] - 2026-11-16
### Fixed
- Incidents: the status tabs (Active, All, Open, False positive and so on) no longer show a tiny vertical scrollbar; the active tab's underline no longer overflows the scroll area by one pixel, and the focus ring is drawn inside the tab so it is not clipped.
## [2.1.0] - 2026-11-16
### Fixed
- Egress, false `dns_bypass` on probes: the hub judged the egress lines of a batch before applying the `resolv.conf` (and `containers.map`) sent in the same batch, and rebuilding a probe's egress engine (a configuration change) dropped those files. The hub now keeps the last files of each probe, applies them before the lines and to every rebuilt engine; the probe queues them before it starts reading logs. Regression test `TestEgressFilesAppliedBeforeLines`.
- Replay: the Repeat control is a regular toggle in the transport bar, styled and behaving like Compress, Only incidents and Select.
- IP analysis: long domains wrap at their dots instead of mid-label.
### Changed
- Incidents page redesigned: severity in words, host-qualified IDs that no longer overlap the title, occurrences and comment counts in the list, phone cards, a clear detail header, a timeline for activity, and a dedicated suppression block that shows the end date, lets you pick 7, 30 or 90 days, and explains why it is disabled (non-egress, high/critical, or status).
- Global filter bar redesigned: one period control (relative presets and an exact window with date pickers, validated against the 30-day retention), visible time zone, previous/next window, a host picker with probe status, a live/fixed indicator, Clear filters and Copy link, sticky and compact while scrolling, bottom sheets on phones, full keyboard and screen reader support. Its classes no longer collide with the replay page.
- IP analysis page rebuilt: identity header, a four-answer summary (what, when, against what, blocked?), a sticky section bar, per-host defense status with unban, ban history table, raw events in their own section with a category filter, and no truncated text at any width.
## [2.0.0] - 2026-11-15
Breaking release: read [docs/migration-2.0.md](docs/migration-2.0.md) before upgrading.
@@ -291,7 +343,9 @@ First release.
- Hostile log content is limited in length and escaped on output; the dashboard ships a strict Content-Security-Policy and the usual hardening headers.
- `--insecure-no-auth` is refused unless the bind address is loopback.
[Unreleased]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...HEAD
[Unreleased]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.1...HEAD
[2.1.1]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.0...v2.1.1
[2.1.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...v2.1.0
[2.0.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...v2.0.0
[1.6.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.5.7...v1.6.0
[1.5.8]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/commit/bc3ce09
+55 -1
View File
@@ -6,6 +6,58 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Não lançado]
## [2.2.2] - 2026-11-19
### Corrigido
- Tráfego de saída: um redeploy que trocou endereços entre contêineres (o rspamd e o clamav do LambdaMail trocaram 172.19.0.2 e .5) era julgado com o `containers.map` do minuto anterior, e os achados caíam no workload errado (SURBL e DNS do rspamd como `clamav`, freshclam como `dns`). O kit do host agora também roda o `urutau-containers-watch`, que regrava o mapa a cada contêiner que sobe ou entra numa rede, e a sonda confere o arquivo a cada 2 segundos em vez de 10. Reinstale o kit do host (`deploy/host/install.sh`) e atualize as sondas.
- Tráfego de saída: `new_geo` não dispara mais para grandes CDNs e nuvens (Cloudflare, Google, AWS, Azure, Akamai, Fastly, Telegram): os endereços são anycast ou globais, e o país da base (1.1.1.1 na Austrália, uma borda da Cloudflare no Canadá) nada diz sobre o destino do tráfego. Teste `TestNewGeoSkipsAnycastCDN`.
## [2.2.1] - 2026-11-16
### Corrigido
- O tráfego dos hosts alimentados por sonda continuava sumindo depois da rotação copytruncate do Traefik mesmo na 2.2.0: a impressão digital do início do arquivo cobria só 64 bytes, e a primeira linha de cada geração do Traefik começa com o mesmo endereço e porta de uma conexão keep-alive, então toda geração parecia o mesmo arquivo e o hub descartava as linhas abaixo da marca anterior. A impressão digital agora cobre até 1024 bytes (a primeira linha inteira, com carimbo de tempo em nanossegundos), e o hub trata impressões de tamanhos diferentes como gerações diferentes. Atualize também as sondas. Testes `TestHeadCoversFirstLine` e `TestSameHeadCopytruncate`.
## [2.2.0] - 2026-11-16
### Adicionado
- Análise de IP: um endereço que nunca atacou mas é destino de saída (por exemplo o IP de um incidente de egress) agora abre a vista "Destino de saída": quais hosts e cargas de trabalho se conectaram, portas, conexões, ASN/país, achados e incidentes ligados. Endpoint novo `GET /api/v1/ip/{ip}/egress`. Quando não há nada, a página diz de forma definitiva que o IP nunca foi visto; se foi visto como origem fora do período, mostra a última data e um botão de 30 dias.
- Filtro global de host: várias sondas podem ser selecionadas ao mesmo tempo (`host=oracle,hostinger` na URL e na API); marcar todas, ou "Todos os hosts", significa todas as sondas.
### Corrigido
- Tráfego: o hub descartava linhas do Traefik depois de cada rotação copytruncate do `access.log` (comparava só inode e offset e ignorava a impressão digital do início que a sonda envia), então o tráfego legítimo do host Oracle sumia por horas após cada rotação. Teste de regressão `TestSameHeadCopytruncate`.
- Filtro global de host: voltar para "Todos os hosts" não fazia nada, porque a URL sem `host=` mantinha o host anterior.
## [2.1.2] - 2026-11-16
### Corrigido
- Saída, `dns_bypass` falso logo após reiniciar o hub: os arquivos que a sonda envia (`resolv.conf`, `containers.map`) ficavam só na memória do hub, então depois de um reinício as linhas de saída que a sonda reenviava ao reconectar eram julgadas antes de ela mandar os arquivos de novo (`coolify-sentinel` da Hostinger → o resolvedor upstream 153.92.2.6, hostinger/INC-8). O hub agora guarda a última cópia de cada arquivo no diretório do nó (`probe-resolv.conf`, `probe-containers.map`) e a carrega na inicialização. Teste de regressão `TestProbeFilesSurviveRestart`.
- Celular: a folha de filtros globais (período e host) abre acima da barra de navegação inferior em vez de cobri-la, tocar na barra a fecha, e a barra de filtros fixa não fica mais por cima do menu "Mais".
## [2.1.1] - 2026-11-16
### Corrigido
- Incidentes: as abas de status (Ativos, Todos, Aberto, Falso positivo etc.) não mostram mais uma barra de rolagem vertical minúscula; o sublinhado da aba ativa não passa mais 1 px da área rolável, e o anel de foco é desenhado dentro da aba para não ser cortado.
## [2.1.0] - 2026-11-16
### Corrigido
- Egress, falso `dns_bypass` nas sondas: o hub julgava as linhas de egress de um lote antes de aplicar o `resolv.conf` (e o `containers.map`) enviado no mesmo lote, e recriar o engine de egress de uma sonda (mudança de configuração) perdia esses arquivos. Agora o hub guarda os últimos arquivos de cada sonda e os aplica antes das linhas e em todo engine recriado; a sonda os enfileira antes de começar a ler os logs. Teste de regressão `TestEgressFilesAppliedBeforeLines`.
- Replay: o controle Repetir é um alternador comum na barra de transporte, com o mesmo visual e comportamento de Comprimir, Só incidentes e Selecionar.
- Análise de IP: domínios longos quebram nos pontos, não no meio de um rótulo.
### Alterado
- Página de incidentes redesenhada: severidade por extenso, IDs qualificados pelo host que não sobrepõem mais o título, ocorrências e comentários na lista, cartões no celular, cabeçalho de detalhe claro, linha do tempo da atividade e um bloco próprio de supressão que mostra a data de fim, permite escolher 7, 30 ou 90 dias e explica por que está desativado (não é egress, é alta/crítica ou o status).
- Barra de filtros global redesenhada: um controle de período (atalhos relativos e janela exata com calendário, validada contra a retenção de 30 dias), fuso visível, janela anterior/seguinte, seletor de host com o status das sondas, indicador ao vivo/fixo, Limpar filtros e Copiar link, fixa e compacta ao rolar, painel inferior no celular, teclado e leitor de tela completos. As classes não colidem mais com a página de replay.
- Página de análise de IP refeita: cabeçalho de identidade, resumo em quatro respostas (o que, quando, contra o quê, bloqueado?), barra de seções fixa, situação de defesa por host com desbanir, tabela de histórico de bans, eventos brutos em seção própria com filtro por categoria e nenhum texto cortado em qualquer largura.
## [2.0.0] - 2026-11-15
Versão com quebra de compatibilidade: leia [docs/pt-BR/migracao-2.0.md](docs/pt-BR/migracao-2.0.md) antes de atualizar.
@@ -291,7 +343,9 @@ Primeira versão.
- O conteúdo hostil dos logs tem tamanho limitado e é escapado na saída; o dashboard envia uma Content-Security-Policy estrita e os cabeçalhos de endurecimento usuais.
- `--insecure-no-auth` é recusado a menos que o endereço de bind seja loopback.
[Não lançado]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...HEAD
[Não lançado]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.1...HEAD
[2.1.1]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.1.0...v2.1.1
[2.1.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v2.0.0...v2.1.0
[2.0.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.6.0...v2.0.0
[1.6.0]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/compare/v1.5.7...v1.6.0
[1.5.8]: https://git.lucasrguerra.dev.br/ciberfauna/urutau/commit/bc3ce09
+1 -1
View File
@@ -87,7 +87,7 @@ It never blocks trusted addresses, private ranges, CDN (Cloudflare) and public r
## Outbound traffic and incidents
Optional (`URUTAU_EGRESS=auto|on|off`; `auto` turns it on for a probe that sends the outbound log). The host kit logs only new TCP connection attempts through nftables, and a container map names the workloads. Urutau checks them for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or with Tor relays, DNS outside the allowed resolvers (`URUTAU_EGRESS_RESOLVERS`), unauthorised outbound scans and new countries. Workloads are defined by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload. The servers themselves, peers and the host's own provider never raise findings, cloud metadata services polled by the host are `infra`, and regular connections to large CDNs and clouds are low severity.
Optional (`URUTAU_EGRESS=auto|on|off`; `auto` turns it on for a probe that sends the outbound log). The host kit logs only new TCP connection attempts through nftables, and a container map names the workloads. Urutau checks them for beaconing (regular conversations with one destination), mining, IRC and SMTP ports, contact with addresses that attacked the server or with Tor relays, DNS outside the allowed resolvers (`URUTAU_EGRESS_RESOLVERS`), unauthorised outbound scans and new countries. Workloads are defined by network or container name (`URUTAU_EGRESS_WORKLOADS`); a `scanner` workload (an authorised surface scanner) has only its scan-shaped traffic summarised, everything else is judged like any other workload. The servers themselves, peers and the host's own provider never raise findings, cloud metadata services polled by the host are `infra`, and regular connections to large CDNs and clouds are low severity, and they never raise a new country (their database country means nothing for anycast).
Every finding above info severity becomes a ticket `INC-<n>` (list, ticket page, manual tickets, CSV export, `/api/v1/incidents`). A ticket marked `false_positive` or `benign` can suppress findings with exactly its key; a resolved ticket reopens if the finding comes back.
+1 -1
View File
@@ -87,7 +87,7 @@ Nunca bloqueia endereços confiáveis, faixas privadas, faixas de CDN (Cloudflar
## Tráfego de saída e incidentes
Opcional (`URUTAU_EGRESS=auto|on|off`; `auto` liga para a sonda que envia o log de saída). O kit de host registra, pelo nftables, só tentativas novas de conexão TCP, e um mapa de contêineres nomeia os workloads. O Urutau checa beaconing (conversas regulares com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou com relays Tor, DNS fora dos resolvers permitidos (`URUTAU_EGRESS_RESOLVERS`), varreduras de saída não autorizadas e países novos. Os workloads são definidos por nome de rede ou de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (um scanner de superfície autorizado) tem só o tráfego em forma de varredura resumido, o resto é julgado como qualquer outro workload. Os próprios servidores, peers e o provedor do host nunca geram achados, serviços de metadados de nuvem consultados pelo host são `infra`, e conexões regulares a grandes CDNs e nuvens têm severidade baixa.
Opcional (`URUTAU_EGRESS=auto|on|off`; `auto` liga para a sonda que envia o log de saída). O kit de host registra, pelo nftables, só tentativas novas de conexão TCP, e um mapa de contêineres nomeia os workloads. O Urutau checa beaconing (conversas regulares com um destino), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou com relays Tor, DNS fora dos resolvers permitidos (`URUTAU_EGRESS_RESOLVERS`), varreduras de saída não autorizadas e países novos. Os workloads são definidos por nome de rede ou de contêiner (`URUTAU_EGRESS_WORKLOADS`); um workload `scanner` (um scanner de superfície autorizado) tem só o tráfego em forma de varredura resumido, o resto é julgado como qualquer outro workload. Os próprios servidores, peers e o provedor do host nunca geram achados, serviços de metadados de nuvem consultados pelo host são `infra`, e conexões regulares a grandes CDNs e nuvens têm severidade baixa e nunca geram país novo (o país da base nada diz sobre anycast).
Todo achado acima de info vira um chamado `INC-<n>` (lista, página do chamado, chamados manuais, exportação CSV, `/api/v1/incidents`). Um chamado marcado `false_positive` ou `benign` pode suprimir achados com exatamente a sua chave; um chamado resolvido reabre se o achado voltar.
+6 -3
View File
@@ -35,9 +35,10 @@ done
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
if [ "$remove" = 1 ]; then
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
systemctl disable --now urutau-egress.service urutau-containers-watch.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
/etc/systemd/system/urutau-containers-watch.service /usr/local/sbin/urutau-containers-watch \
/etc/rsyslog.d/41-urutau-egress.conf /etc/logrotate.d/urutau-egress \
/etc/fail2ban/jail.d/urutau.local /etc/fail2ban/filter.d/urutau.conf /etc/fail2ban/action.d/urutau-allports.conf \
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer \
@@ -62,14 +63,16 @@ nft -c -f /etc/urutau/egress.nft
install -m 0644 "$here/41-urutau-egress.conf" /etc/rsyslog.d/41-urutau-egress.conf
install -m 0644 "$here/urutau.logrotate" /etc/logrotate.d/urutau-egress
install -m 0755 "$here/urutau-containers-map" /usr/local/sbin/urutau-containers-map
install -m 0755 "$here/urutau-containers-watch" /usr/local/sbin/urutau-containers-watch
install -m 0644 "$here/urutau-egress.service" "$here/urutau-containers-map.service" \
"$here/urutau-containers-map.timer" "$here/urutau-logrotate.service" "$here/urutau-logrotate.timer" /etc/systemd/system/
"$here/urutau-containers-map.timer" "$here/urutau-containers-watch.service" "$here/urutau-logrotate.service" "$here/urutau-logrotate.timer" /etc/systemd/system/
systemctl daemon-reload
systemctl restart rsyslog
systemctl enable urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer >/dev/null
systemctl enable urutau-egress.service urutau-containers-map.timer urutau-containers-watch.service urutau-logrotate.timer >/dev/null
systemctl start urutau-logrotate.timer
systemctl restart urutau-egress.service
systemctl start urutau-containers-map.service urutau-containers-map.timer
systemctl restart urutau-containers-watch.service
echo "egress logging on $wan: /var/log/urutau/egress.log, map: /var/log/urutau/containers.map"
if [ "$probe" = 1 ] && [ "$enforce" = 0 ]; then
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# Urutau: rewrites containers.map as soon as Docker attaches a container to a
# network, so a redeploy that swaps addresses between containers is not judged
# with the old names until the next minute of the timer.
set -u
docker events --filter type=network --filter event=connect --filter type=container --filter event=start --format '{{.Type}}' |
while read -r _; do
/usr/local/sbin/urutau-containers-map || true
# a stack redeploy fires dozens of events: drain the burst, then refresh once more
n=0
while read -r -t 1 _; do n=$((n + 1)); done
[ "$n" -gt 0 ] && { /usr/local/sbin/urutau-containers-map || true; }
done
@@ -0,0 +1,12 @@
[Unit]
Description=Urutau: refresh the container map when containers start
After=docker.service
Requires=docker.service
[Service]
ExecStart=/usr/local/sbin/urutau-containers-watch
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target
+1 -1
View File
@@ -96,7 +96,7 @@ The probe has only these variables (flags in [cli.md](cli.md#urutau-probe)). A p
| `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | fail2ban log |
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | kernel log of connections to unserved ports, written by the host kit (see [Probes](#probes-port-scans)) |
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | kernel log of new outbound connections, written by the host kit |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit every minute, so workloads keep their name when the address changes on a redeploy; sent whole when it changes |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | `"<ip> <container>"` map written by the host kit when a container starts (and every minute), so workloads keep their name when the address changes on a redeploy; sent whole when it changes |
| `URUTAU_RESOLV` | `/etc/resolv.conf` of the host (mounted) | resolvers of the host, sent whole when it changes |
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | file where the ban decisions of the hub are appended, read by the host jail; empty ignores ban commands and counts them as errors |
| `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | file where unban requests are appended, read by the host; empty ignores them |
+1 -1
View File
@@ -179,7 +179,7 @@ It is idempotent. `URUTAU_WAN` overrides the detected uplink interface and `URUT
|---|---|
| egress logging | nftables table `inet urutau_egress` (`/etc/urutau/egress.nft`, only logs, never drops, separate from the Docker and fail2ban tables) and the `urutau-egress.service` unit; rsyslog rule `41-urutau-egress.conf` sends the kernel lines to `/var/log/urutau/egress.log` (`URUTAU-EGRESS:`) and `/var/log/urutau/probe.log` (`URUTAU-PROBE:`); logrotate daily, 7 copies, at most 200 MB (`urutau-logrotate.timer`) |
| probes | the `URUTAU-PROBE:` rule logs new inbound connections on the uplink to ports no socket listens on (at most 10 per second per source); the set of open ports is refreshed every minute from `ss`, including ports Docker publishes |
| container map | `urutau-containers-map` and its timer (every minute) write `/var/log/urutau/containers.map` (`<ip> <container>`) and `/var/log/urutau/resolv.conf` (the real upstream resolvers) |
| container map | `urutau-containers-map`, run by its timer (every minute) and by `urutau-containers-watch` (on every container start or network attach, so a redeploy that swaps addresses is named right within seconds), writes `/var/log/urutau/containers.map` (`<ip> <container>`) and `/var/log/urutau/resolv.conf` (the real upstream resolvers) |
| second firewall (`--enforce`) | directory `/var/log/urutau-enforce` (owned by `URUTAU_UID`, group `adm`) with `decisions.log` and `unban.log`; fail2ban filter `urutau`, action `urutau-allports` and jail `urutau` (`polling` backend, `maxretry = 1`, `bantime = 1h`, actions on `INPUT` and `DOCKER-USER`, host `ignoreip` kept); `urutau-unban.path` and `urutau-unban` apply the Unban button |
The `urutau-allports` action behaves like `iptables-allports` but only drops connections the banned address starts (conntrack original direction), so replies to connections the host opened keep flowing. The egress and probe files land in `/var/log/urutau`, which the probe compose file already mounts at `/logs/host`, so the probe finds them at its defaults (`URUTAU_EGRESS=auto` turns on by itself once the file exists). For the second firewall add the mount and the variables to the compose file, start with `observe` and move to `on` when the decisions look right:
+1 -1
View File
@@ -81,7 +81,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
<p align="center"><img src="img/incidents-dark.png" width="900" alt="Page: Incidents"><br><sub>Incidents: tickets for outbound-traffic findings.</sub></p>
<p align="center"><img src="img/incident-detail-dark.png" width="900" alt="Page: Incident ticket"><br><sub>Incident ticket: summary, activity timeline and properties.</sub></p>
**Outbound traffic** (`#/egress`, needs `URUTAU_EGRESS` and the host kit in `deploy/host` on a probe): the new outbound connections of the host and containers, logged by nftables, analysed for beaconing (regular conversations with one destination, with the interval histogram), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor relays, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. It shows a plain-language verdict, evidence cards, a destination map, activity by hour, compact workloads (by network or container name, `URUTAU_EGRESS_WORKLOADS`; a `scanner` workload has only its scan-shaped traffic summarised) and the timeline of authorised scans. Servers themselves, probes and the host's own provider never raise findings; regular connections to large CDNs and clouds are low severity.
**Outbound traffic** (`#/egress`, needs `URUTAU_EGRESS` and the host kit in `deploy/host` on a probe): the new outbound connections of the host and containers, logged by nftables, analysed for beaconing (regular conversations with one destination, with the interval histogram), mining, IRC and SMTP ports, contact with addresses that attacked the server or Tor relays, DNS outside the allowed resolvers, unauthorised outbound scans and new countries. It shows a plain-language verdict, evidence cards, a destination map, activity by hour, compact workloads (by network or container name, `URUTAU_EGRESS_WORKLOADS`; a `scanner` workload has only its scan-shaped traffic summarised) and the timeline of authorised scans. Servers themselves, probes and the host's own provider never raise findings; regular connections to large CDNs and clouds are low severity, and they never raise a new country (anycast).
<p align="center"><img src="img/egress-dark.png" width="900" alt="Page: Outbound traffic"><br><sub>Outbound traffic: scan bursts, beacons and mining from containers.</sub></p>
+1 -1
View File
@@ -96,7 +96,7 @@ A sonda usa só estas variáveis (flags em [cli.md](cli.md#urutau-probe)). Um ca
| `URUTAU_FAIL2BAN_LOG` | `/logs/host/fail2ban.log` | log do fail2ban |
| `URUTAU_PROBE_LOG` | `/logs/host/probe.log` | log do kernel de conexões a portas que ninguém serve, gravado pelo kit do host (veja [Sondagens](#sondagens-varreduras-de-portas)) |
| `URUTAU_EGRESS_LOG` | `/logs/host/egress.log` | log do kernel de conexões novas de saída, gravado pelo kit do host |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host a cada minuto, para que as cargas mantenham o nome quando o endereço muda num redeploy; enviado inteiro quando muda |
| `URUTAU_EGRESS_CONTAINERS` | `/logs/host/containers.map` | mapa `"<ip> <container>"` gravado pelo kit do host quando um contêiner sobe (e a cada minuto), para que as cargas mantenham o nome quando o endereço muda num redeploy; enviado inteiro quando muda |
| `URUTAU_RESOLV` | `/etc/resolv.conf` do host (montado) | resolvedores do host, enviados inteiros quando mudam |
| `URUTAU_ENFORCE_LOG` | `/logs/enforce/decisions.log` | arquivo onde as decisões de ban do hub são acrescentadas, lido pela jail do host; vazio ignora comandos de ban e os conta como erro |
| `URUTAU_ENFORCE_UNBAN_LOG` | `/logs/enforce/unban.log` | arquivo onde os pedidos de desban são acrescentados, lido pelo host; vazio os ignora |
+1 -1
View File
@@ -179,7 +179,7 @@ sudo sh deploy/host/install.sh --remove # desfaz tudo (os logs são mantidos)
|---|---|
| registro de egress | tabela nftables `inet urutau_egress` (`/etc/urutau/egress.nft`, só registra, nunca descarta, separada das tabelas do Docker e do fail2ban) e a unit `urutau-egress.service`; a regra rsyslog `41-urutau-egress.conf` manda as linhas do kernel para `/var/log/urutau/egress.log` (`URUTAU-EGRESS:`) e `/var/log/urutau/probe.log` (`URUTAU-PROBE:`); logrotate diário, 7 cópias, no máximo 200 MB (`urutau-logrotate.timer`) |
| sondagens | a regra `URUTAU-PROBE:` registra conexões novas de entrada pela interface externa a portas em que nenhum socket escuta (no máximo 10 por segundo por origem); o conjunto de portas abertas é atualizado a cada minuto a partir do `ss`, incluindo as portas que o Docker publica |
| mapa de containers | `urutau-containers-map` e seu timer (a cada minuto) gravam `/var/log/urutau/containers.map` (`<ip> <container>`) e `/var/log/urutau/resolv.conf` (os resolvedores reais de upstream) |
| mapa de containers | `urutau-containers-map`, executado pelo timer (a cada minuto) e pelo `urutau-containers-watch` (a cada contêiner que sobe ou entra numa rede, para que um redeploy que troca endereços seja nomeado certo em segundos), grava `/var/log/urutau/containers.map` (`<ip> <container>`) e `/var/log/urutau/resolv.conf` (os resolvedores reais de upstream) |
| segundo firewall (`--enforce`) | diretório `/var/log/urutau-enforce` (dono `URUTAU_UID`, grupo `adm`) com `decisions.log` e `unban.log`; filtro `urutau`, ação `urutau-allports` e jail `urutau` do fail2ban (backend `polling`, `maxretry = 1`, `bantime = 1h`, ações em `INPUT` e `DOCKER-USER`, `ignoreip` do host mantido); `urutau-unban.path` e `urutau-unban` aplicam o botão Desbanir |
A ação `urutau-allports` funciona como `iptables-allports`, mas só descarta conexões que o endereço banido inicia (direção original do conntrack), então as respostas a conexões que o host abriu continuam fluindo. Os arquivos de egress e sondagem caem em `/var/log/urutau`, que o compose já monta em `/logs/host`, então a sonda os encontra nos padrões (`URUTAU_EGRESS=auto` liga sozinho assim que o arquivo existe). Para o segundo firewall, acrescente a montagem e as variáveis ao compose, comece com `observe` e passe para `on` quando as decisões parecerem certas:
+1 -1
View File
@@ -81,7 +81,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
<p align="center"><img src="../img/incidents-dark-pt.png" width="900" alt="Página: Incidentes"><br><sub>Incidentes: chamados para achados do tráfego de saída.</sub></p>
<p align="center"><img src="../img/incident-detail-dark-pt.png" width="900" alt="Página: Chamado de incidente"><br><sub>Chamado de incidente: resumo, linha do tempo de atividade e propriedades.</sub></p>
**Tráfego de saída** (`#/egress`, exige `URUTAU_EGRESS` e o kit de host em `deploy/host` numa sonda): as novas conexões de saída do host e dos contêineres, registradas pelo nftables, analisadas quanto a beaconing (conversas regulares com um destino, com o histograma de intervalos), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou relays Tor, DNS fora dos resolvers permitidos, varreduras de saída não autorizadas e países novos. Mostra um veredito em linguagem simples, cartões de evidência, mapa de destinos, atividade por hora, workloads compactos (por nome de rede ou contêiner, `URUTAU_EGRESS_WORKLOADS`; um workload `scanner` tem só o tráfego em forma de varredura resumido) e a linha do tempo das varreduras autorizadas. Os próprios servidores, sondas e o provedor do host nunca geram achados; conexões regulares a grandes CDNs e nuvens têm severidade baixa.
**Tráfego de saída** (`#/egress`, exige `URUTAU_EGRESS` e o kit de host em `deploy/host` numa sonda): as novas conexões de saída do host e dos contêineres, registradas pelo nftables, analisadas quanto a beaconing (conversas regulares com um destino, com o histograma de intervalos), mineração, portas de IRC e SMTP, contato com endereços que atacaram o servidor ou relays Tor, DNS fora dos resolvers permitidos, varreduras de saída não autorizadas e países novos. Mostra um veredito em linguagem simples, cartões de evidência, mapa de destinos, atividade por hora, workloads compactos (por nome de rede ou contêiner, `URUTAU_EGRESS_WORKLOADS`; um workload `scanner` tem só o tráfego em forma de varredura resumido) e a linha do tempo das varreduras autorizadas. Os próprios servidores, sondas e o provedor do host nunca geram achados; conexões regulares a grandes CDNs e nuvens têm severidade baixa e nunca geram país novo (anycast).
<p align="center"><img src="../img/egress-dark-pt.png" width="900" alt="Página: Tráfego de saída"><br><sub>Tráfego de saída: rajadas de varredura, beacons e mineração em contêineres.</sub></p>
+68 -12
View File
@@ -63,6 +63,11 @@ type Node struct {
egrSrc atomic.Pointer[egress.Source]
egrActive atomic.Bool
sources atomic.Pointer[[]string]
// Last containers.map / resolv.conf the probe sent. The probe resends them
// only when they change, so they are kept here and applied to every engine
// this node builds (a configuration change rebuilds the engine).
containers atomic.Pointer[[]byte]
resolv atomic.Pointer[[]byte]
}
func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, error) {
@@ -119,6 +124,7 @@ func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, erro
sh.wg.Add(1)
go func() { defer sh.wg.Done(); n.Enf.Run(sh.ctx) }()
}
n.loadProbeFiles()
if !egressOff(c) {
if err := n.buildEgress(rec.Egress); err != nil {
return nil, err
@@ -184,11 +190,52 @@ func (n *Node) Close() {
}
}
// probeFilePath is where the last copy of a file sent by the probe is kept,
// so that after a hub restart the egress lines replayed by the probe are
// judged with its resolvers and container names before it sends them again.
func (n *Node) probeFilePath(name string) string {
return filepath.Join(n.Dir, "probe-"+name)
}
func (n *Node) loadProbeFiles() {
for _, f := range []struct {
name string
dst *atomic.Pointer[[]byte]
}{{wire.FileContainers, &n.containers}, {wire.FileResolv, &n.resolv}} {
b, err := os.ReadFile(n.probeFilePath(f.name))
if err != nil || len(b) > wire.MaxFileBytes {
continue
}
f.dst.Store(&b)
}
}
func (n *Node) saveProbeFile(name string, data []byte) {
p := n.probeFilePath(name)
if old, err := os.ReadFile(p); err == nil && string(old) == string(data) {
return
}
tmp := p + ".tmp"
if err := os.WriteFile(tmp, data, 0o600); err != nil {
n.sh.log.Warn("probe file not saved", "node", n.name, "file", name, "err", err)
return
}
if err := os.Rename(tmp, p); err != nil {
n.sh.log.Warn("probe file not saved", "node", n.name, "file", name, "err", err)
}
}
func (n *Node) buildEgress(eg hub.Egress) error {
eng, err := newEgressEngine(n.sh.c, n.St, eg, n.Primary)
if err != nil {
return err
}
if b := n.containers.Load(); b != nil {
eng.SetContainers(*b)
}
if b := n.resolv.Load(); b != nil {
eng.SetResolv(*b)
}
n.egr.Store(eng)
n.egrSrc.Store(egress.NewRemoteSource(eng, n.sh.log))
n.egrSrc.Load().SetState("waiting")
@@ -240,6 +287,27 @@ func (n *Node) Ready() bool { return true }
func (n *Node) Offsets() map[string]wire.Pos { return n.Run.RemoteOffsets() }
func (n *Node) Apply(b wire.Batch) (int, int) {
// Files first: egress lines of this very batch must be judged with the
// resolvers and container names that came with them.
for _, f := range b.Files {
data := []byte(f.Data)
switch f.Name {
case wire.FileContainers:
n.containers.Store(&data)
case wire.FileResolv:
n.resolv.Store(&data)
default:
continue
}
n.saveProbeFile(f.Name, data)
if e := n.egr.Load(); e != nil {
if f.Name == wire.FileContainers {
e.SetContainers(data)
} else {
e.SetResolv(data)
}
}
}
acc, dup := n.Run.ApplyBatch(b.Lines)
if acc > 0 {
for _, l := range b.Lines {
@@ -249,18 +317,6 @@ func (n *Node) Apply(b wire.Batch) (int, int) {
}
}
}
for _, f := range b.Files {
e := n.egr.Load()
if e == nil {
continue
}
switch f.Name {
case wire.FileContainers:
e.SetContainers([]byte(f.Data))
case wire.FileResolv:
e.SetResolv([]byte(f.Data))
}
}
return acc, dup
}
+17
View File
@@ -82,3 +82,20 @@ func TestProbeSourceMissingIsWaiting(t *testing.T) {
}
_ = time.Now
}
func TestSameHeadCopytruncate(t *testing.T) {
old := store.Offset{Inode: 7, Offset: 900, FP: 111, FPLen: 64}
if !sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 111, FPLen: 64}) {
t.Fatal("same generation must be a duplicate")
}
if sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 222, FPLen: 64}) {
t.Fatal("truncated and regrown file must not be a duplicate")
}
// production 2026-11-16: the saved head had 64 bytes, the new probe sends longer ones
if sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 333, FPLen: 1024}) {
t.Fatal("fingerprints of different lengths must not be taken for the same file")
}
if !sameHead(store.Offset{Inode: 7, Offset: 900}, store.Offset{Inode: 7, Offset: 500, FP: 1, FPLen: 64}) {
t.Fatal("without a saved fingerprint the offset decides")
}
}
+29
View File
@@ -0,0 +1,29 @@
package app
import (
"io"
"log/slog"
"testing"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// The files sent by a probe survive a hub restart: without them the egress
// lines the probe replays right after reconnecting were judged with the hub's
// own resolvers (a dns_bypass false positive on the probe's upstream resolver).
func TestProbeFilesSurviveRestart(t *testing.T) {
dir := t.TempDir()
sh := &shared{log: slog.New(slog.NewTextHandler(io.Discard, nil))}
n := &Node{name: "hostinger", Dir: dir, sh: sh}
n.saveProbeFile(wire.FileResolv, []byte("nameserver 153.92.2.6\n"))
n.saveProbeFile(wire.FileContainers, []byte("172.17.0.2 coolify-sentinel\n"))
n2 := &Node{name: "hostinger", Dir: dir, sh: sh}
n2.loadProbeFiles()
if b := n2.resolv.Load(); b == nil || string(*b) != "nameserver 153.92.2.6\n" {
t.Fatalf("resolv.conf not restored: %v", b)
}
if b := n2.containers.Load(); b == nil || string(*b) != "172.17.0.2 coolify-sentinel\n" {
t.Fatalf("containers.map not restored: %v", b)
}
}
+16 -1
View File
@@ -225,7 +225,7 @@ func (r *Runner) Feed(src string, text []byte, end store.Offset) bool {
func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
name := runnerSource(src)
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset {
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset && sameHead(saved, end) {
return false
}
if src == wire.SrcEgress {
@@ -243,6 +243,21 @@ func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
return true
}
// sameHead reports whether two positions of one inode belong to the same file
// generation. A copytruncate rotation (Traefik's log) keeps the inode and
// restarts the offsets at 0: without comparing the head fingerprint every new
// line below the old high-water mark would be taken for a duplicate and lost
// until the file regrew past it. Fingerprints of different lengths cannot be
// compared: they count as different generations (at worst a replay across a
// generation start is counted twice, never a whole generation lost). Without a
// fingerprint on either side (old state) the offset alone decides.
func sameHead(a, b store.Offset) bool {
if a.FPLen == 0 || b.FPLen == 0 {
return true
}
return a.FPLen == b.FPLen && a.FP == b.FP
}
// ApplyBatch applies the lines of a batch under the commit mutex.
func (r *Runner) ApplyBatch(lines []wire.Line) (accepted, dup int) {
r.mu.Lock()
+1 -1
View File
@@ -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 = "2.0.0"
var Version = "2.2.2"
+42
View File
@@ -681,3 +681,45 @@ func TestBeaconMetadataAndKnownCDN(t *testing.T) {
t.Fatalf("surbl: %+v", f)
}
}
func TestEngineDst(t *testing.T) {
e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
for i := 0; i < 70; i++ { // more destinations than the top-50
e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", fmt.Sprintf("198.18.0.%d", i+1), "tcp", 80))
}
e.IngestEvent(mk(t0.Add(time.Hour), "10.0.3.5", "198.18.0.70", "tcp", 443))
from, to := t0.Unix()-60, t0.Unix()+7200
d, _, ok := e.Dst(from, to, ip("198.18.0.70"))
if !ok || d.Conns != 2 || d.IP != "198.18.0.70" || len(d.Workloads) != 1 || len(d.Ports) != 2 || d.Ports[0] != 80 {
t.Fatalf("dst: %+v ok=%v", d, ok)
}
if _, _, ok := e.Dst(from, to, ip("203.0.113.9")); ok {
t.Fatal("unknown dst found")
}
if _, _, ok := e.Dst(from-10*86400, from-9*86400, ip("198.18.0.70")); ok {
t.Fatal("dst found outside the window")
}
}
func TestNewGeoSkipsAnycastCDN(t *testing.T) {
geo := func(s string) (string, string, string) {
switch s {
case "1.1.1.1":
return "AU", "AS13335", "Cloudflare"
case "149.154.166.110":
return "NL", "", ""
case "203.0.113.50":
return "DE", "AS197540", "netcup"
}
return "BR", "AS2", "y"
}
e := newEng(t, Config{Geo: geo})
e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443))
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "1.1.1.1", "udp", 53)) // Cloudflare anycast
e.IngestEvent(mk(t0.Add(25*time.Hour), "10.0.3.5", "149.154.166.110", "tcp", 443)) // Telegram prefix, no ASN
e.IngestEvent(mk(t0.Add(26*time.Hour), "10.0.3.5", "203.0.113.50", "tcp", 443))
g := kinds(rep(e), "new_geo")
if len(g) != 1 || g[0].Dst != "203.0.113.50" {
t.Fatalf("new_geo: %+v", g)
}
}
+3 -1
View File
@@ -752,7 +752,9 @@ func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat
if ws.role != RoleScanner && !fan && ds.cc != "" && isGlobal(ev.Dst) {
if _, seen := ws.geo[ds.cc]; !seen {
ws.geo[ds.cc] = struct{}{}
if t-ws.first >= int64(e.cfg.Learn/time.Second) {
// Anycast CDNs and big clouds: the database country of 1.1.1.1 or a
// Cloudflare edge says nothing about where the traffic goes.
if t-ws.first >= int64(e.cfg.Learn/time.Second) && !commonCloudASNs[ds.asn] && !inCommonCDN(ev.Dst) {
e.addFinding("new_geo", "low", ws.name, dst, dport, ev.Proto, t, 0, 0, "first contact with country "+ds.cc+" "+ds.asn, 1)
}
} else if len(ws.geo) > 300 {
+43
View File
@@ -454,3 +454,46 @@ func EmptyReport() Report {
return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Scanner: ScannerOut{Bursts: []BurstOut{}},
Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}}
}
// Dst looks one destination up in the dst table (not limited to the top 50):
// its connections in [from, to] and the findings that target it. ok is false
// when the window holds neither.
func (e *Engine) Dst(from, to int64, ip netip.Addr) (DstOut, []Finding, bool) {
e.mu.Lock()
defer e.mu.Unlock()
if to <= from {
to = from + 1
}
fs := []Finding{}
for _, f := range e.findings {
if f.Last >= from && f.First <= to && f.Dst == ip.String() {
c := *f
c.Samples = append([]int64(nil), f.Samples...)
fs = append(fs, c)
}
}
sort.Slice(fs, func(i, j int) bool {
if fs[i].Last != fs[j].Last {
return fs[i].Last > fs[j].Last
}
return fs[i].ID < fs[j].ID
})
out := DstOut{IP: ip.String(), Workloads: []string{}, Ports: []uint16{}}
if el, ok := e.dsts.m[ip]; ok { // read-only: no LRU promotion
ds := el.Value.(*lent[netip.Addr, *dstStat]).v
d0, d1 := int32(from/86400), int32(to/86400)
for _, d := range ds.days {
if d.day >= d0 && d.day <= d1 {
out.Conns += uint64(d.n)
}
}
out.CC, out.ASN, out.Org = ds.cc, ds.asn, ds.og
out.Workloads = append(out.Workloads, ds.wls...)
out.Ports = append(out.Ports, ds.ports...)
sort.Slice(out.Ports, func(a, b int) bool { return out.Ports[a] < out.Ports[b] })
}
if out.Conns == 0 && len(fs) == 0 {
return DstOut{}, nil, false
}
return out, fs, true
}
+17 -1
View File
@@ -867,7 +867,7 @@ func (f *Filter) Match(r *Rec) bool {
if r.T < f.From || (f.To != 0 && r.T > f.To) {
return false
}
if f.Host != "" && r.Host != f.Host {
if f.Host != "" && !hostMatch(f.Host, r.Host) {
return false
}
if len(f.Cats) > 0 && !f.Cats[r.Cat] {
@@ -1164,3 +1164,19 @@ func (l *Log) Counts(from, to int64) map[int64]int64 {
// StartCursor is a cursor that begins an ascending read at time t.
func StartCursor(t int64) string { return encodeCursor(t, 0) }
// hostMatch reports whether host is the filter or one of its comma list.
func hostMatch(filter, host string) bool {
if filter == host {
return true
}
if !strings.Contains(filter, ",") {
return false
}
for _, n := range strings.Split(filter, ",") {
if strings.TrimSpace(n) == host {
return true
}
}
return false
}
+18 -1
View File
@@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
@@ -67,6 +68,22 @@ func NewHub(provider func() []Backend) *Hub {
subs: map[chan store.LiveEvent]struct{}{}, vsubs: map[chan store.VisitMsg]struct{}{}, attach: map[string]func(){}}
}
// onlyHas reports whether name is in only: one node name or a comma list.
func onlyHas(only, name string) bool {
if only == name {
return true
}
if !strings.Contains(only, ",") {
return false
}
for _, n := range strings.Split(only, ",") {
if strings.TrimSpace(n) == name {
return true
}
}
return false
}
func (h *Hub) backends(only string) []Backend {
if h == nil || h.Provider == nil {
return nil
@@ -74,7 +91,7 @@ func (h *Hub) backends(only string) []Backend {
all := h.Provider()
out := make([]Backend, 0, len(all))
for _, b := range all {
if only == "" || only == b.Name() {
if only == "" || onlyHas(only, b.Name()) {
out = append(out, b)
}
}
+78
View File
@@ -0,0 +1,78 @@
package hub_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// A probe that starts with a backlog sends resolv.conf in the same batch as
// the egress lines (or right before them). The hub must apply the files first:
// DNS to a resolver listed in that resolv.conf is not "dns_bypass". A probe
// that never sent resolv.conf is the control: the same line is a finding.
// Regression: the 2.0.0 cutover opened two false dns_bypass incidents.
func TestEgressFilesAppliedBeforeLines(t *testing.T) {
dir := t.TempDir()
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
hp.start()
defer func() { hp.stop() }()
base := "http://" + hp.addr
push := func(name, token string, b wire.Batch) {
t.Helper()
post := func(path string, v any) {
t.Helper()
body, _ := json.Marshal(v)
req, _ := http.NewRequest("POST", base+path, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set(wire.HeaderProbe, name)
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
out, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 200 {
t.Fatalf("%s %s: %d %s", name, path, res.StatusCode, out)
}
}
post(wire.PathHello, wire.Hello{Proto: wire.Proto, Name: name, Version: "test", Sources: []string{wire.SrcEgress}})
post(wire.PathPush, b)
}
line := func(host string) wire.Line {
ts := time.Now().UTC().Format("2006-01-02T15:04:05+00:00")
txt := ts + " " + host + " kernel: URUTAU-EGRESS: IN= OUT=eth0 SRC=192.0.2.10 DST=153.92.2.6 PROTO=UDP SPT=40000 DPT=53\n"
return wire.Line{Src: wire.SrcEgress, Text: txt, End: wire.Pos{Inode: 7, Offset: int64(len(txt))}}
}
tokens := map[string]string{}
for _, n := range []string{"withresolv", "noresolv"} {
code, b := hp.send("POST", "/api/v1/probes", map[string]string{"name": n})
var o struct{ Token string }
if code != 201 || json.Unmarshal(b, &o) != nil {
t.Fatalf("create %s: %d %s", n, code, b)
}
tokens[n] = o.Token
}
resolv := wire.File{Name: wire.FileResolv, Data: "nameserver 1.1.1.1\nnameserver 153.92.2.6\n"}
// the file comes AFTER the line inside the batch, as the probe may queue them
push("withresolv", tokens["withresolv"], wire.Batch{Seq: 1, Sent: time.Now().UnixMilli(), Lines: []wire.Line{line("withresolv")}, Files: []wire.File{resolv}})
push("noresolv", tokens["noresolv"], wire.Batch{Seq: 1, Sent: time.Now().UnixMilli(), Lines: []wire.Line{line("noresolv")}})
bypass := func(host string) bool {
_, b := hp.send("GET", "/api/v1/egress?range=1h&host="+host, nil)
return strings.Contains(string(b), `"dns_bypass"`)
}
waitFor(t, "control probe reports dns_bypass", 15*time.Second, func() bool { return bypass("noresolv") })
if bypass("withresolv") {
t.Fatal("DNS to a resolver listed in the probe's resolv.conf was reported as dns_bypass")
}
}
+24 -18
View File
@@ -212,9 +212,15 @@ func appendFile(t *testing.T, path string, lines ...string) {
}
}
func startRun(ctx context.Context, c Config) chan error {
done := make(chan error, 1)
go func() { done <- Run(ctx, c, quiet()) }()
// startRun runs the probe in the background. The cleanup cancels it and waits
// for Run to return, so no state write races the TempDir removal (cleanups run
// in reverse order: this one, registered after t.TempDir, runs first).
func startRun(t *testing.T, ctx context.Context, c Config) chan error {
t.Helper()
ctx, cancel := context.WithCancel(ctx)
done, fin := make(chan error, 1), make(chan struct{})
go func() { defer close(fin); done <- Run(ctx, c, quiet()) }()
t.Cleanup(func() { cancel(); <-fin })
return done
}
@@ -228,7 +234,7 @@ func TestEndToEnd(t *testing.T) {
e.cfg.Location = &wire.Location{Lat: 1, Lon: 2, Label: "x"}
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t1", "t2")
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
done := startRun(t, ctx, e.cfg)
appendFile(t, e.cfg.Paths[wire.SrcAuth], "a1")
eventually(t, "3 lines", 5*time.Second, func() bool { return hub.count() == 3 })
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "t3\xff")
@@ -281,7 +287,7 @@ func TestHubOutageNoLossNoDuplicates(t *testing.T) {
e := newEnv(t, srv.URL)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "first")
eventually(t, "first", 5*time.Second, func() bool { return hub.count() == 1 })
@@ -316,14 +322,14 @@ func TestRestartResumesFromState(t *testing.T) {
tp := e.cfg.Paths[wire.SrcTraefik]
appendFile(t, tp, "a", "b", "c")
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
done := startRun(t, ctx, e.cfg)
eventually(t, "3", 5*time.Second, func() bool { return hub.count() == 3 })
cancel()
<-done
appendFile(t, tp, "d")
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
startRun(ctx2, e.cfg)
startRun(t, ctx2, e.cfg)
eventually(t, "4", 5*time.Second, func() bool { return hub.count() >= 4 })
time.Sleep(200 * time.Millisecond)
if got := hub.texts(); len(got) != 4 || got[3] != "traefik:d" {
@@ -343,7 +349,7 @@ func TestFreshProbeStartsAtHubOffsets(t *testing.T) {
hub.offsets[wire.SrcTraefik] = wire.Pos{Inode: ino, Offset: int64(len("old1\nold2\n"))}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "new1", 5*time.Second, func() bool { return hub.count() >= 1 })
time.Sleep(200 * time.Millisecond)
if got := hub.texts(); len(got) != 1 || got[0] != "traefik:new1" {
@@ -360,7 +366,7 @@ func TestHubAckAheadRaisesSeq(t *testing.T) {
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
}
@@ -374,7 +380,7 @@ func TestPushBackpressure503RetryAfter(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
start := time.Now()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "x", 8*time.Second, func() bool { return hub.count() == 1 })
if el := time.Since(start); el < 900*time.Millisecond {
t.Errorf("retried after %v, Retry-After: 1 not honored", el)
@@ -429,7 +435,7 @@ func TestUnauthorizedRevokedMidSession(t *testing.T) {
defer srv.Close()
e := newEnv(t, srv.URL)
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x")
done := startRun(context.Background(), e.cfg)
done := startRun(t, context.Background(), e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
revoked.Lock()
rev = true
@@ -456,7 +462,7 @@ func TestGzipOverThreshold(t *testing.T) {
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "20", 5*time.Second, func() bool { return hub.count() == 20 })
hub.mu.Lock()
defer hub.mu.Unlock()
@@ -476,7 +482,7 @@ func TestSmallPushNotGzipped(t *testing.T) {
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "tiny")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "1", 5*time.Second, func() bool { return hub.count() == 1 })
hub.mu.Lock()
defer hub.mu.Unlock()
@@ -501,7 +507,7 @@ func TestCommandsApplied(t *testing.T) {
{Seq: 5, Kind: "other", Line: good},
}
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, e.cfg)
done := startRun(t, ctx, e.cfg)
eventually(t, "cmds", 5*time.Second, func() bool {
s, err := loadState(e.state)
return err == nil && s.s.LastCmd == 5
@@ -518,7 +524,7 @@ func TestCommandsApplied(t *testing.T) {
}
// restart: the hub redelivers everything, nothing is applied twice
ctx2, cancel2 := context.WithCancel(context.Background())
done2 := startRun(ctx2, e.cfg)
done2 := startRun(t, ctx2, e.cfg)
time.Sleep(600 * time.Millisecond)
cancel2()
<-done2
@@ -582,7 +588,7 @@ func TestOversizeLineCountedNotSent(t *testing.T) {
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "ok", strings.Repeat("z", wire.MaxLine+10), "after")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "2 lines", 5*time.Second, func() bool { return hub.count() == 2 })
time.Sleep(100 * time.Millisecond)
if got := hub.texts(); len(got) != 2 || got[1] != "traefik:after" {
@@ -598,7 +604,7 @@ func TestMissingSourceWaitsAndNoPathLeak(t *testing.T) {
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "x") // auth.log never created
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startRun(ctx, e.cfg)
startRun(t, ctx, e.cfg)
eventually(t, "x", 5*time.Second, func() bool { return hub.count() == 1 })
appendFile(t, e.cfg.Paths[wire.SrcTraefik], "y")
eventually(t, "status", 5*time.Second, func() bool {
@@ -666,7 +672,7 @@ func TestHelperProbe(t *testing.T) {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := startRun(ctx, cfg)
done := startRun(t, ctx, cfg)
io.Copy(io.Discard, os.Stdin) // parent closes stdin when done
cancel()
<-done
+12 -4
View File
@@ -17,7 +17,7 @@ import (
const (
chanSize = 4096
batchBytes = 128 << 10 // well under the hub limit; keeps the probe heap small
filePollEach = 10 * time.Second
filePollEach = 2 * time.Second
)
// item is what the followers and the file watcher hand to the collector.
@@ -60,6 +60,15 @@ func fromTail(p tail.Pos) wire.Pos {
// startTailers launches one follower per configured source. A source with no
// local position starts where the hub says it already has data.
func (p *probe) startTailers(ctx context.Context, hubOffsets map[string]wire.Pos) {
// containers.map and resolv.conf go into the queue before any line, so the
// hub never judges a backlog of egress lines without them.
ready := make(chan struct{})
p.wg.Add(1)
go func() { defer p.wg.Done(); p.watchFiles(ctx, ready) }()
select {
case <-ready:
case <-ctx.Done():
}
for _, src := range p.sources {
path := p.cfg.Paths[src]
pos, ok := p.st.pos(src)
@@ -86,13 +95,11 @@ func (p *probe) startTailers(ctx context.Context, hubOffsets map[string]wire.Pos
p.wg.Add(1)
go func() { defer p.wg.Done(); f.Run(ctx) }()
}
p.wg.Add(1)
go func() { defer p.wg.Done(); p.watchFiles(ctx) }()
}
// watchFiles sends containers.map and resolv.conf whole whenever they change,
// and again after each reconnect.
func (p *probe) watchFiles(ctx context.Context) {
func (p *probe) watchFiles(ctx context.Context, ready chan<- struct{}) {
files := []struct{ name, path string }{
{wire.FileContainers, p.cfg.Containers},
{wire.FileResolv, p.cfg.Resolv},
@@ -120,6 +127,7 @@ func (p *probe) watchFiles(ctx context.Context) {
}
}
check()
close(ready)
t := time.NewTicker(p.fileEvery)
defer t.Stop()
for {
+4 -5
View File
@@ -32,17 +32,16 @@ func (s *Server) analytics(kind string) http.HandlerFunc {
return
}
host := q.Get("host")
if len(host) > 64 {
if !hostListOK(host) {
badRequest(w, "invalid host")
return
}
if host == "all" {
host = ""
}
if host != "" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
sel, ok := s.parseHosts(host)
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return
}
host = sel.csv(s.opt.Store.Name())
dim := q.Get("dim")
if kind == "concentration" {
if dim == "" {
+149
View File
@@ -0,0 +1,149 @@
package server
import (
"encoding/json"
"net/http"
"net/netip"
"sort"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
)
func init() {
registerUserRoute("GET /api/v1/ip/{ip}/egress", func(s *Server) http.HandlerFunc { return s.ipEgressAPI })
}
type ipEgressHost struct {
Host string `json:"host"`
Conns uint64 `json:"conns"`
CC string `json:"cc"`
ASN string `json:"asn"`
Org string `json:"org"`
Workloads []string `json:"workloads"`
Ports []uint16 `json:"ports"`
}
type ipEgressInc struct {
ID string `json:"id"`
Host string `json:"host"`
Title string `json:"title"`
Status string `json:"status"`
Severity string `json:"severity"`
Kind string `json:"kind"`
Workload string `json:"workload"`
Last int64 `json:"last_seen"`
}
// ipEgressAPI: GET /api/v1/ip/{ip}/egress. What the node(s) did towards this
// address (egress connections, findings, incidents) and when it was last seen
// as an inbound source.
func (s *Server) ipEgressAPI(w http.ResponseWriter, r *http.Request) {
ip, err := netip.ParseAddr(r.PathValue("ip"))
if err != nil || ip.Zone() != "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
return
}
ip = ip.Unmap()
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := r.URL.Query().Get("host")
if len(host) > 253 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
return
}
local, peers, only, ok := s.studyHosts(w, host)
if !ok {
return
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
self := s.opt.Store.Name()
out := struct {
IP string `json:"ip"`
Egress []ipEgressHost `json:"egress"`
Findings []egress.Finding `json:"findings"`
Incidents []ipEgressInc `json:"incidents"`
LastSeenInbound int64 `json:"last_seen_inbound"`
}{IP: ip.String(), Egress: []ipEgressHost{}, Findings: []egress.Finding{}, Incidents: []ipEgressInc{}}
add := func(h string, d egress.DstOut, fs []egress.Finding) {
if d.Conns > 0 || len(d.Workloads) > 0 {
out.Egress = append(out.Egress, ipEgressHost{Host: h, Conns: d.Conns, CC: d.CC, ASN: d.ASN, Org: d.Org,
Workloads: append([]string{}, d.Workloads...), Ports: append([]uint16{}, d.Ports...)})
}
for _, f := range fs {
f.Host = h
out.Findings = append(out.Findings, f)
}
}
if eng := egressEngine.Load(); local && eng != nil {
if d, fs, ok := eng.Dst(from, to, ip); ok {
add(self, d, fs)
}
}
if peers && s.opt.Hub != nil {
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
names := make([]string, 0, len(raws))
for n := range raws {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
var pr egress.Report
if json.Unmarshal(raws[n], &pr) != nil {
continue
}
pr.Sanitize(n)
var fs []egress.Finding
for _, f := range pr.Findings {
if f.Dst == ip.String() {
fs = append(fs, f)
}
}
var d egress.DstOut
for _, x := range pr.TopDst { // peers only report their top destinations
if x.IP == ip.String() {
d = x
}
}
add(n, d, fs)
}
}
sort.Slice(out.Findings, func(i, j int) bool { return out.Findings[i].Last > out.Findings[j].Last })
if len(out.Findings) > 200 {
out.Findings = out.Findings[:200]
}
for _, h := range s.incHosts() {
if (host != "" && host != "all" && host != h) || len(out.Incidents) >= 100 {
continue
}
st := s.incStore(h)
if st == nil {
continue
}
for _, t := range st.All(incidents.Query{Q: ip.String()}) {
if t.Dst != ip.String() {
continue
}
out.Incidents = append(out.Incidents, ipEgressInc{ID: h + "/" + t.ID, Host: h, Title: t.Title, Status: t.Status,
Severity: t.Severity, Kind: t.Kind, Workload: t.Workload, Last: t.LastSeen})
}
}
sort.Slice(out.Incidents, func(i, j int) bool { return out.Incidents[i].Last > out.Incidents[j].Last })
key := ip.String()
if d, ok := s.opt.Store.IP(key); ok {
out.LastSeenInbound = d.Last
}
if s.opt.Hub != nil {
for _, d := range s.opt.Hub.IPDetail(key) {
if d.Last > out.LastSeenInbound {
out.LastSeenInbound = d.Last
}
}
}
writeJSON(w, 200, out)
}
+41
View File
@@ -1,7 +1,9 @@
package server
import (
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"net/netip"
"path/filepath"
"strconv"
"testing"
"time"
@@ -68,3 +70,42 @@ func TestEgressAPI(t *testing.T) {
t.Fatalf("peer token must not open the user route")
}
}
func TestIPEgressAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
inc, err := incidents.Open(filepath.Join(t.TempDir(), "incidents.json"), nil)
if err != nil {
t.Fatal(err)
}
h := New(Options{Token: userTok, Version: "t", Store: st, Incidents: inc})
auth := map[string]string{"Authorization": "Bearer " + userTok}
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
if err != nil {
t.Fatal(err)
}
SetEgress(e)
defer SetEgress(nil)
now := time.Now()
e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.5.2"), Dst: netip.MustParseAddr("203.0.113.7"), Proto: "tcp", DPort: 6667, In: "br-1"})
inc.Sync([]incidents.Finding{{Host: "oracle", Kind: "beacon", Severity: "high", Workload: "ciberlab", Dst: "203.0.113.7", Proto: "tcp", DPort: 6667, First: now.Add(-time.Hour).Unix(), Last: now.Unix(), Count: 9}})
d := getJSON(t, h, "/api/v1/ip/203.0.113.7/egress?range=24h", auth)
eg := d["egress"].([]any)
if len(eg) != 1 || eg[0].(map[string]any)["host"] != "oracle" || eg[0].(map[string]any)["conns"].(float64) != 1 {
t.Fatalf("egress: %v", d)
}
ics := d["incidents"].([]any)
if len(ics) != 1 || ics[0].(map[string]any)["id"] != "oracle/INC-1" {
t.Fatalf("incidents: %v", d["incidents"])
}
if d["last_seen_inbound"].(float64) != 0 {
t.Fatalf("inbound: %v", d)
}
d = getJSON(t, h, "/api/v1/ip/203.0.113.99/egress?range=24h", auth)
if len(d["egress"].([]any)) != 0 || len(d["incidents"].([]any)) != 0 || len(d["findings"].([]any)) != 0 {
t.Fatalf("empty: %v", d)
}
if w := do(h, "GET", "/api/v1/ip/nope/egress", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("bad ip: %d", w.Code)
}
}
+28 -11
View File
@@ -290,13 +290,10 @@ func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
hosts := s.incHosts()
if q.Host != "" && q.Host != "all" {
hosts = []string{q.Host}
if s.incStore(q.Host) == nil {
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
return
}
hosts := s.incSelect(q.Host)
if hosts == nil {
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
return
}
q.Host = ""
if len(hosts) == 1 {
@@ -480,10 +477,7 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
cw := csv.NewWriter(w)
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
hosts := s.incHosts()
if q.Host != "" && q.Host != "all" {
hosts = []string{q.Host}
}
hosts := s.incSelect(q.Host)
q.Host = ""
var rows []qSummary
for _, h := range hosts {
@@ -504,3 +498,26 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
}
cw.Flush()
}
// incSelect resolves the host filter of the ticket queries: "" or "all" is
// every host with a store, otherwise the listed ones (comma list) that have
// one. It returns nil when a selection names none.
func (s *Server) incSelect(raw string) []string {
if raw == "" || raw == "all" {
return s.incHosts()
}
var out []string
seen := map[string]bool{}
for _, n := range strings.Split(raw, ",") {
n = strings.TrimSpace(n)
if n == "all" {
return s.incHosts()
}
if n == "" || seen[n] || s.incStore(n) == nil {
continue
}
seen[n] = true
out = append(out, n)
}
return out
}
+4 -8
View File
@@ -96,16 +96,12 @@ func figuresOf(t store.Totals, tr store.TrafficData) reportFigures {
// trafficOf is what /api/v1/traffic answers for all domains, merged with the peers.
func (s *Server) trafficOf(r *http.Request, rg store.Range, host string) store.TrafficData {
var parts []store.TrafficData
self := s.opt.Store.Name()
if host == "all" || host == self {
sel, _ := s.parseHosts(host)
if sel.local {
parts = append(parts, s.opt.Store.TrafficFor(rg, "all"))
}
if s.opt.Hub != nil && host != self {
only := ""
if host != "all" {
only = host
}
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", only)...)
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", sel.only())...)
}
return store.MergeTraffic(host, parts)
}
+1 -1
View File
@@ -118,7 +118,7 @@ func (s *Server) geoAPI(w http.ResponseWriter, r *http.Request) {
if host == "" {
host = "all"
}
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
if _, ok := s.parseHosts(host); !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return
}
+104
View File
@@ -0,0 +1,104 @@
package server
import (
"sort"
"strings"
)
// maxHostSel bounds how many names one host selection may carry.
const maxHostSel = 16
// hostSel is a resolved host selection of a request: "all" (or empty), one
// host, or a comma list such as host=oracle,hostinger.
type hostSel struct {
all bool // every host: no filtering
local bool // this node is part of the selection
peers []string // the other nodes of the selection (sorted), empty with all
}
// csv is the canonical text of the selection ("" for all): the hub's own name
// (when present) first, then the peers.
func (h hostSel) csv(self string) string {
if h.all {
return ""
}
var n []string
if h.local {
n = append(n, self)
}
return strings.Join(append(n, h.peers...), ",")
}
// only is the peers' list the fed.Hub understands ("" asks every node).
func (h hostSel) only() string {
if h.all {
return ""
}
return strings.Join(h.peers, ",")
}
// parseHosts resolves a host query value. ok is false for names this hub does
// not serve, for a malformed or oversized list.
func (s *Server) parseHosts(raw string) (hostSel, bool) {
raw = strings.TrimSpace(raw)
if raw == "" || raw == "all" {
return hostSel{all: true, local: true}, true
}
if len(raw) > 64*maxHostSel {
return hostSel{}, false
}
self := s.opt.Store.Name()
seen := map[string]bool{}
var sel hostSel
for _, n := range strings.Split(raw, ",") {
n = strings.TrimSpace(n)
switch {
case n == "":
continue
case n == "all":
return hostSel{all: true, local: true}, true
case len(n) > 64 || len(seen) >= maxHostSel:
return hostSel{}, false
case seen[n]:
continue
}
seen[n] = true
if n == self {
sel.local = true
} else if s.opt.Hub != nil && s.opt.Hub.Has(n) {
sel.peers = append(sel.peers, n)
} else {
return hostSel{}, false
}
}
if len(seen) == 0 {
return hostSel{all: true, local: true}, true
}
sort.Strings(sel.peers)
// naming every node is the same as asking for all of them
if sel.local {
every := true
if s.opt.Hub != nil {
for _, p := range s.opt.Hub.PeerNames() {
every = every && seen[p]
}
}
if every {
return hostSel{all: true, local: true}, true
}
}
return sel, true
}
// hostListOK bounds the text of a host list: names of 64 bytes at most, 16 at most.
func hostListOK(raw string) bool {
if len(raw) > 64*maxHostSel+maxHostSel {
return false
}
for _, n := range strings.Split(raw, ",") {
if len(strings.TrimSpace(n)) > 64 {
return false
}
}
return true
}
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"encoding/json"
"testing"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"time"
)
// host= accepts "all", one name or a comma list, the same way on every endpoint.
func TestHostSelectionList(t *testing.T) {
mk := func(ip string) store.PeerExport {
e := store.PeerExport{V: 1}
e.Summary.IPs = []store.IPSummary{{IP: ip, Score: 10}}
return e
}
hub := fed.NewHub(func() []fed.Backend {
return []fed.Backend{fakeBackend{name: "p1", exp: mk("198.51.100.1")}, fakeBackend{name: "p2", exp: mk("198.51.100.2")}, fakeBackend{name: "p3", exp: mk("198.51.100.3")}}
})
st := store.New(store.Config{Name: "me", Version: "t"})
st.Ingest(core.Event{Time: time.Now(), IP: "203.0.113.9", Cat: core.Scanner, Source: "traefik", Status: 404, Path: "/.env"})
h := New(Options{Token: utok, Store: st, Hub: hub})
total := func(host string) int {
code, body := bearerGet(h, "/api/v1/ips?range=24h&min_score=0&host="+host)
if code != 200 {
t.Fatalf("host=%q: %d %s", host, code, body)
}
var o struct{ Total int }
if err := json.Unmarshal([]byte(body), &o); err != nil {
t.Fatal(err)
}
return o.Total
}
for host, want := range map[string]int{"": 4, "all": 4, "p1": 1, "p1,p2": 2, "p1,p2,p3": 3, "me,p3": 2, "me": 1, "me,p1,p2,p3": 4, "p2,p2": 1, "p1,all": 4} {
if got := total(host); got != want {
t.Errorf("host=%q: %d IPs, want %d", host, got, want)
}
}
for _, ep := range []string{"summary", "traffic", "integrity", "geo", "report"} {
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,p2"); code != 200 {
t.Errorf("%s host=p1,p2: %d", ep, code)
}
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,nope"); code != 404 {
t.Errorf("%s host=p1,nope: %d", ep, code)
}
}
for _, ep := range []string{"period", "metrics", "evolution", "egress"} {
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=me,p1"); code != 200 {
t.Errorf("%s host=me,p1: %d", ep, code)
}
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,nope"); code != 404 {
t.Errorf("%s host=p1,nope: %d", ep, code)
}
}
}
+13 -15
View File
@@ -37,13 +37,13 @@ func (s *Server) eventFilter(w http.ResponseWriter, r *http.Request, defaultSpan
}
eq.From, eq.To = rg.Bounds(s.opt.Now().Unix())
eq.Host = q.Get("host")
if eq.Host == "all" {
eq.Host = ""
}
if len(eq.Host) > 64 {
if !hostListOK(eq.Host) {
badRequest(w, "invalid host")
return eq, false
}
if sel, ok := s.parseHosts(eq.Host); ok { // "all" and a list naming every node become ""
eq.Host = sel.csv(s.opt.Store.Name())
}
if ip := q.Get("ip"); ip != "" {
_, err1 := netip.ParseAddr(ip)
_, err2 := netip.ParsePrefix(ip)
@@ -217,21 +217,19 @@ func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
}{list[from:to], gap, trunc, s.opt.Store.EventLog() != nil, pageTotal{metaOf(len(list), page, per), len(list)}})
}
// studyHosts resolves the host selection of period and metrics: whether the
// local study is wanted and which peers to ask. It answers 404 itself.
// studyHosts resolves the host selection of period and metrics (one name, "all"
// or a comma list): whether the local study is wanted and which peers to ask
// (only: their names, comma separated). It answers 404 itself.
func (s *Server) studyHosts(w http.ResponseWriter, host string) (local bool, peers bool, only string, ok bool) {
self := s.opt.Store.Name()
if host == "" || host == "all" {
return true, s.opt.Hub != nil, "", true
}
if host == self {
return true, false, "", true
}
if s.opt.Hub == nil || !s.opt.Hub.Has(host) {
sel, ok := s.parseHosts(host)
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return false, false, "", false
}
return false, true, host, true
if sel.all {
return true, s.opt.Hub != nil, "", true
}
return sel.local, len(sel.peers) > 0, sel.only(), true
}
// userSlot admits one more user-side study (503 with Retry-After when four run).
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
@@ -139,7 +140,7 @@ func (s *Server) primaryName() string { return s.opt.Store.Name() }
// enforceFor returns the engine of a host ("" or the primary: the primary's).
func (s *Server) enforceFor(host string) *enforce.Engine {
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
if host == "" || strings.Contains(host, ",") || host == s.primaryName() || s.opt.Nodes == nil {
return enforceEngine.Load()
}
return s.opt.Nodes.Enforce(host)
+13 -25
View File
@@ -371,27 +371,23 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
// parts returns the summaries to merge for a host selection.
func (s *Server) parts(ctx context.Context, rg store.Range, host string) (parts []store.Summary, all []store.HostInfo) {
self := s.opt.Store.Name()
local := s.opt.Store.SummaryFor(rg)
all = append(all, local.Hosts...)
if s.opt.Hub != nil {
all = append(all, s.opt.Hub.Hosts()...)
}
if host == "" || host == "all" || host == self {
sel, _ := s.parseHosts(host)
if sel.local {
parts = append(parts, local)
}
if s.opt.Hub != nil && host != self {
only := ""
if host != "" && host != "all" {
only = host
}
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, only)...)
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, sel.only())...)
}
return
}
func (s *Server) knownHost(w http.ResponseWriter, host string) bool {
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
if _, ok := s.parseHosts(host); !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return false
}
@@ -437,16 +433,12 @@ func (s *Server) allIPs(ctx context.Context, rg store.Range, host string) []stor
func (s *Server) ipsOf(ctx context.Context, rg store.Range, host string, localOnly bool) []store.IPSummary {
var lists [][]store.IPSummary
self := s.opt.Store.Name()
if host == "" || host == "all" || host == self {
sel, _ := s.parseHosts(host)
if sel.local {
lists = append(lists, s.opt.Store.AllIPs(rg, false))
}
if s.opt.Hub != nil && host != self && !localOnly {
only := ""
if host != "" && host != "all" {
only = host
}
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, only) {
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) && !localOnly {
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, sel.only()) {
lists = append(lists, p.IPs)
}
}
@@ -714,20 +706,16 @@ func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
if host == "" {
host = "all"
}
self := s.opt.Store.Name()
if !s.knownHost(w, host) {
return
}
sel, _ := s.parseHosts(host)
var parts []store.TrafficData
if host == "all" || host == self {
if sel.local {
parts = append(parts, s.opt.Store.TrafficFor(rg, domain))
}
if s.opt.Hub != nil && host != self {
only := ""
if host != "all" {
only = host
}
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, only)...)
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, sel.only())...)
}
out := store.MergeTraffic(host, parts)
out.Domain = domain
+263 -70
View File
@@ -614,7 +614,7 @@
var seen = {}, list = [];
var rec = state.summary ? state.summary.recent || [] : [];
state.live.concat(rec).forEach(function (e) {
if (state.host !== 'all' && e.host !== state.host) return;
if (!hostHas(state.host, e.host)) return;
var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || '');
if (seen[key]) return;
seen[key] = 1;
@@ -1021,7 +1021,7 @@
// each probe enforces its own bans: the operator picks where to lift it (or every host)
var hostSel = el('select', { id: 'unban-host' });
var hostRow = el('div', { class: 'unban-host', hidden: true }, el('label', { for: 'unban-host' }, t('pr.unban.host')), hostSel);
var wantHost = (opts && opts.host) || (state.host !== 'all' ? state.host : 'all');
var wantHost = (opts && opts.host) || (hostList(state.host).length === 1 ? state.host : 'all');
getSummary(ctx()).then(function (s) {
var hs = (s.hosts || []).map(function (x) { return x.name; });
if (hs.length < 2) return;
@@ -1832,7 +1832,7 @@
var p = [];
if (sl.from !== null && sl.from !== undefined) p.push('from=' + encodeURIComponent(new Date(sl.from * 1000).toISOString()), 'to=' + encodeURIComponent(new Date(sl.to * 1000).toISOString()));
else p.push('r=' + sl.range);
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host));
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host).replace(/%2C/gi, ','));
return p;
}
function buildHash(id, segments, extra, sl) {
@@ -1841,6 +1841,14 @@
return '#/' + [id].concat((segments || []).map(encodeURIComponent)).join('/') + '?' + parts.join('&');
}
function hrefFor(id, segments, extra) { return buildHash(id, segments || [], extra || {}); }
// host selection: 'all' or a comma list of probe names (host=oracle,hostinger in the URL and in the API)
function hostList(v) {
var seen = {}, out = [];
String(v || '').split(',').forEach(function (n) { n = n.trim(); if (n && n !== 'all' && n.length <= 64 && !seen[n]) { seen[n] = 1; out.push(n); } });
return out.slice(0, 16);
}
function hostJoin(list) { return list.length ? list.join(',') : 'all'; }
function hostHas(v, name) { return v === 'all' || !v || hostList(v).indexOf(name) >= 0; }
// read r/from/to/host from the URL; absent keys keep the current slice
function readSlice(q) {
var f = q.get('from'), to = q.get('to'), r = q.get('r') || q.get('range'), ok = false;
@@ -1849,44 +1857,96 @@
if (isFinite(a) && isFinite(b) && b > a && (b - a) / 1000 <= MAX_SPAN) { state.from = Math.floor(a / 1000); state.to = Math.floor(b / 1000); ok = true; }
}
if (!ok && r && PRESETS.indexOf(r) >= 0) { state.range = r; state.from = state.to = null; lsSet('urutau.range', r); }
if (q.has('host')) { state.host = q.get('host') || 'all'; lsSet('urutau.host', state.host); }
if (q.has('host')) { state.host = hostJoin(hostList(q.get('host'))); lsSet('urutau.host', state.host); }
}
// change the slice: the URL changes, the router does the rest
function setShell(over) {
var sl = { range: state.range, from: state.from, to: state.to, host: state.host };
Object.keys(over).forEach(function (k) { sl[k] = over[k]; });
// "all" leaves host= out of the URL and readSlice keeps the current host when the key is absent:
// apply the host here so going back to every probe works
if (over.host !== undefined) { state.host = hostJoin(hostList(over.host)); lsSet('urutau.host', state.host); }
var q = Object.assign({}, state.params.query); delete q.p; // a new period or host starts at page 1
var id = current ? current.id : 'overview', hash = buildHash(id, state.params.segments, q, sl);
if (hash !== location.hash) history.pushState(null, '', hash);
route();
}
// ---------------------------------------------------------------- range picker
// ---------------------------------------------------------------- filter bar (period + host)
// One period control (relative presets + absolute window), one host control with probe status,
// a summary of what is applied (with "clear" and "copy link") and a live/fixed indicator.
// Everything is written to the URL hash (setShell), so any state can be shared and restored.
// Popovers on desktop, bottom sheets under 768px. Keys: t (period), Esc, arrows inside a list.
var rp = { open: false, pop: null, btn: null, from: null, to: null, err: null };
var hp = { open: false, pop: null, btn: null };
var DEFAULT_RANGE = '24h';
function localInput(ts) {
var d = new Date(ts * 1000), p = function (n) { return String(n).padStart(2, '0'); };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + 'T' + p(d.getHours()) + ':' + p(d.getMinutes());
}
function presetButtons() { return rp.pop ? Array.prototype.slice.call(rp.pop.querySelectorAll('.chip-btn')) : []; }
// short name of the browser time zone ("GMT-3", "UTC"); dates in the bar and in the inputs use it
function tzName() {
try {
var part = new Intl.DateTimeFormat(lang, { timeZoneName: 'short' }).formatToParts(new Date()).filter(function (x) { return x.type === 'timeZoneName'; })[0];
if (part) return part.value;
} catch (e) { /* old engine */ }
var m = -new Date().getTimezoneOffset();
return 'UTC' + (m >= 0 ? '+' : '-') + Math.floor(Math.abs(m) / 60);
}
function tzFull() { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || tzName(); } catch (e) { return tzName(); } }
function svgIcon(d) { var n = iconNode('<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' + d + '</svg>'); n.setAttribute('aria-hidden', 'true'); return n; }
var IC = {
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
server: '<rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/>',
caret: '<path d="m6 9 6 6 6-6"/>', prev: '<path d="m15 6-6 6 6 6"/>', next: '<path d="m9 6 6 6-6 6"/>',
close: '<path d="M6 6l12 12M18 6 6 18"/>', link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',
check: '<path d="m5 12 5 5 9-10"/>'
};
function presetButtons() { return rp.pop ? Array.prototype.slice.call(rp.pop.querySelectorAll('.fb-chip')) : []; }
function hostOptions() { return hp.pop ? Array.prototype.slice.call(hp.pop.querySelectorAll('.fb-opt')) : []; }
function isDefaultSlice() { return !isCustom() && state.range === DEFAULT_RANGE && state.host === 'all' && state.domain === 'all'; }
function customLabel() { return shortDate(state.from) + ' – ' + shortDate(state.to); }
function renderRangePicker() {
if (!rp.btn) return;
rp.label.textContent = rangeShort();
var custom = isCustom();
document.querySelectorAll('#range-picker [data-range]').forEach(function (b) { b.setAttribute('aria-pressed', !custom && b.getAttribute('data-range') === state.range ? 'true' : 'false'); });
if (rp.from) { var now = Math.floor(Date.now() / 1000); rp.from.value = localInput(custom ? state.from : now - presetSecs(state.range)); rp.to.value = localInput(custom ? state.to : now); }
rp.label.textContent = custom ? customLabel() : rangeShort();
rp.tz.textContent = tzName();
rp.btn.title = t('fb.period.title', { tz: tzFull() });
rp.btn.classList.toggle('is-custom', custom);
rp.prev.hidden = rp.next.hidden = !custom;
if (custom) rp.next.disabled = state.to >= Math.floor(Date.now() / 1000) - 60;
presetButtons().forEach(function (b) { b.setAttribute('aria-pressed', !custom && b.getAttribute('data-range') === state.range ? 'true' : 'false'); });
if (rp.from) {
var now = Math.floor(Date.now() / 1000);
rp.from.min = rp.to.min = localInput(now - MAX_SPAN); rp.from.max = rp.to.max = localInput(now);
if (!rp.open) { rp.from.value = localInput(custom ? state.from : now - presetSecs(state.range)); rp.to.value = localInput(custom ? state.to : now); }
rp.tzNote.textContent = t('fb.tz', { tz: tzFull() === tzName() ? tzName() : tzFull() + ' (' + tzName() + ')' });
}
renderHostPicker();
}
function closeRangePicker(refocus) {
if (!rp.open) return;
rp.open = false; rp.pop.hidden = true; rp.scrim.hidden = true; rp.btn.setAttribute('aria-expanded', 'false');
if (refocus) rp.btn.focus();
function closePop(o, refocus) {
if (!o.open) return;
o.open = false; o.pop.hidden = true; o.scrim.hidden = true; o.btn.setAttribute('aria-expanded', 'false');
document.documentElement.classList.remove('fb-lock');
if (refocus) o.btn.focus();
}
function openPop(o, focusSel) {
if (!o.pop) return;
closePop(o === rp ? hp : rp, false);
o.open = true; o.pop.hidden = false; o.scrim.hidden = false; o.btn.setAttribute('aria-expanded', 'true');
if (matchMedia('(max-width: 767px)').matches) document.documentElement.classList.add('fb-lock');
var cur = o.pop.querySelector(focusSel) || o.pop.querySelector('button');
if (cur) cur.focus();
}
// closes whichever filter popover is open (kept under this name: Esc and other pages call it)
function closeRangePicker(refocus) { closePop(rp, refocus); closePop(hp, refocus); }
// the phone sheet sits above the bottom tab bar: using the tab bar closes it
document.addEventListener('click', function (e) { if (e.target.closest && e.target.closest('.tabbar')) closeRangePicker(false); }, true);
function openRangePicker() {
if (!rp.pop) return;
renderRangePicker();
rp.open = false; renderRangePicker();
rp.err.textContent = '';
rp.open = true; rp.pop.hidden = false; rp.scrim.hidden = false; rp.btn.setAttribute('aria-expanded', 'true');
var cur = rp.pop.querySelector('.chip-btn[aria-pressed="true"]') || rp.pop.querySelector('.chip-btn');
if (cur) cur.focus();
openPop(rp, '.fb-chip[aria-pressed="true"]');
}
function stepPreset(dir) {
var i = PRESETS.indexOf(state.range);
@@ -1898,84 +1958,219 @@
if (!isCustom()) return;
var span = state.to - state.from, now = Math.floor(Date.now() / 1000), nf2 = state.from + dir * span, nt = state.to + dir * span;
if (nt > now) { nt = now; nf2 = now - span; }
if (nf2 < now - MAX_SPAN) { nf2 = now - MAX_SPAN; nt = Math.min(now, nf2 + span); }
if (nf2 === state.from && nt === state.to) return;
setShell({ from: nf2, to: nt });
}
function applyCustom() {
var a = Date.parse(rp.from.value), b = Date.parse(rp.to.value);
var a = Date.parse(rp.from.value), b = Date.parse(rp.to.value), now = Date.now();
var msg = '';
if (!isFinite(a) || !isFinite(b)) msg = t('range.err.missing');
else if (b <= a) msg = t('range.err.order');
else if ((b - a) / 1000 > MAX_SPAN) msg = t('range.err.span');
else if (a < now - MAX_SPAN * 1000 - 60000) msg = t('fb.err.old');
else if (a > now) msg = t('fb.err.future');
rp.err.textContent = msg;
rp.from.setAttribute('aria-invalid', msg ? 'true' : 'false'); rp.to.setAttribute('aria-invalid', msg ? 'true' : 'false');
if (msg) return;
closeRangePicker(true);
setShell({ from: Math.floor(a / 1000), to: Math.floor(b / 1000) });
setShell({ from: Math.floor(a / 1000), to: Math.floor(Math.min(b, now) / 1000) });
}
function sheetHead(title, o) {
var x = el('button', { type: 'button', class: 'btn icon fb-x', 'aria-label': t('fb.close') }, svgIcon(IC.close));
x.addEventListener('click', function () { closePop(o, true); });
return h('div', 'fb-head', h('h2', null, title), x);
}
// arrows move between the buttons of one list; Esc closes and returns focus to the trigger
function popKeys(o, list) {
o.pop.addEventListener('keydown', function (e) {
if (e.key === 'Escape') { e.stopPropagation(); closePop(o, true); return; }
var items = list(), i = items.indexOf(e.target);
if (i < 0) return;
var d = { ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1 }[e.key];
if (e.key === 'Home') { e.preventDefault(); items[0].focus(); }
else if (e.key === 'End') { e.preventDefault(); items[items.length - 1].focus(); }
else if (d) { e.preventDefault(); items[(i + d + items.length) % items.length].focus(); }
});
// keep Tab inside the sheet on phones
o.pop.addEventListener('keydown', function (e) {
if (e.key !== 'Tab' || !matchMedia('(max-width: 767px)').matches) return;
var f = Array.prototype.slice.call(o.pop.querySelectorAll('button:not([disabled]), input')).filter(function (n) { return n.offsetParent; });
if (!f.length) return;
if (e.shiftKey && document.activeElement === f[0]) { e.preventDefault(); f[f.length - 1].focus(); }
else if (!e.shiftKey && document.activeElement === f[f.length - 1]) { e.preventDefault(); f[0].focus(); }
});
}
function mkScrim(o) { var s = h('div', 'fb-scrim'); s.hidden = true; s.addEventListener('click', function () { closePop(o, true); }); return s; }
function buildRangePicker() {
var box = $('#range-picker');
clear(box);
rp.btn = el('button', { type: 'button', class: 'btn rp-btn', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'aria-controls': 'rp-pop', 'aria-label': t('range.picker'), title: t('range.keys') });
rp.label = h('span', 'rp-label');
rp.btn.appendChild(rp.label);
rp.btn.appendChild(h('span', 'rp-caret', '\u25BE'));
rp.btn.lastChild.setAttribute('aria-hidden', 'true');
rp.btn.addEventListener('click', function () { rp.open ? closeRangePicker(true) : openRangePicker(); });
var sc = h('div', 'seg rp-shortcuts');
sc.setAttribute('role', 'group'); sc.setAttribute('aria-label', t('range.label'));
SHORTCUTS.forEach(function (p) {
var b = el('button', { type: 'button', 'data-range': p }, parseInt(p, 10) + ' ' + p.slice(-1));
b.addEventListener('click', function () { setShell({ range: p, from: null, to: null }); });
sc.appendChild(b);
});
rp.pop = h('div', 'popover rp-pop');
rp.btn = el('button', { type: 'button', class: 'fb-trigger fb-period', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'aria-controls': 'rp-pop' });
rp.label = h('span', 'fb-val');
rp.tz = h('span', 'fb-tz');
rp.btn.appendChild(svgIcon(IC.clock));
rp.btn.appendChild(h('span', 'fb-txt', h('span', 'fb-k', t('range.label')), rp.label));
rp.btn.appendChild(rp.tz);
rp.btn.appendChild(h('span', 'fb-caret', svgIcon(IC.caret)));
rp.btn.addEventListener('click', function () { rp.open ? closePop(rp, true) : openRangePicker(); });
rp.prev = el('button', { type: 'button', class: 'fb-step', 'aria-label': t('fb.prev'), title: t('fb.prev') + ' (←)' }, svgIcon(IC.prev));
rp.next = el('button', { type: 'button', class: 'fb-step', 'aria-label': t('fb.next'), title: t('fb.next') + ' (→)' }, svgIcon(IC.next));
rp.prev.addEventListener('click', function () { shiftWindow(-1); });
rp.next.addEventListener('click', function () { shiftWindow(1); });
rp.pop = h('div', 'fb-pop fb-pop-period');
rp.pop.id = 'rp-pop'; rp.pop.setAttribute('role', 'dialog'); rp.pop.setAttribute('aria-label', t('range.picker')); rp.pop.hidden = true;
rp.pop.appendChild(sheetHead(t('range.picker'), rp));
var rel = h('div', 'fb-col fb-rel');
rel.appendChild(h('div', 'fb-title', t('fb.relative')));
PRESET_GROUPS.forEach(function (g) {
var grp = h('div', 'chip-group');
var grp = h('div', 'fb-chips');
grp.setAttribute('role', 'group'); grp.setAttribute('aria-label', t(g[0]));
g[1].forEach(function (p) {
var b = el('button', { type: 'button', class: 'chip-btn', 'data-range': p, 'aria-pressed': 'false' }, parseInt(p, 10) + ' ' + p.slice(-1));
var n = parseInt(p, 10), lbl = p.slice(-1) === 'h' ? pl('range.nh', n, { n: nf(n) }) : pl('range.nd', n, { n: nf(n) });
var b = el('button', { type: 'button', class: 'fb-chip', 'data-range': p, 'aria-pressed': 'false', 'aria-label': lbl, title: lbl }, nf(n) + ' ' + p.slice(-1));
b.addEventListener('click', function () { closeRangePicker(true); setShell({ range: p, from: null, to: null }); });
grp.appendChild(b);
});
rp.pop.appendChild(h('div', 'rp-group', h('div', 'rp-title', t(g[0])), grp));
rel.appendChild(h('div', 'fb-grp', h('span', 'fb-sub', t(g[0])), grp));
});
rp.from = el('input', { type: 'datetime-local', id: 'rp-from' }); rp.to = el('input', { type: 'datetime-local', id: 'rp-to' });
rp.err = h('p', 'rp-err'); rp.err.setAttribute('role', 'alert');
var apply = el('button', { type: 'button', class: 'btn primary' }, t('range.apply'));
var abs = h('div', 'fb-col fb-abs');
rp.from = el('input', { type: 'datetime-local', id: 'rp-from', 'aria-describedby': 'rp-tz rp-err' });
rp.to = el('input', { type: 'datetime-local', id: 'rp-to', 'aria-describedby': 'rp-tz rp-err' });
rp.err = h('p', 'fb-err'); rp.err.id = 'rp-err'; rp.err.setAttribute('role', 'alert');
rp.tzNote = h('p', 'fb-note'); rp.tzNote.id = 'rp-tz';
var apply = el('button', { type: 'button', class: 'btn primary fb-apply' }, t('range.apply'));
apply.addEventListener('click', applyCustom);
rp.pop.appendChild(h('div', 'rp-group rp-custom', h('div', 'rp-title', t('range.custom')),
h('label', null, h('span', null, t('range.from')), rp.from), h('label', null, h('span', null, t('range.to')), rp.to), rp.err, apply));
rp.pop.appendChild(h('p', 'note rp-keys', t('range.keys')));
rp.pop.addEventListener('keydown', function (e) {
var tg = e.target;
if (e.key === 'Escape') { e.stopPropagation(); closeRangePicker(true); return; }
if (tg.classList && tg.classList.contains('chip-btn') && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].indexOf(e.key) >= 0) {
var list = presetButtons(), i = list.indexOf(tg), d = (e.key === 'ArrowLeft' || e.key === 'ArrowUp') ? -1 : 1;
e.preventDefault(); list[(i + d + list.length) % list.length].focus();
}
});
rp.scrim = h('div', 'scrim rp-scrim'); rp.scrim.hidden = true;
rp.scrim.addEventListener('click', function () { closeRangePicker(true); });
box.appendChild(rp.btn); box.appendChild(sc); box.appendChild(rp.pop); box.appendChild(rp.scrim);
[rp.from, rp.to].forEach(function (i) { i.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); applyCustom(); } }); });
abs.appendChild(h('div', 'fb-title', t('fb.absolute')));
abs.appendChild(el('label', { class: 'fb-field', for: 'rp-from' }, h('span', null, t('range.from')), rp.from));
abs.appendChild(el('label', { class: 'fb-field', for: 'rp-to' }, h('span', null, t('range.to')), rp.to));
abs.appendChild(rp.tzNote); abs.appendChild(h('p', 'fb-note', t('fb.retention')));
abs.appendChild(rp.err); abs.appendChild(apply);
rp.pop.appendChild(h('div', 'fb-cols', rel, abs));
rp.pop.appendChild(h('p', 'fb-keys', t('range.keys')));
popKeys(rp, presetButtons);
rp.scrim = mkScrim(rp);
box.appendChild(rp.prev); box.appendChild(rp.btn); box.appendChild(rp.next); box.appendChild(rp.pop); box.appendChild(rp.scrim);
rp.open = false;
buildHostPicker();
buildSummary();
renderRangePicker();
}
// ---- host picker: hosts are the probes; shows online/offline and how many are up
function buildHostPicker() {
var box = $('#host-picker');
if (!box) return;
clear(box);
hp.btn = el('button', { type: 'button', class: 'fb-trigger fb-host', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'aria-controls': 'hp-pop' });
hp.dot = h('span', 'fb-dot');
hp.label = h('span', 'fb-val');
hp.count = h('span', 'fb-count');
hp.btn.appendChild(svgIcon(IC.server));
hp.btn.appendChild(h('span', 'fb-txt', h('span', 'fb-k', t('host.label')), h('span', 'fb-valrow', hp.dot, hp.label)));
hp.btn.appendChild(hp.count);
hp.btn.appendChild(h('span', 'fb-caret', svgIcon(IC.caret)));
hp.btn.addEventListener('click', function () { hp.open ? closePop(hp, true) : openPop(hp, '.fb-opt[aria-pressed="true"]'); });
hp.pop = h('div', 'fb-pop fb-pop-host');
hp.pop.id = 'hp-pop'; hp.pop.setAttribute('role', 'dialog'); hp.pop.setAttribute('aria-label', t('fb.host.pick')); hp.pop.hidden = true;
hp.list = h('div', 'fb-opts'); hp.list.setAttribute('role', 'group'); hp.list.setAttribute('aria-label', t('host.label'));
hp.pop.appendChild(sheetHead(t('fb.host.pick'), hp));
hp.pop.appendChild(hp.list);
popKeys(hp, hostOptions);
hp.scrim = mkScrim(hp);
box.appendChild(hp.btn); box.appendChild(hp.pop); box.appendChild(hp.scrim);
box.hidden = true;
}
function hostOpt(value, name, meta, tone) {
var sel = hostList(state.host), on = value === 'all' ? !sel.length : sel.indexOf(value) >= 0;
var b = el('button', { type: 'button', class: 'fb-opt', 'data-host': value, 'aria-pressed': on ? 'true' : 'false' },
h('span', 'fb-dot ' + tone), h('span', 'fb-opt-t', h('span', 'fb-opt-n', name), h('span', 'fb-opt-m', meta)), h('span', 'fb-tick', svgIcon(IC.check)));
b.addEventListener('click', function () {
// "all" clears the selection; any other row toggles that probe (several can be on); all of them, or none, is "all"
var cur = hostList(state.host), next;
if (value === 'all') next = [];
else {
var i = cur.indexOf(value);
next = i >= 0 ? cur.filter(function (n) { return n !== value; }) : cur.concat([value]);
var names = (state.hostList || []).map(function (x) { return x.name; });
if (names.length && names.every(function (n) { return next.indexOf(n) >= 0; })) next = [];
}
var nv = hostJoin(next);
if (value === 'all') closePop(hp, true);
if (nv !== state.host) setShell({ host: nv });
});
return b;
}
function renderHostPicker() {
if (!hp.btn) return;
var hosts = state.hostList || [], on = hosts.filter(function (x) { return x.online; }).length;
$('#host-picker').hidden = hosts.length < 2;
var sel = hostList(state.host), picked = hosts.filter(function (x) { return sel.indexOf(x.name) >= 0; });
var pOn = picked.filter(function (x) { return x.online; }).length;
hp.label.textContent = !sel.length ? t('host.all') : sel.join(', ');
var tone = !sel.length ? (on === hosts.length ? 'on' : on ? 'warn' : 'off') : (pOn === picked.length && picked.length ? 'on' : pOn ? 'warn' : 'off');
hp.dot.className = 'fb-dot ' + tone;
hp.count.textContent = !sel.length ? on + '/' + hosts.length : (sel.length > 1 ? pOn + '/' + picked.length : (pOn ? t('host.online') : t('host.offline')));
hp.count.className = 'fb-count ' + tone;
hp.btn.setAttribute('aria-label', t('host.label') + ': ' + hp.label.textContent + ', ' + t('fb.host.status', { n: on, m: hosts.length }));
var want = hosts.map(function (x) { return x.name + (x.online ? '1' : '0') + (x.version || ''); }).join('|') + '|' + state.host + '|' + lang;
if (hp.list.getAttribute('data-k') === want) return;
hp.list.setAttribute('data-k', want);
clear(hp.list);
hp.list.appendChild(hostOpt('all', t('host.all'), t('fb.host.status', { n: on, m: hosts.length }), on === hosts.length ? 'on' : on ? 'warn' : 'off'));
hosts.forEach(function (x) {
var meta = [x.online ? t('host.online') : t('host.offline')];
if (x.self) meta.push(t('host.self'));
if (x.version) meta.push(x.version);
if (!x.online && x.last_seen) meta.push(ago(x.last_seen));
hp.list.appendChild(hostOpt(x.name, x.name, meta.join(' · '), x.online ? 'on' : 'off'));
});
}
// ---- summary line: what is applied, live/fixed, clear, copy link
function buildSummary() {
var tools = $('#slice-tools');
if (!tools) return;
clear(tools);
rp.clear = el('button', { type: 'button', class: 'fb-link' }, t('fb.clear'));
rp.clear.title = t('fb.clear.title');
rp.clear.addEventListener('click', function () { state.domain = 'all'; setShell({ range: DEFAULT_RANGE, from: null, to: null, host: 'all' }); });
var copy = el('button', { type: 'button', class: 'fb-link fb-copy', title: t('fb.copy.title') }, svgIcon(IC.link), h('span', null, t('fb.copy')));
copy.addEventListener('click', function () {
var done = function () { toast(t('fb.copied')); }, url = location.href;
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(url).then(done, function () { toast(url); });
else toast(url);
});
tools.appendChild(rp.clear); tools.appendChild(copy);
}
// ---------------------------------------------------------------- shell
function setSliceNote(text) { state.note = text || ''; renderSlice(); }
function renderSlice() {
var p = $('#slice-text');
if (!p) return;
clear(p);
var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: state.host })];
var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: hostList(state.host).join(', ') })];
if (current && pages[current.id] && pages[current.id].domain) parts.push(state.domain === 'all' ? t('slice.allDomains') : t('slice.domain', { name: state.domain }));
if (state.note) parts.push(state.note);
p.appendChild(document.createTextNode(t('slice.showing') + ' '));
var live = !isCustom();
var mode = h('span', 'fb-mode ' + (live ? 'is-live' : 'is-fixed'), h('span', 'fb-pulse'), live ? t('fb.live') : t('fb.fixed'));
mode.title = live ? t('fb.live.title') : t('fb.fixed.title');
p.appendChild(mode);
p.appendChild(document.createTextNode(' ' + t('slice.showing') + ' '));
p.appendChild(h('strong', null, rangeArticle()));
p.appendChild(document.createTextNode(' · ' + parts.join(' · ')));
p.appendChild(document.createTextNode(' (' + tzName() + ') · ' + parts.join(' · ')));
$('#domain').hidden = !(current && pages[current.id] && pages[current.id].domain);
if (rp.clear) rp.clear.hidden = isDefaultSlice();
renderRangePicker();
}
// the bar sticks under the top bar; once it is stuck the summary line folds away
function watchStick() {
var bar = $('#slice'), s = $('#slice-sentinel');
if (!bar || !s || !window.IntersectionObserver) return;
new IntersectionObserver(function (es) { bar.classList.toggle('is-stuck', !es[0].isIntersecting); }, { rootMargin: '-' + (parseInt(cssVar('--topbar-h'), 10) || 64) + 'px 0px 0px 0px' }).observe(s);
}
function navId() { return current ? (current.id === 'ip' ? 'ips' : current.id) : null; }
// small counter on a rail/tab item (e.g. open incidents); n <= 0 removes it. Set by page scripts.
var navBadges = {};
@@ -2134,17 +2329,15 @@
}
function updateHostSelect(s) {
var sel = $('#host'), hosts = s.hosts || [];
var want = hosts.map(function (x) { return x.name; }).join('|') + '|' + lang;
if (sel.getAttribute('data-hosts') !== want) {
clear(sel);
sel.appendChild(el('option', { value: 'all' }, t('host.all')));
hosts.forEach(function (x) { sel.appendChild(el('option', { value: x.name }, x.name)); });
sel.setAttribute('data-hosts', want);
var hosts = s.hosts || [];
state.hostList = hosts;
if (state.host !== 'all' && hosts.length) {
var known = hostList(state.host).filter(function (n) { return hosts.some(function (x) { return x.name === n; }); });
if (known.length === hosts.length) known = [];
var kv = hostJoin(known);
if (kv !== state.host) { state.host = kv; lsSet('urutau.host', kv); }
}
if (state.host !== 'all' && !hosts.some(function (x) { return x.name === state.host; })) { state.host = 'all'; lsSet('urutau.host', 'all'); }
sel.value = state.host;
sel.hidden = hosts.length < 2;
renderHostPicker();
}
function shellSummary() {
return getSummary(ctx()).then(function (s) {
@@ -2167,7 +2360,7 @@
buildRangePicker();
readSlice(parseHash().query);
renderRangePicker();
$('#host').addEventListener('change', function (e) { setShell({ host: e.target.value }); });
watchStick();
$('#domain').addEventListener('change', function (e) { state.domain = e.target.value; renderSlice(); notifyPage(); });
$('#lang').addEventListener('click', function () {
lang = lang === 'en' ? 'pt-BR' : 'en'; lsSet('urutau.lang', lang);
@@ -2198,7 +2391,7 @@
return;
}
if (e.ctrlKey || e.metaKey || e.altKey || typing(e) || !box.hidden) return;
if (e.key === 't') { e.preventDefault(); rp.open ? closeRangePicker(true) : openRangePicker(); }
if (e.key === 't') { e.preventDefault(); rp.open ? closePop(rp, true) : openRangePicker(); }
else if (e.key === '[') stepPreset(-1);
else if (e.key === ']') stepPreset(1);
else if ((e.key === 'ArrowLeft' || e.key === 'ArrowRight') && e.target === document.body && isCustom()) { e.preventDefault(); shiftWindow(e.key === 'ArrowLeft' ? -1 : 1); }
@@ -2206,7 +2399,7 @@
document.addEventListener('click', function (e) {
var more = $('#more');
if (!more.hidden && !more.contains(e.target) && !$('#tabbar').contains(e.target)) setMore(false);
if (rp.open && !$('#range-picker').contains(e.target)) closeRangePicker(false);
if ((rp.open || hp.open) && !$('#slice').contains(e.target)) closeRangePicker(false);
if (helpPinned) hideHelp();
});
window.addEventListener('hashchange', route);
+44 -2
View File
@@ -20,7 +20,6 @@ window.URUTAU_I18N = {
'host.label': 'Host',
'host.all': 'All hosts',
'range.label': 'Time range',
'range.custom': 'Custom',
'range.in.nh.one': 'in the last hour',
'range.in.nh.other': 'in the last {n} hours',
'range.in.nd.one': 'in the last day',
@@ -126,6 +125,28 @@ window.URUTAU_I18N = {
'slice.domain': 'domain {name}',
'slice.ips.one': '{n} IP',
'slice.ips.other': '{n} IPs',
'fb.label': 'Filters: period and host',
'fb.period.title': 'Period of every panel (time zone {tz}). Shortcut: t',
'fb.tz': 'Times in {tz}.',
'fb.err.old': 'The start is older than the 30-day retention.',
'fb.err.future': 'The start is in the future.',
'fb.close': 'Close',
'fb.prev': 'Previous window',
'fb.next': 'Next window',
'fb.relative': 'Relative to now',
'fb.absolute': 'Exact window',
'fb.retention': 'Data is kept for 30 days; a window can span up to 30 days.',
'fb.host.pick': 'Choose host',
'fb.host.status': '{n} of {m} online',
'fb.clear': 'Clear filters',
'fb.clear.title': 'Back to the last 24 hours on all hosts',
'fb.copy': 'Copy link',
'fb.copy.title': 'Copy a link to this exact view',
'fb.copied': 'Link copied.',
'fb.live': 'Live',
'fb.live.title': 'Relative period: the window moves with the clock and refreshes every 10 s.',
'fb.fixed': 'Fixed',
'fb.fixed.title': 'Exact window: the data does not move with the clock.',
'kpi.requests': 'Requests',
'kpi.malicious': 'Malicious events',
'kpi.hostile': 'Hostile IPs',
@@ -535,7 +556,6 @@ window.URUTAU_I18N = {
'host.label': 'Host',
'host.all': 'Todos os hosts',
'range.label': 'Período',
'range.custom': 'Personalizado',
'range.in.nh.one': 'na última hora',
'range.in.nh.other': 'nas últimas {n} horas',
'range.in.nd.one': 'no último dia',
@@ -641,6 +661,28 @@ window.URUTAU_I18N = {
'slice.domain': 'domínio {name}',
'slice.ips.one': '{n} IP',
'slice.ips.other': '{n} IPs',
'fb.label': 'Filtros: período e host',
'fb.period.title': 'Período de todos os painéis (fuso {tz}). Atalho: t',
'fb.tz': 'Horários em {tz}.',
'fb.err.old': 'O início é anterior à retenção de 30 dias.',
'fb.err.future': 'O início está no futuro.',
'fb.close': 'Fechar',
'fb.prev': 'Janela anterior',
'fb.next': 'Janela seguinte',
'fb.relative': 'Relativo a agora',
'fb.absolute': 'Janela exata',
'fb.retention': 'Os dados ficam 30 dias; a janela pode ter até 30 dias.',
'fb.host.pick': 'Escolher host',
'fb.host.status': '{n} de {m} online',
'fb.clear': 'Limpar filtros',
'fb.clear.title': 'Voltar às últimas 24 horas em todos os hosts',
'fb.copy': 'Copiar link',
'fb.copy.title': 'Copiar um link para esta visão exata',
'fb.copied': 'Link copiado.',
'fb.live': 'Ao vivo',
'fb.live.title': 'Período relativo: a janela acompanha o relógio e atualiza a cada 10 s.',
'fb.fixed': 'Fixo',
'fb.fixed.title': 'Janela exata: os dados não acompanham o relógio.',
'kpi.requests': 'Requisições',
'kpi.malicious': 'Eventos maliciosos',
'kpi.hostile': 'IPs hostis',
+95 -56
View File
@@ -26,66 +26,96 @@
.inc-id { font-weight: 600; white-space: nowrap; }
/* ---------------- list */
.inc-bar { display: flex; flex-wrap: nowrap; align-items: center; justify-content: space-between; gap: var(--s-4); margin-bottom: var(--s-4); border-bottom: 1px solid var(--line); }
.inc-tabwrap { display: flex; align-items: center; gap: var(--s-2); min-width: 0; flex: 1 1 auto; }
.inc-bar { display: flex; flex-direction: column; align-items: stretch; gap: var(--s-2); margin-bottom: var(--s-3); }
.inc-tabwrap { display: flex; align-items: center; gap: var(--s-2); min-width: 0; border-bottom: 1px solid var(--line); }
.inc-info { color: var(--ink-muted); cursor: help; font-size: 1rem; flex: none; }
.inc-tabs { display: flex; flex-wrap: nowrap; overflow-x: auto; gap: var(--s-1); min-width: 0; scrollbar-width: thin; }
.inc-tab { display: inline-flex; align-items: center; gap: 6px; height: 36px; padding: 0 var(--s-3); border: 0; border-bottom: 2px solid transparent; background: none; color: var(--ink-muted); cursor: pointer; font: inherit; font-size: .875rem; white-space: nowrap; flex: none; margin-bottom: -1px; }
.inc-tabs { display: flex; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; gap: 0; min-width: 0; scrollbar-width: thin; }
.inc-tab { display: inline-flex; align-items: center; gap: 6px; height: 40px; padding: 0 10px; border: 0; border-bottom: 2px solid transparent; background: none; color: var(--ink-muted); cursor: pointer; font: inherit; font-size: .875rem; white-space: nowrap; flex: none; }
.inc-tabs .inc-tab:focus-visible { box-shadow: inset 0 0 0 2px var(--accent); }
.inc-tab:hover { color: var(--ink); }
.inc-tab.on { color: var(--ink); font-weight: 600; border-bottom-color: var(--accent); }
.inc-tab.zero { opacity: .6; }
.inc-n { font-size: .75rem; color: var(--ink-muted); background: var(--surface-raised); border-radius: 999px; padding: 0 6px; }
.inc-tab-sep { width: 1px; background: var(--line); margin: 8px var(--s-2); flex: none; }
.inc-toolbar { display: flex; flex-wrap: wrap; gap: var(--s-2); align-items: center; padding-bottom: var(--s-2); flex: none; }
.inc-search { width: 240px; max-width: 100%; }
@media (max-width: 1500px) {
.inc-bar { flex-direction: column; align-items: stretch; gap: var(--s-2); border-bottom: 0; }
.inc-tabwrap { border-bottom: 1px solid var(--line); }
.inc-toolbar { padding-bottom: 0; }
.inc-search { flex: 1 1 200px; }
}
.inc-tab.zero { opacity: .55; }
.inc-n { font-size: .75rem; color: var(--ink-muted); background: var(--surface-raised); border-radius: 999px; padding: 0 6px; min-width: 1.25rem; text-align: center; }
.inc-tab.on .inc-n { background: var(--accent-soft); color: var(--accent); }
.inc-tab-sep { width: 1px; background: var(--line); margin: 10px 4px; flex: none; }
.inc-toolbar { display: flex; flex-wrap: wrap; gap: var(--s-2); align-items: center; }
.inc-search { flex: 1 1 260px; min-width: 0; }
.inc-table { border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-panel); }
.inc-thead, .inc-row {
display: grid; grid-template-columns: 10px 64px minmax(0, 1fr) 124px 90px 200px 76px; gap: var(--s-3); align-items: center; padding: 8px var(--s-3);
}
.inc-thead { border-radius: var(--radius-sm) var(--radius-sm) 0 0; position: sticky; top: var(--topbar-h, 56px); z-index: 2; background: var(--surface-raised); border-bottom: 1px solid var(--line); font-size: .75rem; color: var(--ink-muted); text-transform: uppercase; letter-spacing: .04em; }
/* severity: a word, not only a colour; the row's left edge repeats it */
.inc-sev { display: inline-flex; align-items: center; gap: 6px; font-size: .75rem; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; white-space: nowrap; color: var(--ink-muted); }
.inc-sev::before { content: ""; width: 8px; height: 8px; border-radius: 2px; background: var(--sev-info); flex: none; }
.inc-sev-critical { color: var(--sev-critical); } .inc-sev-critical::before { background: var(--sev-critical); }
.inc-sev-high { color: var(--sev-high); } .inc-sev-high::before { background: var(--sev-high); }
.inc-sev-medium { color: var(--sev-medium); } .inc-sev-medium::before { background: var(--sev-medium); }
.inc-sev-low { color: var(--info); } .inc-sev-low::before { background: var(--info); }
.inc-table { border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-panel); overflow: hidden; }
.inc-thead, .inc-row { display: grid; grid-template-columns: 84px minmax(0, 1fr) 150px 120px 56px 80px; gap: var(--s-3); align-items: center; padding: 10px var(--s-4) 10px calc(var(--s-4) - 3px); }
.inc-thead { padding-top: 8px; padding-bottom: 8px; background: var(--surface-raised); border-bottom: 1px solid var(--line); font-size: .75rem; color: var(--ink-muted); text-transform: uppercase; letter-spacing: .04em; border-left: 3px solid transparent; }
.inc-thead .r { text-align: right; }
.inc-row { min-height: 44px; box-sizing: border-box; color: var(--ink); text-decoration: none; border-bottom: 1px solid var(--line); }
.inc-row { min-height: 56px; box-sizing: border-box; color: var(--ink); text-decoration: none; border-bottom: 1px solid var(--line); border-left: 3px solid transparent; }
.inc-row.inc-s-critical { border-left-color: var(--sev-critical); }
.inc-row.inc-s-high { border-left-color: var(--sev-high); }
.inc-row.inc-s-medium { border-left-color: var(--sev-medium); }
.inc-row:last-child { border-bottom: 0; }
.inc-row:hover { background: var(--surface-raised); }
.inc-row:hover .inc-title { color: var(--accent); }
.inc-row:focus-visible { outline: 0; box-shadow: inset 0 0 0 2px var(--accent); }
.inc-main { display: flex; align-items: center; gap: var(--s-2); min-width: 0; }
.inc-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; font-weight: 500; }
.inc-rtags { display: inline-flex; gap: 4px; flex: none; }
.inc-rtags .chip { margin: 0; font-size: .75rem; }
.inc-who, .inc-where { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .8125rem; color: var(--ink-muted); min-width: 0; }
.inc-where { font-size: .75rem; }
.inc-main { display: grid; gap: 3px; min-width: 0; }
.inc-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; font-weight: 600; font-size: .9375rem; }
.inc-rmeta { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: .75rem; color: var(--ink-muted); white-space: nowrap; overflow: hidden; }
.inc-rid { color: var(--ink-faint); flex: none; }
.inc-sep { color: var(--ink-faint); flex: none; }
.inc-trunc { overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 0 1 auto; }
.inc-tag { flex: none; padding: 0 6px; border-radius: 4px; background: var(--surface-raised); border: 1px solid var(--line); color: var(--ink-muted); font-size: .75rem; line-height: 18px; }
.inc-cc { flex: none; display: inline-flex; align-items: center; gap: 3px; }
.inc-cc::before { content: ""; width: 12px; height: 12px; background: currentColor; -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.2'%3E%3Cpath d='M4 5h16v11H9l-5 4z'/%3E%3C/svg%3E") center/contain no-repeat; mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.2'%3E%3Cpath d='M4 5h16v11H9l-5 4z'/%3E%3C/svg%3E") center/contain no-repeat; }
.inc-c-st { min-width: 0; }
.inc-c-st .badge { max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
.inc-who { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .8125rem; min-width: 0; }
.inc-who.none { color: var(--ink-faint); font-style: italic; }
.inc-cnt { text-align: right; font-size: .8125rem; color: var(--ink-muted); font-variant-numeric: tabular-nums; }
.inc-when { text-align: right; font-size: .8125rem; color: var(--ink-muted); white-space: nowrap; }
.inc-empty { display: grid; justify-items: center; gap: var(--s-2); padding: 48px var(--s-4); text-align: center; }
.inc-results .pgr { margin-top: var(--s-4); }
@media (max-width: 1100px) {
.inc-thead, .inc-row { grid-template-columns: 76px minmax(0, 1fr) 140px 72px; }
.inc-thead > :nth-child(4), .inc-thead > :nth-child(5), .inc-row > .inc-who, .inc-row > .inc-cnt { display: none; }
}
@media (max-width: 720px) {
.inc-thead { display: none; }
.inc-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-1) var(--s-3); padding: var(--s-3); }
.inc-row > :nth-child(3) { order: 4; flex: 1 1 100%; }
.inc-row > :nth-child(4) { order: 5; flex: none; }
.inc-row > :nth-child(5) { order: 6; flex: none; }
.inc-row > :nth-child(6) { order: 7; flex: 1 1 100%; }
.inc-row > :nth-child(7) { order: 3; margin-left: auto; }
.inc-search { width: 100%; flex-basis: 100%; }
.inc-row { grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "sev st when" "main main main" "who who cnt"; gap: 6px var(--s-2); padding: var(--s-3); }
.inc-row > .inc-c-sev { grid-area: sev; }
.inc-row > .inc-c-st { grid-area: st; }
.inc-row > .inc-when { grid-area: when; }
.inc-row > .inc-main { grid-area: main; }
.inc-row > .inc-who { grid-area: who; display: block; font-size: .75rem; color: var(--ink-muted); }
.inc-row > .inc-cnt { grid-area: cnt; display: block; font-size: .75rem; }
.inc-title { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
.inc-rmeta { flex-wrap: wrap; row-gap: 2px; white-space: normal; }
.inc-trunc { max-width: 100%; white-space: nowrap; }
.inc-toolbar > select { flex: 1 1 calc(50% - var(--s-2)); min-width: 0; }
.inc-toolbar > .btn { flex: 1 1 100%; }
.inc-search { flex-basis: 100%; }
}
/* ---------------- detail */
.inc-back { display: inline-block; margin-bottom: var(--s-3); color: var(--accent); text-decoration: none; font-size: .875rem; }
.inc-back:hover { text-decoration: underline; }
.inc-detail.busy { pointer-events: none; }
.inc-head { position: sticky; top: var(--topbar-h, 56px); z-index: 5; display: grid; gap: var(--s-2); padding: var(--s-3) 0; margin-bottom: var(--s-4); background: var(--surface-base); border-bottom: 1px solid var(--line); }
.inc-h1 { display: flex; align-items: center; gap: var(--s-3); min-width: 0; }
.inc-h-title { flex: 1 1 auto; margin: 0; font-size: 1.25rem; font-weight: 700; min-width: 0; line-height: 1.3; }
.inc-title-btn { all: unset; cursor: text; display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.inc-backnav { margin-bottom: var(--s-2); }
.inc-head { display: grid; gap: var(--s-2); padding: 0 0 var(--s-4); margin-bottom: var(--s-4); border-bottom: 1px solid var(--line); min-width: 0; }
.inc-crumb { display: flex; gap: 6px; font-size: .8125rem; color: var(--ink-muted); }
.inc-facts { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; margin: 0; font-size: .8125rem; color: var(--ink-muted); }
.inc-fk { color: var(--ink-faint); }
.inc-facts strong { color: var(--ink); font-weight: 600; }
.inc-supb { background: var(--surface-raised); }
.inc-h1 { display: flex; align-items: flex-start; gap: var(--s-3); min-width: 0; }
.inc-h-title { flex: 1 1 auto; margin: 0; font-size: 1.375rem; overflow-wrap: anywhere; font-weight: 700; min-width: 0; line-height: 1.3; }
.inc-title-btn { all: unset; cursor: text; display: block; max-width: 100%; white-space: normal; overflow-wrap: anywhere; border-radius: 4px; }
.inc-title-btn:hover { text-decoration: underline dotted; }
.inc-title-in { width: 100%; box-sizing: border-box; font-size: 1.125rem; }
.inc-quick { display: flex; gap: var(--s-2); flex: none; }
.inc-quick { display: flex; flex-wrap: wrap; gap: var(--s-2); flex: none; justify-content: flex-end; }
.inc-q-tp:not(:disabled) { border-color: var(--danger); color: var(--danger); }
.inc-q-ok:not(:disabled) { border-color: var(--ok); color: var(--ok); }
.inc-h2 { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2); min-width: 0; }
@@ -94,7 +124,7 @@
.inc-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: var(--s-4); align-items: start; max-width: 1280px; }
.inc-maincol { display: grid; gap: var(--s-4); min-width: 0; }
.inc-aside { display: grid; gap: var(--s-4); position: sticky; top: calc(var(--topbar-h, 56px) + 96px); min-width: 0; align-self: start; }
.inc-aside { display: grid; gap: var(--s-4); position: sticky; top: calc(var(--topbar-h, 56px) + 16px); min-width: 0; align-self: start; }
.inc-card { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: var(--s-3) var(--s-4); min-width: 0; box-sizing: border-box; }
.inc-card h2, .inc-tech summary { margin: 0 0 var(--s-3); font-size: .9375rem; font-weight: 600; }
.inc-card-h { display: flex; align-items: center; justify-content: space-between; gap: var(--s-2); margin-bottom: var(--s-2); }
@@ -150,6 +180,25 @@
.inc-grp summary { cursor: pointer; list-style: none; display: flex; align-items: baseline; gap: var(--s-2); }
.inc-grp summary::-webkit-details-marker { display: none; }
.inc-sub { margin: var(--s-2) 0 0 var(--s-4); }
.inc-card h3 { margin: 0 0 4px; font-size: .75rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; color: var(--ink-muted); }
.inc-verdict + .inc-evid { margin-top: var(--s-3); }
.inc-evid .inc-pre { margin-top: 0; }
.inc-supbox { margin-top: var(--s-3); padding: var(--s-3); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); display: grid; gap: 6px; }
.inc-supbox.on { border-color: color-mix(in srgb, var(--warn) 55%, transparent); background: var(--warn-soft); }
.inc-supbox.off label { color: var(--ink-muted); }
.inc-sup-row { display: flex; align-items: center; justify-content: space-between; gap: var(--s-3); }
.inc-sup-row label { font-size: .875rem; font-weight: 600; }
.inc-supbox .inc-switch { margin: 0; flex: none; }
.inc-supbox p { margin: 0; }
.inc-why summary { cursor: pointer; font-size: .8125rem; color: var(--accent); }
.inc-why p { margin: 4px 0 0; }
/* activity as a timeline: comments are cards, system changes are quiet lines on the rail */
.inc-activity .inc-feed:not(.inc-sub) { position: relative; padding-left: 20px; }
.inc-activity .inc-feed:not(.inc-sub)::before { content: ""; position: absolute; left: 6px; top: 4px; bottom: 4px; width: 2px; background: var(--line); }
.inc-activity .inc-feed > li { position: relative; }
.inc-activity .inc-feed:not(.inc-sub) > .inc-cmt::before { content: ""; position: absolute; left: -18px; top: 18px; width: 10px; height: 10px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 3px var(--surface-panel); }
.inc-activity .inc-feed:not(.inc-sub) > .inc-ev > .inc-ev-dot, .inc-activity .inc-feed:not(.inc-sub) > .inc-grp summary > .inc-ev-dot { position: absolute; left: -16px; top: 7px; margin: 0; box-shadow: 0 0 0 3px var(--surface-panel); }
.inc-ev { padding: 2px 0; line-height: 1.5; }
@media (max-width: 900px) {
.inc-head { position: static; }
@@ -157,7 +206,7 @@
.inc-aside { display: contents; position: static; }
.inc-props { order: 1; }
.inc-maincol { order: 2; width: 100%; }
.inc-tech { order: 3; }
.inc-tech { order: 3; width: 100%; }
}
@media (max-width: 600px) {
.inc-h1 { flex-wrap: wrap; }
@@ -166,21 +215,11 @@
.inc-metaline { margin-left: 0; flex-basis: 100%; }
}
.inc-st { min-width: 0; }
.inc-st .badge { max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
.inc-row:last-child { border-radius: 0 0 var(--radius-sm) var(--radius-sm); }
.inc-keyrow > :not(.inc-key) { flex: none; white-space: nowrap; }
.inc-dl dd { min-width: 0; }
.inc-main { flex-direction: column; align-items: stretch; justify-content: center; gap: 2px; }
.inc-mrow { display: flex; align-items: center; gap: var(--s-2); min-width: 0; }
.inc-sub { font-size: .75rem; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.inc-tabs { gap: 0; }
.inc-tab { padding: 0 10px; font-size: .8125rem; }
.inc-tab-sep { margin: 8px 4px; }
.inc-main > .inc-sub { padding: 0; margin: 0; background: none; border: 0; align-self: flex-start; max-width: 100%; }
@media (max-width: 600px) {
.inc-quick { flex-wrap: wrap; overflow-x: visible; }
.inc-quick { overflow-x: visible; justify-content: stretch; }
.inc-quick .btn { flex: 1 1 auto; }
.inc-toolbar > select { flex: 1 1 calc(50% - var(--s-2)); min-width: 0; }
.inc-toolbar > .btn { flex: 1 1 100%; }
.inc-h-title { font-size: 1.1875rem; }
.inc-cmt { padding: var(--s-2) var(--s-3); }
}
.inc-supl { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 45%, transparent); }
.inc-supbox select { min-width: 0; max-width: 9rem; }
+93 -37
View File
@@ -180,7 +180,17 @@
'inc.meta': 'opened {a} · updated {b} · {n} occurrences',
'inc.h.group': '{who} made {n} changes',
'inc.copy': 'Copy', 'inc.copied': 'Copied',
'inc.title.edit': 'Edit title'
'inc.title.edit': 'Edit title',
'inc.col.count': 'Hits', 'inc.unassigned': 'Unassigned', 'inc.evidence': 'What was detected',
'inc.summary.none': 'No conclusion yet. Write what you found once you know.',
'inc.sup.on': 'On: new identical findings are hidden from the outbound traffic page.',
'inc.sup.what': 'Hide new findings with this same fingerprint from the outbound traffic page.',
'inc.sup.more': 'How it works',
'inc.sup.until': 'Suppressed until {date} (turned on {ago}).', 'inc.sup.until.short': 'Suppressed until {date}',
'inc.sup.only.egress': 'Only tickets from outbound traffic findings can be suppressed.',
'inc.sup.only.low': 'High or critical findings cannot be suppressed.',
'inc.sup.for': 'Suppress for', 'inc.sup.days': '{n} days',
'inc.sup.reopen': 'The ticket reopens by itself when the period ends or if the severity goes up.'
},
'pt-BR': {
'inc.col.id': 'ID', 'inc.col.title': 'Título', 'inc.col.status': 'Status', 'inc.col.assignee': 'Responsável', 'inc.col.where': 'Servidor / destino', 'inc.col.seen': 'Última vez',
@@ -194,7 +204,17 @@
'inc.meta': 'aberto {a} · atualizado {b} · {n} ocorrências',
'inc.h.group': '{who} fez {n} alterações',
'inc.copy': 'Copiar', 'inc.copied': 'Copiado',
'inc.title.edit': 'Editar título'
'inc.title.edit': 'Editar título',
'inc.col.count': 'Ocorr.', 'inc.unassigned': 'Sem responsável', 'inc.evidence': 'O que foi detectado',
'inc.summary.none': 'Ainda sem conclusão. Escreva o que descobriu quando souber.',
'inc.sup.on': 'Ligada: novos achados iguais ficam ocultos na página de tráfego de saída.',
'inc.sup.what': 'Oculta da página de tráfego de saída os novos achados com esta mesma impressão digital.',
'inc.sup.more': 'Como funciona',
'inc.sup.until': 'Suprimido até {date} (ligado {ago}).', 'inc.sup.until.short': 'Suprimido até {date}',
'inc.sup.only.egress': 'Só chamados de achados do tráfego de saída podem ser suprimidos.',
'inc.sup.only.low': 'Achados de severidade alta ou crítica não podem ser suprimidos.',
'inc.sup.for': 'Suprimir por', 'inc.sup.days': '{n} dias',
'inc.sup.reopen': 'O chamado reabre sozinho quando o prazo vence ou se a severidade subir.'
}
});
@@ -248,7 +268,7 @@
// ------------------------------------------------------------ list
function listView(host) {
var seq = 0, on = true, timer = 0;
var results = el('div', { class: 'inc-results' });
var results = el('div', { class: 'inc-results', 'aria-live': 'polite', 'aria-busy': 'false' });
var tabsBox = el('div', { class: 'inc-tabs', role: 'group', 'aria-label': t('inc.tabs') });
var counts = null;
@@ -265,7 +285,7 @@
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
return p;
}
var search = el('input', { type: 'search', class: 'inc-search', autocomplete: 'off', placeholder: t('inc.search'), 'aria-label': t('inc.search') });
var search = el('input', { type: 'search', class: 'inc-search', autocomplete: 'off', placeholder: t('inc.search') + ' /', 'aria-label': t('inc.search') });
search.value = cur().q;
var sevSel = el('select', { 'aria-label': t('inc.f.severity') });
sevSel.appendChild(el('option', { value: '' }, t('inc.sev.all')));
@@ -285,6 +305,14 @@
sevSel.addEventListener('change', function () { U.setParam('sev', sevSel.value); reload(); });
sortSel.addEventListener('change', function () { U.setParam('sort', sortSel.value === 'updated' ? '' : sortSel.value); reload(); });
function slash(e) {
if (e.key !== '/' || e.ctrlKey || e.metaKey || e.altKey) return;
var a = document.activeElement, tag = a && a.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (a && a.isContentEditable) || document.querySelector('dialog[open]')) return;
e.preventDefault(); search.focus();
}
document.addEventListener('keydown', slash);
search.setAttribute('aria-keyshortcuts', '/');
var info = el('span', { class: 'inc-info', tabindex: '0', role: 'img', title: t('inc.lead'), 'aria-label': t('inc.lead') }, 'ⓘ');
host.appendChild(el('div', { class: 'inc-bar' }, el('div', { class: 'inc-tabwrap' }, info, tabsBox), el('div', { class: 'inc-toolbar' }, search, sevSel, sortSel, newBtn)));
host.appendChild(results);
@@ -304,22 +332,24 @@
});
}
function row(it) {
var where = [it.host ? String(it.host) : '', it.dst ? it.dst + (it.dport ? ':' + it.dport : '') : ''].filter(Boolean).join(' · ');
var full = [(it.workload || ''), it.dst ? '→ ' + it.dst + (it.dport ? ':' + it.dport : '') : ''].filter(Boolean).join(' ');
// egress tickets: pattern on top, workload below (the auto title repeats both and gets cut)
var sev = sevOf(it.severity), q = splitId(it);
var dst = it.dst ? it.dst + (it.dport ? ':' + it.dport : '') : '';
// egress tickets: pattern as the headline, workload -> destination in the meta line (the auto title repeats both and gets cut)
var auto = it.source === 'egress' && it.kind && it.workload;
var head = auto ? tr('eg.kind.' + it.kind, String(it.kind)) : String(it.title || it.id);
var titleLine = el('span', { class: 'inc-main' + (auto ? ' two' : '') },
el('span', { class: 'inc-mrow' }, el('strong', { class: 'inc-title', title: String(it.title || it.id) }, head),
(it.tags && it.tags.length) ? el('span', { class: 'inc-rtags' }, tagChips(it.tags.slice(0, 1))) : null),
auto ? el('span', { class: 'inc-sub mono', title: String(it.workload) }, String(it.workload)) : null);
return el('a', { class: 'inc-row', href: U.href('incidents', idSegs(it)), title: full },
dot(it.severity),
el('span', { class: 'inc-id mono', title: splitId(it).full }, splitId(it).full),
titleLine,
el('span', { class: 'inc-st' }, statusBadge(it.status)),
el('span', { class: 'inc-who' }, it.assignee ? String(it.assignee) : '—'),
el('span', { class: 'inc-where mono' }, where),
var head = auto ? tr('eg.kind.' + it.kind, String(it.kind)) : String(it.title || q.full);
var meta = el('span', { class: 'inc-rmeta' }, el('span', { class: 'mono inc-rid' }, q.full));
function add(node) { meta.appendChild(el('span', { class: 'inc-sep', 'aria-hidden': 'true' }, '·')); meta.appendChild(node); }
if (auto) add(el('span', { class: 'mono inc-trunc', title: String(it.workload) + (dst ? ' → ' + dst : '') }, String(it.workload) + (dst ? ' → ' + dst : '')));
else if (dst) add(el('span', { class: 'mono inc-trunc' }, dst));
(Array.isArray(it.tags) ? it.tags.slice(0, 2) : []).forEach(function (g) { add(el('span', { class: 'inc-tag' }, String(g))); });
if (it.suppress) add(el('span', { class: 'inc-tag inc-supl', title: it.suppress_until ? t('inc.sup.until.short', { date: U.fmt.date(it.suppress_until) }) : '' }, t('eg.suppressed.chip')));
if (it.comment_count) add(el('span', { class: 'inc-cc', title: t(it.comment_count === 1 ? 'inc.comments.n.one' : 'inc.comments.n.other', { n: nf(it.comment_count) }) }, nf(it.comment_count)));
return el('a', { class: 'inc-row inc-s-' + sev, href: U.href('incidents', idSegs(it)), title: String(it.title || q.full) },
el('span', { class: 'inc-c-sev' }, el('span', { class: 'inc-sev inc-sev-' + sev }, t('inc.sev.' + sev))),
el('span', { class: 'inc-main' }, el('strong', { class: 'inc-title' }, head), meta),
el('span', { class: 'inc-c-st' }, statusBadge(it.status)),
el('span', { class: 'inc-who' + (it.assignee ? '' : ' none') }, it.assignee ? String(it.assignee) : t('inc.unassigned')),
el('span', { class: 'inc-cnt num', title: t('inc.t.count') }, '×' + nf(it.count || 1)),
el('span', { class: 'inc-when' }, when(it.last_seen)));
}
function paint(r, f) {
@@ -339,8 +369,8 @@
box.appendChild(e);
return;
}
box.appendChild(el('div', { class: 'inc-thead', 'aria-hidden': 'true' }, el('span'), el('span', null, t('inc.col.id')), el('span', null, t('inc.col.title')), el('span', null, t('inc.col.status')),
el('span', null, t('inc.col.assignee')), el('span', null, t('inc.col.where')), el('span', { class: 'r' }, t('inc.col.seen'))));
box.appendChild(el('div', { class: 'inc-thead', 'aria-hidden': 'true' }, el('span', null, t('inc.f.severity')), el('span', null, t('inc.col.title')), el('span', null, t('inc.col.status')),
el('span', null, t('inc.col.assignee')), el('span', { class: 'r' }, t('inc.col.count')), el('span', { class: 'r' }, t('inc.col.seen'))));
items.forEach(function (it) { box.appendChild(row(it)); });
var total2 = r.total || items.length, pages = Math.max(1, Math.ceil(total2 / PER_PAGE));
var pg = U.ui.pager({ page: f.p, pages: pages, total: total2, onPage: function (n) { U.setParam('p', n); load(); window.scrollTo(0, 0); } });
@@ -366,7 +396,7 @@
});
}
load();
return { refresh: load, update: load, destroy: function () { on = false; seq++; clearTimeout(timer); } };
return { refresh: load, update: load, destroy: function () { on = false; seq++; clearTimeout(timer); document.removeEventListener('keydown', slash); } };
}
// ------------------------------------------------------------ new ticket dialog
@@ -425,7 +455,7 @@
function detailView(host, id, idHost) {
var seq = 0, on = true, tk = null, busy = false;
var box = el('div', { class: 'inc-detail' });
host.appendChild(el('a', { class: 'inc-back', href: U.href('incidents') }, '← ' + t('inc.back')));
host.appendChild(el('nav', { class: 'inc-backnav', 'aria-label': t('inc.title') }, el('a', { class: 'inc-back', href: U.href('incidents') }, '← ' + t('inc.back'))));
host.appendChild(box);
var errBox = el('p', { class: 'inc-err', role: 'alert', hidden: true });
@@ -486,10 +516,19 @@
}
var q = el('div', { class: 'inc-quick', role: 'group', 'aria-label': t('inc.quick') },
quick(t('inc.quick.fp'), 'false_positive', 'fp'), quick(t('inc.quick.tp'), 'true_positive', 'tp'), quick(t('inc.quick.resolve'), 'resolved', 'ok'));
var meta = el('span', { class: 'inc-hint inc-metaline' }, t('inc.meta', { a: x.created_at ? U.fmt.ago(x.created_at) : '-', b: x.updated_at ? U.fmt.ago(x.updated_at) : '-', n: nf(x.count) }));
return el('header', { class: 'inc-head' },
el('div', { class: 'inc-h1' }, dot(x.severity), el('span', { class: 'inc-id mono' }, splitId(x).full), title, q),
el('div', { class: 'inc-h2' }, sevBadge(x.severity), statusBadge(x.status), x.suppress ? el('span', { class: 'chip' }, t('eg.suppressed.chip')) : null, tagChips(x.tags), meta));
var q2 = splitId(x), sev = sevOf(x.severity);
var facts = el('p', { class: 'inc-facts' });
function fact(k, v) { if (facts.firstChild) facts.appendChild(el('span', { class: 'inc-sep', 'aria-hidden': 'true' }, '·')); facts.appendChild(el('span', null, el('span', { class: 'inc-fk' }, k + ' '), v)); }
fact(t('inc.t.created'), when(x.created_at));
fact(t('inc.t.last'), when(x.last_seen || x.updated_at));
fact(t('inc.t.count'), el('strong', { class: 'num' }, nf(x.count || 1)));
if (x.assignee) fact(t('inc.f.assignee'), el('strong', null, String(x.assignee)));
return el('header', { class: 'inc-head inc-s-' + sev },
el('div', { class: 'inc-crumb mono' }, q2.host ? el('span', null, q2.host) : null, q2.host ? el('span', { class: 'inc-sep', 'aria-hidden': 'true' }, '/') : null, el('span', null, q2.num)),
el('div', { class: 'inc-h1' }, title, q),
el('div', { class: 'inc-h2' }, el('span', { class: 'inc-sev inc-sev-' + sev }, t('inc.sev.' + sev)), statusBadge(x.status),
x.suppress ? el('span', { class: 'badge inc-supb' }, t('eg.suppressed.chip')) : null, tagChips(x.tags, 'inc-tag')),
facts);
}
// ---- properties (each control saves by itself)
@@ -504,7 +543,9 @@
tg.value = (x.tags || []).join(', ');
var sup = el('input', { type: 'checkbox', id: 'inc-e-sup', role: 'switch', class: 'inc-switch', 'aria-describedby': 'inc-e-sup-h' });
sup.checked = !!x.suppress;
sup.disabled = SUPPRESSIBLE.indexOf(statusOf(x.status)) < 0;
var hi = ['critical', 'high'];
var supWhy = x.source !== 'egress' ? 'inc.sup.only.egress' : (hi.indexOf(sevOf(x.severity)) >= 0 || hi.indexOf(String(x.max_severity || '')) >= 0) ? 'inc.sup.only.low' : SUPPRESSIBLE.indexOf(statusOf(x.status)) < 0 ? 'inc.f.suppress.off' : '';
sup.disabled = !x.suppress && !!supWhy;
st.addEventListener('change', function () {
var d = { status: st.value };
if (x.suppress && SUPPRESSIBLE.indexOf(st.value) < 0) d.suppress = false;
@@ -517,15 +558,28 @@
me.addEventListener('click', function () { if (authorName() !== (x.assignee || '')) patch({ assignee: authorName() }); });
tg.addEventListener('change', function () { var l = parseTags(tg.value); if (!sameList(l, x.tags)) patch({ tags: l }); });
tg.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); tg.blur(); } });
sup.addEventListener('change', function () { patch({ suppress: sup.checked }); });
var supHint = el('span', { class: 'inc-hint', id: 'inc-e-sup-h', title: t('inc.f.suppress.help') }, t('inc.sup.hint'));
var days = el('select', { id: 'inc-e-days', 'aria-label': t('inc.sup.for') });
[7, 30, 90].forEach(function (d) { var o = el('option', { value: String(d) }, t('inc.sup.days', { n: d })); if (d === 30) o.selected = true; days.appendChild(o); });
sup.addEventListener('change', function () {
if (sup.checked) patch({ suppress: true, suppress_until: Math.floor(Date.now() / 1000) + Number(days.value) * 86400 });
else patch({ suppress: false });
});
var supState = x.suppress
? t('inc.sup.until', { date: x.suppress_until ? U.fmt.date(x.suppress_until) : '-', ago: x.suppressed_at ? U.fmt.ago(x.suppressed_at) : '-' })
: (supWhy ? t(supWhy) : t('inc.sup.what'));
var supHint = el('details', { class: 'inc-why' }, el('summary', null, t('inc.sup.more')), el('p', { class: 'inc-hint' }, t('inc.f.suppress.help')));
return el('section', { class: 'inc-card inc-props' }, el('h2', null, t('inc.props')),
row(t('inc.f.status'), st, 'inc-e-status'),
row(t('inc.f.severity'), sev, 'inc-e-sev'),
row(t('inc.f.assignee'), el('div', { class: 'inc-stack' }, asg, me), 'inc-e-asg'),
row(t('inc.f.tags'), el('div', { class: 'inc-stack' }, tg, el('span', { class: 'inc-hint', id: 'inc-e-tags-h' }, t('inc.f.tags.hint'))), 'inc-e-tags'),
row(t('inc.sup.short'), el('div', { class: 'inc-stack' }, sup, supHint), 'inc-e-sup'),
errBox);
errBox,
el('div', { class: 'inc-supbox' + (sup.disabled ? ' off' : '') + (x.suppress ? ' on' : '') },
el('div', { class: 'inc-sup-row' }, el('label', { for: 'inc-e-sup' }, t('inc.f.suppress')), sup),
el('p', { class: 'inc-hint', id: 'inc-e-sup-h' }, supState),
(!x.suppress && !sup.disabled) ? el('div', { class: 'inc-sup-row' }, el('label', { for: 'inc-e-days', class: 'inc-hint' }, t('inc.sup.for')), days) : null,
el('p', { class: 'inc-hint' }, t('inc.sup.reopen')),
supHint));
}
// ---- summary: conclusion + original detail
@@ -536,9 +590,10 @@
var has = !!(x.verdict || x.detail);
node.classList.toggle('empty', !has && !edit);
if (!has && !edit) {
var add = el('button', { type: 'button', class: 'btn sm' }, '+ ' + t('inc.concl.add'));
var add = el('button', { type: 'button', class: 'btn sm' }, t('inc.concl.add'));
add.addEventListener('click', function () { render(true); });
node.appendChild(add);
node.appendChild(el('div', { class: 'inc-card-h' }, el('h2', null, t('inc.summary')), add));
node.appendChild(el('p', { class: 'inc-hint' }, t('inc.summary.none')));
return;
}
var head = el('div', { class: 'inc-card-h' }, el('h2', null, t('inc.summary')));
@@ -558,8 +613,8 @@
node.appendChild(ta);
node.appendChild(el('div', { class: 'inc-btns' }, cn, sv));
setTimeout(function () { ta.focus(); }, 0);
} else if (x.verdict) node.appendChild(el('p', { class: 'inc-text' }, String(x.verdict)));
if (x.detail) node.appendChild(el('pre', { class: 'inc-pre', 'aria-label': t('inc.detail.label') }, String(x.detail)));
} else if (x.verdict) node.appendChild(el('div', { class: 'inc-verdict' }, el('h3', null, t('inc.f.verdict')), el('p', { class: 'inc-text' }, String(x.verdict))));
if (x.detail) node.appendChild(el('div', { class: 'inc-evid' }, el('h3', null, t('inc.evidence')), el('pre', { class: 'inc-pre' }, String(x.detail))));
}
render(false);
return node;
@@ -647,7 +702,8 @@
ul.appendChild(el('li', { class: 'inc-ev inc-grp' }, el('details', null,
el('summary', null, el('span', { class: 'inc-ev-dot', 'aria-hidden': 'true' }), t('inc.h.group', { who: String(e.h.author || '-'), n: grp.length }), ' ', el('span', { class: 'inc-ev-when' }, when(e.at))), inner)));
}
return el('section', { class: 'inc-card inc-activity' }, el('div', { class: 'inc-card-h' }, el('h2', null, t('inc.activity'))), composer(), evs.length ? ul : null);
return el('section', { class: 'inc-card inc-activity', 'aria-label': t('inc.activity') }, el('div', { class: 'inc-card-h' }, el('h2', null, t('inc.activity')), el('span', { class: 'inc-hint' }, t('inc.comments.n.' + ((x.comments || []).length === 1 ? 'one' : 'other'), { n: nf((x.comments || []).length) }))),
composer(), evs.length ? ul : el('p', { class: 'inc-hint' }, t('inc.comments.none')));
}
// ---- technical data
+8 -4
View File
@@ -35,14 +35,18 @@
</div>
</header>
<div class="slice" id="slice">
<div class="slice-sentinel" id="slice-sentinel" aria-hidden="true"></div>
<section class="slice" id="slice" data-i18n-aria="fb.label">
<div class="slice-ctl">
<div class="range-picker" id="range-picker"></div>
<select id="host" data-i18n-aria="host.label"></select>
<div class="host-picker" id="host-picker" hidden></div>
<select id="domain" hidden data-i18n-aria="traffic.domain"></select>
</div>
<p class="slice-txt" id="slice-text" aria-live="polite"></p>
</div>
<div class="slice-sum">
<p class="slice-txt" id="slice-text" aria-live="polite"></p>
<div class="slice-tools" id="slice-tools"></div>
</div>
</section>
<div class="err-banner" id="err" role="alert" hidden></div>
+94
View File
@@ -369,3 +369,97 @@ a.ipx-tag.lnk:hover { border-color: var(--accent); }
.ipx-cut.hi { background: var(--ink); }
.ipx-score-cuts { font-size: .75rem; }
.ipx-score-rule { font-size: .8125rem; color: var(--ink); padding: 4px 8px; border-radius: 6px; background: var(--danger-soft); border: 1px solid color-mix(in srgb, var(--danger) 40%, transparent); overflow-wrap: anywhere; }
/* ================================================================ v2 layout (2026-11): hero + top tabs */
.ipx > .ipx-grid { grid-template-columns: minmax(0, 1fr); }
@media (min-width: 1024px) {
.ipx > .ipx-grid { grid-template-columns: repeat(12, minmax(0, 1fr)); }
.ipx > .ipx-grid > * { grid-column: 1 / -1; }
}
.ipx-card[tabindex="-1"]:focus { outline: none; }
.ipx-card[tabindex="-1"]:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.ipx-card { scroll-margin-top: calc(var(--ipx-top) + 64px); }
/* tabs: one horizontal sticky bar at every width */
.ipx > .ipx-toc { position: sticky; top: var(--ipx-top); z-index: 6; margin: 0; padding: 0; background: var(--surface-base); border: 0; border-bottom: 1px solid var(--line); }
.ipx > .ipx-toc::before, .ipx > .ipx-toc::after { display: block; }
.ipx > .ipx-toc .ipx-toc-l { flex-direction: row; overflow-x: auto; gap: 2px; padding: 0; border: 0; }
.ipx > .ipx-toc .ipx-toc-a { width: auto; margin: 0; border: 0; border-bottom: 2px solid transparent; border-radius: 0; min-height: 44px; padding: 0 14px; background: none; }
.ipx > .ipx-toc .ipx-toc-a:hover { background: var(--surface-raised); }
.ipx > .ipx-toc .ipx-toc-a[aria-current="true"] { color: var(--ink); border-bottom-color: var(--accent); background: none; }
.ipx > .ipx-toc .ipx-toc-a:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
/* hero */
.ipx-hero { position: relative; display: flex; flex-direction: column; gap: var(--s-4); padding: var(--s-4); border: 1px solid var(--line); border-radius: var(--radius, 10px); background: var(--surface-raised); border-top: 4px solid var(--ink-faint); }
.ipx-hero.tone-danger { border-top-color: var(--danger); }
.ipx-hero.tone-warn { border-top-color: var(--warn); }
.ipx-hero.tone-info { border-top-color: var(--info, var(--accent)); }
.ipx-hero-top { display: flex; gap: var(--s-4); align-items: flex-start; justify-content: space-between; flex-wrap: wrap; }
.ipx-hero-main { flex: 1 1 22rem; display: flex; flex-direction: column; gap: var(--s-2); }
.ipx-hero-line { display: flex; align-items: center; gap: var(--s-2) var(--s-3); flex-wrap: wrap; }
.ipx-hero-ip { margin: 0; font-family: var(--font-mono); font-size: clamp(1.375rem, 4.6vw, 2rem); line-height: 1.15; font-weight: 700; letter-spacing: -.01em; white-space: nowrap; }
.ipx-hero-ip.ipv { font-size: clamp(1.375rem, 4.6vw, 2rem); }
.ipx-hero-lead { font-size: 1.0625rem; line-height: 1.45; font-weight: 600; color: var(--ink); }
.ipx-hero-id { display: flex; flex-wrap: wrap; gap: 4px var(--s-4); color: var(--ink-muted); font-size: .875rem; }
.ipx-hero-i { overflow-wrap: anywhere; }
.ipx-hero-rdns { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; }
.ipx-hero-score { flex: none; display: flex; align-items: baseline; gap: 6px; padding: var(--s-2) var(--s-3); border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); background: var(--surface-sunken); }
.ipx-hero-sv { font-size: 2rem; font-weight: 800; line-height: 1; }
.ipx-hero.tone-danger .ipx-hero-sv { color: var(--danger); }
.ipx-hero.tone-warn .ipx-hero-sv { color: var(--warn); }
.ipx-hero-so { color: var(--ink-faint); font-size: .8125rem; white-space: nowrap; }
.ipx-qs { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1px; background: var(--line); border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); overflow: hidden; }
@media (min-width: 560px) { .ipx-qs { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 1024px) { .ipx-qs { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
.ipx-q { background: var(--surface-base); padding: 10px 12px; display: flex; flex-direction: column; gap: 4px; }
.ipx-q-k { font: 600 .6875rem/1.3 var(--font-mono); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-faint); }
.ipx-q-v { margin: 0; display: flex; flex-direction: column; gap: 2px; font-weight: 600; overflow-wrap: break-word; }
.ipx-q-s { font-weight: 400; color: var(--ink-muted); font-size: .8125rem; }
.ipx-q.tone-ok .ipx-q-block { color: var(--ok); }
.ipx-q.tone-danger .ipx-q-block { color: var(--danger); }
.ipx-q-act { align-self: flex-start; margin-top: 6px; }
.ipx-hero > .ipx-banner { margin: 0; }
/* summary */
.ipx-conf { font-size: .8125rem; }
/* targets & techniques */
.ipx-attack { display: grid; gap: var(--s-5, 20px); grid-template-columns: minmax(0, 1fr); }
@media (min-width: 1024px) { .ipx-attack { grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); } }
.ipx-attack-t, .ipx-attack-m, .ipx-idcl { display: flex; flex-direction: column; gap: var(--s-4); }
.ipx-idcl { margin-top: var(--s-4); }
@media (min-width: 1024px) { .ipx-idcl { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; } }
/* defense */
.ipx-defgrid { display: grid; gap: var(--s-4); grid-template-columns: minmax(0, 1fr); }
@media (min-width: 1024px) { .ipx-defgrid { grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); } }
.ipx-hostst { display: flex; flex-direction: column; gap: 6px; margin-top: var(--s-2); }
.ipx-hst { display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); }
.ipx-hst.on { border-color: color-mix(in srgb, var(--ok) 45%, var(--line)); }
.ipx-hst-h { font-weight: 700; }
.ipx-hst-s { color: var(--ink-muted); font-size: .875rem; overflow-wrap: anywhere; }
.ipx-unban { margin-top: var(--s-3); }
.ipx-hist > summary { cursor: pointer; list-style: revert; padding: 4px 0; min-height: 32px; }
.ipx-hist > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.ipx-hist .ipx-tbl-w { margin-top: var(--s-2); }
/* events */
.ipx-evbar { display: flex; align-items: center; gap: var(--s-2); flex-wrap: wrap; margin-bottom: var(--s-3); }
.ipx-evl { font-weight: 600; color: var(--ink-muted); font-size: .875rem; }
.ipx-sel { min-height: 36px; max-width: 100%; padding: 0 10px; border: 1px solid var(--line-strong); border-radius: var(--radius-sm, 7px); background: var(--surface-base); color: var(--ink); font: inherit; }
.ipx-evt td.ipx-td-req { width: 45%; }
@media (max-width: 767px) {
.ipx-evt tr { display: grid !important; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 8px; padding: 8px 10px !important; }
.ipx-evt td, .ipx-evt td.ipx-td-req { display: block !important; padding: 0 !important; width: auto !important; }
.ipx-evt td::before { display: none; }
.ipx-evt td:nth-child(1) { grid-column: 1; color: var(--ink-muted); font-size: .8125rem; }
.ipx-evt td:nth-child(2) { grid-column: 2; grid-row: 1; justify-self: end; }
.ipx-evt td:nth-child(3) { grid-column: 1 / -1; font-size: .8125rem; color: var(--ink-muted); }
.ipx-evt td:nth-child(4) { grid-column: 1 / -1; }
.ipx-evt td:nth-child(5), .ipx-evt td:nth-child(6) { display: inline-block !important; font-size: .8125rem; color: var(--ink-muted); }
.ipx-evt td:nth-child(5)::before, .ipx-evt td:nth-child(6)::before { display: inline; content: attr(data-label) " "; font: 600 .625rem/1 var(--font-mono); text-transform: uppercase; color: var(--ink-faint); }
.ipx-evt td:nth-child(6) { justify-self: end; }
.ipx-hero { padding: var(--s-3); }
.ipx-hero-score { padding: 6px 10px; }
.ipx-hero-sv { font-size: 1.5rem; }
}
+315 -35
View File
@@ -29,8 +29,21 @@
'ip.loading': 'Loading the analysis.',
'ip.invalid': 'This is not a valid IP address.',
'ip.error': 'Could not load this IP.',
'ip.notfound': 'No activity from this IP in the selected period.',
'ip.notfound.hint': 'Pick a longer period above, or the IP was never seen.',
'ip.never': 'This IP was never seen by Urutau (neither as a source nor as an egress destination).',
'ip.dst.title': 'Egress destination',
'ip.dst.lead': 'Our workloads connected to this address; it never attacked us.',
'ip.dst.hint': 'Outbound connections from this installation to the IP, not inbound attacks.',
'ip.dst.host': 'Host',
'ip.dst.workloads': 'Workloads',
'ip.dst.ports': 'Ports',
'ip.dst.conns': 'Connections',
'ip.dst.net': 'Network',
'ip.dst.findings': 'Findings',
'ip.dst.incidents': 'Linked incidents',
'ip.dst.nofind': 'No finding in this period.',
'ip.dst.last': 'Last: {when}',
'ip.dst.inb.after': 'Last seen as an attacker (inbound) on {when}, outside the selected period.',
'ip.dst.inb.btn': 'Show the last 30 days',
'ip.retry': 'Try again',
'ip.lead.hostile': 'Hostile: {events} {range}',
'ip.lead.suspicious': 'Suspicious: {events} {range}',
@@ -310,7 +323,32 @@
'ip.rel.campaigns.empty': 'Not part of a detected campaign.',
'ip.rel.campaign.ips.one': '{n} IP',
'ip.rel.campaign.ips.other': '{n} IPs',
'ip.rel.open': 'Open analysis of {ip}'
'ip.rel.open': 'Open analysis of {ip}',
'ip.sec.summary': 'Summary',
'ip.sec.attack': 'Targets & techniques',
'ip.sec.identity': 'Identity',
'ip.sec.events': 'Events',
'ip.q.what': 'What it did',
'ip.q.when': 'When',
'ip.q.against': 'Against',
'ip.q.blocked': 'Blocked?',
'ip.q.blocked.yes': 'Yes, on {hosts}',
'ip.q.blocked.no': 'No active ban',
'ip.q.blocked.list': 'on the exported blocklist',
'ip.q.last': 'last seen {ago}',
'ip.q.more': '+{n} more',
'ip.q.nothing': 'Nothing recorded in this period',
'ip.score.over': 'Raw score {n}; the scale is capped at 1000.',
'ip.def.hosts': 'Status per host',
'ip.def.host.on': 'banned by {jails}',
'ip.def.host.off': 'no active ban',
'ip.def.history': 'Ban history ({n})',
'ip.id.title': 'Identity and clients',
'ip.id.hint': 'Where it comes from and what it claims to be. Location is approximate; user agents are easy to forge.',
'ip.ev.filter': 'Show',
'ip.ev.filter.all': 'All categories',
'ip.ev.filter.none': 'No event of this category on this page.',
'ip.attack.hint': 'What it asked for, against which sites, and the MITRE ATT&CK techniques that implies.'
},
'pt-BR': {
'ip.title': 'Análise de IP',
@@ -329,8 +367,21 @@
'ip.loading': 'Carregando a análise.',
'ip.invalid': 'Este não é um endereço IP válido.',
'ip.error': 'Não foi possível carregar este IP.',
'ip.notfound': 'Nenhuma atividade deste IP no período selecionado.',
'ip.notfound.hint': 'Escolha um período maior acima, ou o IP nunca foi visto.',
'ip.never': 'Este IP nunca foi visto pelo Urutau (nem como origem nem como destino de saída).',
'ip.dst.title': 'Destino de saída',
'ip.dst.lead': 'Nossas cargas de trabalho conectaram a este endereço; ele nunca nos atacou.',
'ip.dst.hint': 'Conexões de saída desta instalação para o IP, não ataques de entrada.',
'ip.dst.host': 'Host',
'ip.dst.workloads': 'Cargas de trabalho',
'ip.dst.ports': 'Portas',
'ip.dst.conns': 'Conexões',
'ip.dst.net': 'Rede',
'ip.dst.findings': 'Achados',
'ip.dst.incidents': 'Incidentes ligados',
'ip.dst.nofind': 'Nenhum achado neste período.',
'ip.dst.last': 'Último: {when}',
'ip.dst.inb.after': 'Visto pela última vez como atacante (entrada) em {when}, fora do período selecionado.',
'ip.dst.inb.btn': 'Mostrar os últimos 30 dias',
'ip.retry': 'Tentar de novo',
'ip.lead.hostile': 'Hostil: {events} {range}',
'ip.lead.suspicious': 'Suspeito: {events} {range}',
@@ -610,7 +661,32 @@
'ip.rel.campaigns.empty': 'Não faz parte de uma campanha detectada.',
'ip.rel.campaign.ips.one': '{n} IP',
'ip.rel.campaign.ips.other': '{n} IPs',
'ip.rel.open': 'Abrir a análise de {ip}'
'ip.rel.open': 'Abrir a análise de {ip}',
'ip.sec.summary': 'Resumo',
'ip.sec.attack': 'Alvos e técnicas',
'ip.sec.identity': 'Identidade',
'ip.sec.events': 'Eventos',
'ip.q.what': 'O que fez',
'ip.q.when': 'Quando',
'ip.q.against': 'Contra o quê',
'ip.q.blocked': 'Está bloqueado?',
'ip.q.blocked.yes': 'Sim, em {hosts}',
'ip.q.blocked.no': 'Sem ban ativo',
'ip.q.blocked.list': 'na lista de bloqueio exportada',
'ip.q.last': 'última vez {ago}',
'ip.q.more': '+{n}',
'ip.q.nothing': 'Nada registrado neste período',
'ip.score.over': 'Pontuação bruta {n}; a escala vai até 1000.',
'ip.def.hosts': 'Situação por host',
'ip.def.host.on': 'banido por {jails}',
'ip.def.host.off': 'sem ban ativo',
'ip.def.history': 'Histórico de bans ({n})',
'ip.id.title': 'Identidade e clientes',
'ip.id.hint': 'De onde vem e o que diz ser. A localização é aproximada; user agents são fáceis de falsificar.',
'ip.ev.filter': 'Mostrar',
'ip.ev.filter.all': 'Todas as categorias',
'ip.ev.filter.none': 'Nenhum evento desta categoria nesta página.',
'ip.attack.hint': 'O que pediu, contra quais sites, e as técnicas MITRE ATT&CK que isso indica.'
}
});
@@ -828,6 +904,7 @@
return {
level: levelOf(has(v.level) ? v.level : d.level),
score: score1000(has(v.score) ? v.score : d.score),
raw: num(has(v.score) ? v.score : d.score),
strong: !!v.strong,
admin: !!v.admin,
reasons: arr(v.reasons).filter(isObj)
@@ -852,7 +929,7 @@
// one coherent view of the bans: the history plus any ban that is active now
function banList(d) {
var raw = arr(has(d.bans) ? d.bans : d.ban_history).filter(isObj);
var list = raw.map(function (x) { return { jail: x.jail, t: ts(x.t), unban: ts(x.unban), active: x.active === true || (x.active === undefined && !ts(x.unban)) }; });
var list = raw.map(function (x) { return { jail: x.jail, host: str(x.host), t: ts(x.t), unban: ts(x.unban), active: x.active === true || (x.active === undefined && !ts(x.unban)) }; });
var anyActive = list.some(function (x) { return x.active; });
if (d.banned && !anyActive) {
var js = arr(d.jails).filter(function (j) { return typeof j === 'string'; });
@@ -1102,6 +1179,106 @@
return node;
}
// ---------------------------------------------------------------- hero: the 5-second answer
function moved(card) { var b = card && card.querySelector('.ipx-cb'); return b ? Array.prototype.slice.call(b.childNodes) : []; }
function hostBans(d) {
var by = {}, order = [];
banList(d).forEach(function (b) {
var k = b.host || '';
if (!by[k]) { by[k] = { host: k, jails: [], active: false, last: 0 }; order.push(k); }
var g = by[k];
if (b.active) { g.active = true; if (b.jail && g.jails.indexOf(b.jail) < 0) g.jails.push(b.jail); }
if (b.t > g.last) g.last = b.t;
});
arr(d.hosts).forEach(function (x) { var k = keyOf(x); if (k && !by[k]) { by[k] = { host: k, jails: [], active: false, last: 0 }; order.push(k); } });
return order.map(function (k) { return by[k]; });
}
function moreList(list, n) {
var out = list.slice(0, n).join(', ');
return list.length > n ? out + ' ' + t('ip.q.more', { n: N(list.length - n) }) : out;
}
function qCell(key, main, sub, tone) {
return h('div', 'ipx-q' + (tone ? ' tone-' + tone : ''), h('dt', 'ipx-q-k', t(key)), h('dd', 'ipx-q-v', main, sub ? h('span', 'ipx-q-s', sub) : null));
}
function heroCard(d, ip, ctx) {
var v = normalizeVerdict(d), tone = v.admin ? 'info' : LEVEL_TONE[v.level];
var node = h('header', 'ipx-hero tone-' + tone);
var id = isObj(d.identity) ? d.identity : {}, geo = isObj(d.geo) ? d.geo : {};
var cc = str(geo.cc || d.cc).toUpperCase(), asn = has(id.asn) ? id.asn : d.asn, org = str(id.as_org || d.as_org), rdns = str(has(id.rdns) ? id.rdns : d.rdns);
var place = [str(geo.city || d.city), str(geo.country || d.country) || (fmt.country && cc ? fmt.country(cc) : cc)].filter(Boolean).join(', ');
var idl = h('p', 'ipx-hero-id');
if (place) idl.appendChild(h('span', 'ipx-hero-i', cc && fmt.flag ? fmt.flag(cc) + ' ' : '', place));
if (asn || org) idl.appendChild(h('span', 'ipx-hero-i', h('span', 'ipx-mono', asn ? 'AS' + num(asn) : ''), org ? ' ' + clip(org, 60) : ''));
if (rdns) {
var rd = h('span', 'ipx-hero-i ipx-hero-rdns', untrusted(clip(rdns, 120)));
if (has(id.fcrdns_ok)) rd.appendChild(h('span', 'ipx-seal ' + (id.fcrdns_ok ? 'ok' : 'bad'), { title: t('ip.id.fcrdns.hint') }, (id.fcrdns_ok ? '✓ ' : '⚠ ') + t(id.fcrdns_ok ? 'ip.id.fcrdns.ok' : 'ip.id.fcrdns.bad')));
idl.appendChild(rd);
}
var over = v.raw > 1000;
var score = h('div', 'ipx-hero-score', { role: 'img', 'aria-label': t('ip.score.label', { n: v.score }) + (over ? '. ' + t('ip.score.over', { n: N(Math.round(v.raw)) }) : ''), title: over ? t('ip.score.over', { n: N(Math.round(v.raw)) }) : '' },
h('span', 'ipx-num ipx-hero-sv', N(v.score) + (over ? '+' : '')), h('span', 'ipx-hero-so', t('ip.score.of')));
node.appendChild(h('div', 'ipx-hero-top',
h('div', 'ipx-hero-main',
h('div', 'ipx-hero-line', h('h1', 'ipx-hero-ip ipv', ip), badge(v.admin ? t('ip.admin') : t('ip.level.' + v.level), tone, 'ipx-hero-lv')),
h('p', 'ipx-hero-lead', leadText(d, v, ctx)),
idl.firstChild ? idl : null),
score));
// the four questions
var q = h('dl', 'ipx-qs');
var cats = entries(d.counts).filter(function (e) { return e[0] !== 'ban' && e[1] > 0; });
var fams = arr(d.families).filter(isObj).sort(function (a, b) { return num(b.n) - num(a.n); });
q.appendChild(cats.length
? qCell('ip.q.what', cats.slice(0, 2).map(function (e) { return catLabel(e[0]) + ' (' + N(e[1]) + ')'; }).join(', '), fams.length ? moreList(fams.map(function (f) { return famLabel(f.fam); }), 2) : '')
: qCell('ip.q.what', h('span', 'ipx-faint', t('ip.q.nothing'))));
var tm = isObj(d.time) ? d.time : {}, first = ts(has(tm.first) ? tm.first : d.first), last = ts(has(tm.last) ? tm.last : d.last);
q.appendChild(qCell('ip.q.when', first ? dShort(first) + (last && last !== first ? ' → ' + dShort(last) : '') : '-', last ? t('ip.q.last', { ago: ago(last) }) : ''));
var doms = [];
arr(d.targets).forEach(function (x) { if (isObj(x) && x.domain && doms.indexOf(x.domain) < 0) doms.push(str(x.domain)); });
if (!doms.length) arr(d.domains).forEach(function (x) { var k = keyOf(x); if (k) doms.push(k); });
var hostsL = arr(d.hosts).map(keyOf).filter(Boolean);
q.appendChild(qCell('ip.q.against', doms.length ? h('span', 'ipx-q-wrap', moreList(doms.map(function (x) { return clip(x, 60).replace(/\./g, '.\u200b'); }), 2)) : hostsL.length ? moreList(hostsL, 3) : '-', doms.length && hostsL.length ? 'host: ' + moreList(hostsL, 3) : ''));
var hb = hostBans(d).filter(function (g) { return g.active; }), bl = isObj(d.blocklist) ? !!d.blocklist.listed : !!d.blocklisted;
var bv = h('span', 'ipx-q-block', hb.length ? t('ip.q.blocked.yes', { hosts: hb.map(function (g) { return g.host || '?'; }).join(', ') }) : isBanned(d) ? t('ip.def.active') : t('ip.q.blocked.no'));
var bcell = qCell('ip.q.blocked', bv, bl ? t('ip.q.blocked.list') : '', hb.length || isBanned(d) ? 'ok' : (v.level === 'hostile' ? 'danger' : ''));
if (isBanned(d) && U.unbanDialog) bcell.lastChild.appendChild(h('button', 'ipx-btn sm ipx-q-act', { type: 'button', onclick: function () { U.unbanDialog(d.ip || ip, function () { if (S) load(S); }); } }, t('unban.btn')));
q.appendChild(bcell);
node.appendChild(q);
var b1 = exposureBanner(d), b2 = incidentBanner(d);
if (b1) node.appendChild(b1);
if (b2) node.appendChild(b2);
return node;
}
function summaryCard(d, ip, ctx) {
var v = normalizeVerdict(d);
var c = card('ip.sec.summary', null, 12, 'ipx-summary');
var two = h('div', 'ipx-vtwo');
two.appendChild(reasonsBlock(v));
two.appendChild(actionsBlock(d));
var conf = h('p', 'ipx-faint ipx-conf', t('ip.score.cuts', { a: 10, b: 50 }) + ' ' + t('ip.confidence') + ': ' + (v.admin ? t('ip.confidence.admin') : v.strong ? t('ip.confidence.high') : t('ip.confidence.medium')) + '.');
c.body.appendChild(two);
c.body.appendChild(conf);
c.body.appendChild(toolbar(d, v, ip, ctx));
return c.node;
}
function attackCard(d) {
var tg = safe(function () { return targetsCard(d); }), te = safe(function () { return techniquesCard(d); });
if (!tg && !te) return null;
var c = card('ip.sec.attack', 'ip.attack.hint', 12);
var g = h('div', 'ipx-attack');
if (tg) g.appendChild(h('div', 'ipx-attack-t', moved(tg)));
if (te) g.appendChild(h('div', 'ipx-attack-m', moved(te)));
c.body.appendChild(g);
return c.node;
}
function identityCard(d) {
var c = card('ip.id.title', 'ip.id.hint', 12);
c.body.appendChild(identityChips(d));
var cl = safe(function () { return clientsCard(d); });
if (cl) c.body.appendChild(h('div', 'ipx-idcl', moved(cl)));
return c.node;
}
// ---------------------------------------------------------------- B: activity
function weekdayName(i) {
try { return new Date(Date.UTC(2024, 0, 1 + i)).toLocaleDateString(lang(), { weekday: 'short', timeZone: 'UTC' }); } catch (e) { return String(i + 1); }
@@ -1273,24 +1450,43 @@
if (f0 && bt >= f0) ttb = bt - f0;
}
if (!list.length && !has(ttb) && !bl && !banned) return null;
var c = card('ip.def.title', null, 4);
var b = h('div', 'ipx-block');
b.appendChild(h('h3', 'ipx-h3', t('ip.def.bans')));
if (!list.length) b.appendChild(h('p', 'ipx-muted', t('ip.def.bans.empty')));
var c = card('ip.def.title', null, 12);
var b = h('div', 'ipx-defgrid');
var hs = h('div', 'ipx-block');
hs.appendChild(h('h3', 'ipx-h3', t('ip.def.hosts')));
var groups = hostBans(d);
if (!groups.length) hs.appendChild(h('p', 'ipx-muted', banned ? t('ip.def.active') : t('ip.def.bans.empty')));
else {
var ol = h('ol', 'ipx-bans');
list.sort(function (x, y) { return (y.active ? 1 : 0) - (x.active ? 1 : 0) || y.t - x.t; }).forEach(function (x) {
ol.appendChild(h('li', 'ipx-ban',
h('span', 'ipx-jail ipx-mono', clip(x.jail, 40) || '-'),
x.active ? badge(t('ip.def.active'), 'warn') : null,
x.t ? h('span', 'ipx-ban-t ipx-num', t('ip.def.banAt', { when: dt(x.t) })) : (x.synthetic ? h('span', 'ipx-ban-t ipx-faint', t('ip.def.noinfo')) : null),
x.unban && !x.active ? h('span', 'ipx-ban-u ipx-num ipx-faint', t('ip.def.lifted', { when: dt(x.unban) })) : null));
var ul = h('ul', 'ipx-hostst');
groups.forEach(function (g) {
ul.appendChild(h('li', 'ipx-hst' + (g.active ? ' on' : ''),
h('span', 'ipx-dot tone-' + (g.active ? 'ok' : 'neutral'), { 'aria-hidden': 'true' }),
h('span', 'ipx-hst-h ipx-mono', clip(g.host, 40) || '-'),
h('span', 'ipx-hst-s', g.active ? t('ip.def.host.on', { jails: g.jails.join(', ') || '-' }) : t('ip.def.host.off'))));
});
b.appendChild(ol);
hs.appendChild(ul);
}
if (banned && window.Urutau && Urutau.unbanDialog) {
b.appendChild(Urutau.el('button', { type: 'button', class: 'btn btn-sm ipx-unban', onclick: function () { Urutau.unbanDialog(d.ip, function () { location.reload(); }); } }, t('unban.btn')));
if (banned && U.unbanDialog) hs.appendChild(h('button', 'ipx-btn ipx-unban', { type: 'button', onclick: function () { U.unbanDialog(d.ip, function () { if (S) load(S); }); } }, t('unban.btn')));
b.appendChild(hs);
var hist = list.filter(function (x) { return !x.synthetic; }).sort(function (x, y) { return y.t - x.t; });
var hb = h('div', 'ipx-block');
if (!hist.length) { hb.appendChild(h('h3', 'ipx-h3', t('ip.def.bans'))); hb.appendChild(h('p', 'ipx-muted', t('ip.def.bans.empty'))); }
else {
var det = h('details', 'ipx-hist');
if (hist.length <= 4) det.setAttribute('open', '');
det.appendChild(h('summary', 'ipx-h3 ipx-sum', t('ip.def.history', { n: N(hist.length) })));
var tb = h('tbody');
hist.forEach(function (x) {
tb.appendChild(h('tr', null,
h('td', 'nw', { 'data-label': t('ip.ev.time') }, h('time', 'ipx-num', x.t ? dt(x.t) : '-')),
h('td', null, { 'data-label': 'host' }, h('span', 'ipx-mono', clip(x.host, 40) || '-')),
h('td', null, { 'data-label': 'jail' }, h('span', 'ipx-mono', clip(x.jail, 40) || '-')),
h('td', null, { 'data-label': '' }, x.active ? badge(t('ip.def.active'), 'warn') : x.unban ? h('span', 'ipx-faint', t('ip.def.lifted', { when: dt(x.unban) })) : h('span', 'ipx-faint', '-'))));
});
det.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', h('thead', null, h('tr', null, h('th', null, t('ip.ev.time')), h('th', null, 'host'), h('th', null, 'jail'), h('th', null, h('span', 'sr-only', t('ip.def.title'))))), tb)));
hb.appendChild(det);
}
b.appendChild(hb);
c.body.appendChild(b);
var f = h('dl', 'ipx-facts');
if (has(ttb) || list.length) {
@@ -1449,7 +1645,6 @@
}
function eventsBlock(s) {
var box = h('div', 'ipx-block ipx-evs');
box.appendChild(sub('ip.ev.title', 'ip.ev.hint'));
var body = h('div', 'ipx-ev-b');
box.appendChild(body);
s.evBox = body;
@@ -1464,9 +1659,21 @@
if (ev.disabled) { box.appendChild(emptyState(t('ip.ev.disabled'))); return; }
if (ev.failed && !ev.rows.length) { box.appendChild(emptyState(s.data && totalEvents(s.data) ? nologText(s.data) : t('ip.ev.unavailable'))); return; }
if (!ev.rows.length) { box.appendChild(emptyState(s.data && totalEvents(s.data) ? nologText(s.data) : t('ip.ev.empty'))); return; }
var present = [];
ev.rows.forEach(function (e) { if (e.cat && present.indexOf(e.cat) < 0 && KNOWN_CATS.indexOf(e.cat) >= 0) present.push(e.cat); });
if (ev.filter && present.indexOf(ev.filter) < 0) ev.filter = '';
if (present.length > 1) {
var sel = h('select', 'ipx-sel', { id: 'ipx-evf' });
sel.appendChild(h('option', null, { value: '' }, t('ip.ev.filter.all')));
present.forEach(function (c) { var o = h('option', null, { value: c }, catLabel(c)); if (c === ev.filter) o.selected = true; sel.appendChild(o); });
sel.addEventListener('change', function () { ev.filter = sel.value; paintEvents(s); var n = document.getElementById('ipx-evf'); if (n) n.focus(); });
box.appendChild(h('div', 'ipx-evbar', h('label', 'ipx-evl', { for: 'ipx-evf' }, t('ip.ev.filter')), sel));
}
var rows = ev.rows.filter(function (e) { return !ev.filter || e.cat === ev.filter; });
if (!rows.length) { box.appendChild(emptyState(t('ip.ev.filter.none'))); return; }
var tb = h('tbody');
ev.rows.forEach(function (e) { tb.appendChild(eventRow(e)); });
var table = h('table', 'ipx-tbl tbl-cards', h('thead', null, h('tr', null,
rows.forEach(function (e) { tb.appendChild(eventRow(e)); });
var table = h('table', 'ipx-tbl ipx-ctbl ipx-evt', h('thead', null, h('tr', null,
h('th', null, t('ip.ev.time')), h('th', null, t('ip.ev.cat')), h('th', null, t('ip.ev.target')), h('th', null, t('ip.ev.request')),
h('th', null, t('ip.ev.status')), h('th', null, t('ip.ev.bytes')))), tb);
box.appendChild(h('div', 'ipx-tbl-w', table));
@@ -1521,6 +1728,10 @@
}
c.body.appendChild(b);
}
return c.node;
}
function eventsCard(s) {
var c = card('ip.ev.title', 'ip.ev.hint', 12);
c.body.appendChild(eventsBlock(s));
return c.node;
}
@@ -1741,6 +1952,7 @@
if (!node) return;
var smooth = !(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
node.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto', block: 'start' });
try { node.focus({ preventScroll: true }); } catch (x) { /* old browser */ }
});
return b;
}
@@ -1802,7 +2014,7 @@
h('div', 'ipx-skel-b'), h('div', 'ipx-skel-b short'), h('div', 'ipx-skel-b'));
}
function errorNode(s, key, withRetry) {
var box = h('div', 'ipx-card state-error ipx-state', h('p', 'ipx-empty-t', t(key)), key === 'ip.notfound' ? h('p', 'ipx-empty-h', t('ip.notfound.hint')) : null);
var box = h('div', 'ipx-card state-error ipx-state', h('p', 'ipx-empty-t', t(key)));
if (withRetry) {
var b = h('button', 'ipx-btn', { type: 'button' }, t('ip.retry'));
b.addEventListener('click', function () { load(s); });
@@ -1815,7 +2027,8 @@
var d = s.data, ip = s.ip;
var wrap = shell(s);
wrap.appendChild(headBar(s));
var layout = h('div', 'ipx-layout');
var hero = safe(function () { return heroCard(d, ip, s.ctx); });
if (hero) wrap.appendChild(hero);
var tocScroll = h('ul', 'ipx-toc-l');
var toc = h('nav', 'ip-toc ipx-toc', { 'aria-label': t('ip.toc') }, tocScroll);
var grid = h('div', 'ipx-grid');
@@ -1823,25 +2036,91 @@
function add(id, key, node) {
if (!node) return;
node.id = 'ipx-' + id;
node.setAttribute('tabindex', '-1');
grid.appendChild(node);
items.push(id);
tocScroll.appendChild(h('li', null, tocItem(s, id, key)));
}
add('verdict', 'ip.sec.verdict', safe(function () { return verdictCard(d, ip, s.ctx); }));
add('summary', 'ip.sec.summary', safe(function () { return summaryCard(d, ip, s.ctx); }));
add('activity', 'ip.sec.activity', safe(function () { return activityCard(d); }));
add('defense', 'ip.sec.defense', safe(function () { return defenseCard(d); }));
add('techniques', 'ip.sec.techniques', safe(function () { return techniquesCard(d); }));
add('attack', 'ip.sec.attack', safe(function () { return attackCard(d); }));
add('sessions', 'ip.sec.sessions', safe(function () { return sessionsCard(d, s, ip); }));
add('targets', 'ip.sec.targets', safe(function () { return targetsCard(d); }));
add('clients', 'ip.sec.clients', safe(function () { return clientsCard(d); }));
add('defense', 'ip.sec.defense', safe(function () { return defenseCard(d); }));
add('identity', 'ip.sec.identity', safe(function () { return identityCard(d); }));
add('related', 'ip.sec.related', safe(function () { return relatedCard(d); }));
layout.appendChild(toc);
layout.appendChild(grid);
wrap.appendChild(layout);
add('events', 'ip.sec.events', safe(function () { return eventsCard(s); }));
wrap.appendChild(toc);
wrap.appendChild(grid);
watchToc(s, toc, items);
watchScrollFade(s, toc);
}
// ---------------------------------------------------------------- egress destination (no inbound data)
function dstBadge(sev) { return h('span', 'ipx-chip', str(sev)); }
function egressNode(s, d) {
var eg = arr(d.egress).filter(isObj), fs = arr(d.findings).filter(isObj), ics = arr(d.incidents).filter(isObj);
var c = card('ip.dst.title', 'ip.dst.hint', 12);
c.body.appendChild(h('p', 'ipx-lead', t('ip.dst.lead')));
if (eg.length) {
var tb = h('tbody');
eg.forEach(function (x) {
var cc = str(x.cc).toUpperCase(), net = [x.asn ? str(x.asn) : '', clip(x.org, 60)].filter(Boolean).join(' ');
tb.appendChild(h('tr', null,
h('td', null, str(x.host)),
h('td', null, arr(x.workloads).join(', ') || '-'),
h('td', 'ipx-mono', arr(x.ports).join(', ') || '-'),
h('td', 'ipx-num', N(num(x.conns))),
h('td', null, (cc && fmt.flag ? fmt.flag(cc) + ' ' : '') + (cc && fmt.country ? fmt.country(cc) : cc) + (net ? ' · ' + net : ''))));
});
c.body.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', h('thead', null, h('tr', null,
h('th', null, t('ip.dst.host')), h('th', null, t('ip.dst.workloads')), h('th', null, t('ip.dst.ports')), h('th', null, t('ip.dst.conns')), h('th', null, t('ip.dst.net')))), tb)));
}
c.body.appendChild(sub('ip.dst.findings'));
if (!fs.length) c.body.appendChild(h('p', 'ipx-muted', t('ip.dst.nofind')));
else {
var fb = h('tbody');
fs.forEach(function (f) {
fb.appendChild(h('tr', null, h('td', null, str(f.host)), h('td', null, str(f.kind)), h('td', null, dstBadge(f.severity)), h('td', null, str(f.workload)),
h('td', 'ipx-mono', (str(f.proto) + '/' + num(f.dport))), h('td', null, clip(f.detail, 120)), h('td', null, dt(num(f.last)))));
});
c.body.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', fb)));
}
if (ics.length) {
c.body.appendChild(sub('ip.dst.incidents'));
var ul = h('ul', 'ipx-list');
ics.forEach(function (i) {
var id = str(i.id), parts = id.split('/');
var href = '#/incidents/' + encodeURIComponent(parts[0]) + '/' + encodeURIComponent(parts.slice(1).join('/'));
ul.appendChild(h('li', null, h('a', null, { href: href }, id), ' ', dstBadge(i.severity), ' ', h('span', 'ipx-muted', str(i.status) + ' · ' + clip(i.title, 100))));
});
c.body.appendChild(ul);
}
return c.node;
}
function loadEgress(s, my) {
var p = Object.assign({}, rParams(s.ctx));
if (s.ctx && s.ctx.host && s.ctx.host !== 'all') p.host = s.ctx.host;
U.api('/api/v1/ip/' + encodeURIComponent(s.ip) + '/egress', p).then(function (d) {
if (!s.alive || my !== s.seq) return;
if (!isObj(d)) throw new Error('bad payload');
var has1 = arr(d.egress).length || arr(d.findings).length || arr(d.incidents).length, last = num(d.last_seen_inbound);
if (has1) { showState(s, egressNode(s, d)); return; }
if (last) {
var box = h('div', 'ipx-card ipx-state', h('p', 'ipx-empty-t', t('ip.dst.inb.after', { when: dt(last) })));
var b = h('button', 'ipx-btn', { type: 'button' }, t('ip.dst.inb.btn'));
b.addEventListener('click', function () { location.hash = '#/ip/' + encodeURIComponent(s.ip) + '?r=30d'; });
box.appendChild(b);
showState(s, box);
return;
}
showState(s, errorNode(s, 'ip.never', false));
}).catch(function (e) {
if (!s.alive || my !== s.seq) return;
if (e && e.message === 'unauthorized') return;
showState(s, errorNode(s, 'ip.error', true));
});
}
function load(s) {
var my = ++s.seq;
s.ip = ipFromCtx(s.ctx);
@@ -1861,7 +2140,8 @@
if (!s.alive || my !== s.seq) return;
if (e && e.message === 'unauthorized') return;
s.data = null;
showState(s, errorNode(s, e && e.status === 404 ? 'ip.notfound' : 'ip.error', !(e && e.status === 404)));
if (e && e.status === 404) { loadEgress(s, my); return; }
showState(s, errorNode(s, e && e.status === 404 ? 'ip.never' : 'ip.error', !(e && e.status === 404)));
});
}
+4 -4
View File
@@ -1317,7 +1317,7 @@
this.listDirty = true;
if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return;
var h = this.ctx && this.ctx.host;
if (h && h !== 'all' && h !== r.host) return;
if (h && h !== 'all' && (',' + h + ',').indexOf(',' + r.host + ',') < 0) return;
this.map.spawn(e, { visit: true });
};
P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); };
@@ -1500,21 +1500,21 @@
P.draw = function (r) {
if (this.offCats[r.cat] || this.offHosts[r.host]) return;
var h = this.ctx && this.ctx.host;
if (h && h !== 'all' && h !== r.host) return;
if (h && h !== 'all' && (',' + h + ',').indexOf(',' + r.host + ',') < 0) return;
this.map.spawn(r.ev);
};
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;
return !h || h === 'all' || (',' + h + ',').indexOf(',' + r.host + ',') >= 0;
};
// ------------------------------------------------------------------ panels and metrics
P.hostOk = function (h) {
if (this.offHosts[h]) return false;
var c = this.ctx && this.ctx.host;
return !c || c === 'all' || c === h;
return !c || c === 'all' || (',' + c + ',').indexOf(',' + h + ',') >= 0;
};
// sums the minute buckets from..to (inclusive) over the visible hosts (or all of them)
+1 -1
View File
@@ -865,7 +865,7 @@
ui.compB = toggle(t('rp.compress'), function () { compress = !compress; syncToggles(); writeHash(true); });
ui.onlyB = toggle(t('rp.only'), function () { only = !only; syncToggles(); refilter(); });
ui.selB = toggle(t('rp.select'), function () { selecting = !selecting; if (!selecting && loop) { loop = null; tlDirty = true; } syncToggles(); kick(); });
ui.repB = btn('rp-rep rp-tog', 'repeat', t('rp.repeat'), function () {
ui.repB = toggle(t('rp.repeat'), function () {
repeat = !repeat; syncToggles();
try { localStorage.setItem('urutau.replay.repeat', repeat ? '1' : '0'); } catch (x) { /* storage blocked */ }
if (repeat && ended) restart();
+137 -28
View File
@@ -208,11 +208,6 @@ h1, h2, h3, p, dl, dd, ul { margin: 0; }
.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; }
@@ -407,7 +402,6 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
.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); }
@@ -417,14 +411,14 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
.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;
display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); position: fixed; left: 0; right: 0; bottom: 0; z-index: 34; /* above the sticky filter bar (.slice, 32) */
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:not(.nav-ico):not(.nav-badge) { 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); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 35; 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); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
.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); }
@@ -520,19 +514,6 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
.chip-btn { min-height: var(--row-h); padding: 2px 12px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-raised); cursor: pointer; font-variant-numeric: tabular-nums; }
.chip-btn:hover { border-color: var(--line-strong); }
.chip-btn[aria-pressed="true"] { background: var(--accent); color: var(--on-accent); border-color: transparent; font-weight: 600; }
.range-picker { position: relative; display: inline-flex; gap: var(--s-2); align-items: center; flex-wrap: wrap; }
.rp-title { color: var(--ink-muted); font-size: .8125rem; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; margin-bottom: 6px; }
.rp-custom { display: grid; gap: var(--s-2); }
.rp-custom label { display: grid; gap: 2px; font-size: .875rem; color: var(--ink-muted); }
.rp-custom input { width: 100%; }
.rp-err { color: var(--danger); min-height: 1.2em; font-size: .875rem; }
.rp-scrim { display: none; }
@media (max-width: 767px) {
.rp-shortcuts { display: none; }
.rp-pop { position: fixed; left: 0; right: 0; bottom: 0; top: auto; width: auto; z-index: 60; border-radius: 14px 14px 0 0; max-height: 85vh; overflow-y: auto; padding: var(--s-4); }
.rp-scrim:not([hidden]) { display: block; z-index: 55; }
.chip-btn { min-height: var(--row-h-touch); }
}
/* tables as cards, grouped tables, untrusted text, chips */
.tbl-group td { background: var(--surface-raised); font-weight: 600; color: var(--ink-muted); }
@@ -581,15 +562,8 @@ aside#detail { display: flex; flex-direction: column; gap: var(--s-3); }
@media (max-width: 767px) { .btn, select, input[type="text"], input[type="number"], input[type="search"], input[type="datetime-local"] { min-height: var(--row-h-touch); } }
input[type="datetime-local"] { background: var(--surface-raised); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 6px 12px; min-height: 36px; }
.grid-12 { align-items: stretch; }
.rp-btn { flex: none; width: max-content; max-width: 100%; padding: 6px 14px; }
.range-picker { flex-wrap: nowrap; }
.card-map .mapbox { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
@media (max-width: 1199px) { .card-map .mapbox { grid-template-columns: 1fr; } }
.rp-btn { gap: 8px; }
.rp-caret { flex: none; }
.rp-label { white-space: nowrap; }
@media (max-width: 767px) { .rp-btn { min-width: 0; max-width: 100%; } .rp-label { overflow: hidden; text-overflow: ellipsis; } .range-picker { min-width: 0; max-width: 100%; } }
.rp-btn { padding: 6px 12px; gap: 6px; }
.lead { overflow: clip; }
.mini-wrap { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 6px; align-items: stretch; }
.mini-scale { display: flex; flex-direction: column; justify-content: space-between; height: 56px; font-size: 11px; color: var(--ink-faint); text-align: right; }
@@ -699,3 +673,138 @@ html, body { overflow-x: clip; }
}
.ipv.ipv-long { font-size: .75rem; }
@media (max-width: 767px) { .ipv.ipv-long { font-size: .65rem; } }
/* ---------------------------------------------------------------- filter bar (period + host), sticky */
.slice-sentinel { height: 1px; margin-bottom: -1px; }
.slice { position: sticky; top: var(--topbar-h); z-index: 32; display: flex; flex-direction: column; gap: 6px; padding: var(--s-3) var(--s-6) var(--s-2);
background: var(--surface-base); border-bottom: 1px solid transparent; transition: padding .15s, border-color .15s, box-shadow .15s; }
.slice.is-stuck { padding-top: var(--s-2); border-bottom-color: var(--line); box-shadow: 0 6px 16px -10px rgba(0, 0, 0, .45); }
.slice.is-stuck .slice-sum { display: none; }
.slice-ctl { display: flex; flex-wrap: wrap; gap: var(--s-2); align-items: stretch; min-width: 0; }
.slice-ctl select { max-width: 100%; }
.range-picker, .host-picker { position: relative; display: flex; align-items: stretch; min-width: 0; }
.range-picker { gap: 0; }
.host-picker[hidden] { display: none; }
.fb-trigger { display: inline-flex; align-items: center; gap: 10px; min-height: 44px; padding: 4px 12px; max-width: 100%; min-width: 0; cursor: pointer; text-align: left;
color: var(--ink); background: var(--surface-raised); border: 1px solid var(--line); border-radius: var(--radius-sm); font: inherit; }
.fb-trigger:hover { border-color: var(--line-strong); background: var(--surface-overlay); }
.fb-trigger[aria-expanded="true"] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
.fb-trigger:focus-visible, .fb-step:focus-visible, .fb-chip:focus-visible, .fb-opt:focus-visible, .fb-link:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
.fb-trigger > svg { width: 18px; height: 18px; flex: none; color: var(--ink-muted); }
.fb-txt { display: flex; flex-direction: column; min-width: 0; line-height: 1.15; }
.fb-k { font-size: .6875rem; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-faint); }
.fb-val { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
.fb-valrow { display: inline-flex; align-items: center; gap: 6px; min-width: 0; }
.fb-tz { flex: none; font: 600 .6875rem/1 var(--font-mono); color: var(--ink-muted); padding: 3px 6px; border: 1px solid var(--line); border-radius: 5px; background: var(--surface-sunken); }
.fb-caret { display: inline-flex; flex: none; color: var(--ink-muted); }
.fb-caret svg { width: 16px; height: 16px; transition: transform .15s; }
.fb-trigger[aria-expanded="true"] .fb-caret svg { transform: rotate(180deg); }
.fb-period.is-custom { border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); }
.fb-step { flex: none; width: 36px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; color: var(--ink-muted); background: var(--surface-raised); border: 1px solid var(--line); }
.fb-step[hidden] { display: none; }
.fb-step svg { width: 16px; height: 16px; }
.fb-step:hover:not(:disabled) { color: var(--ink); background: var(--surface-overlay); }
.fb-step:disabled { opacity: .4; cursor: default; }
.fb-step:first-child { border-radius: var(--radius-sm) 0 0 var(--radius-sm); border-right: 0; }
.fb-step:first-child:not([hidden]) + .fb-period { border-radius: 0; }
.fb-period:has(+ .fb-step:not([hidden])) { border-top-right-radius: 0; border-bottom-right-radius: 0; }
.fb-period + .fb-step { border-radius: 0 var(--radius-sm) var(--radius-sm) 0; border-left: 0; }
.fb-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--ink-faint); }
.fb-dot.on { background: var(--ok); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 22%, transparent); }
.fb-dot.warn { background: var(--warn); box-shadow: 0 0 0 3px color-mix(in srgb, var(--warn) 22%, transparent); }
.fb-dot.off { background: var(--danger); box-shadow: 0 0 0 3px color-mix(in srgb, var(--danger) 22%, transparent); }
.fb-count { flex: none; font-size: .75rem; font-weight: 600; padding: 2px 7px; border-radius: 999px; font-variant-numeric: tabular-nums; background: var(--surface-sunken); color: var(--ink-muted); border: 1px solid var(--line); }
.fb-count.on { color: var(--ok); background: var(--ok-soft); border-color: transparent; }
.fb-count.warn { color: var(--warn); background: var(--warn-soft); border-color: transparent; }
.fb-count.off { color: var(--danger); background: var(--danger-soft); border-color: transparent; }
/* popover (desktop) / sheet (phone) */
.fb-pop { position: absolute; z-index: 60; top: calc(100% + 6px); left: 0; background: var(--surface-overlay); border: 1px solid var(--line-strong); border-radius: var(--radius); box-shadow: var(--shadow); padding: var(--s-4); display: flex; flex-direction: column; gap: var(--s-3); }
.fb-pop[hidden], .fb-scrim[hidden] { display: none; }
.fb-pop-period { width: min(660px, calc(100vw - 32px)); }
.fb-pop-host { width: min(340px, calc(100vw - 32px)); padding: var(--s-2); gap: 0; }
.fb-head { display: none; }
.fb-cols { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); gap: var(--s-4); }
.fb-col { display: flex; flex-direction: column; gap: var(--s-2); min-width: 0; }
.fb-rel { min-width: max-content; }
.fb-abs { padding-left: var(--s-4); border-left: 1px solid var(--line); }
.fb-title { font-size: .75rem; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-muted); }
.fb-grp { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: var(--s-2); align-items: center; }
.fb-sub { font-size: .8125rem; color: var(--ink-faint); }
.fb-chips { display: flex; flex-wrap: nowrap; gap: 6px; min-width: 0; }
.fb-chip { white-space: nowrap; min-width: 46px; min-height: 34px; padding: 2px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink); cursor: pointer; font: 500 .875rem var(--font-sans); font-variant-numeric: tabular-nums; }
.fb-chip:hover { border-color: var(--line-strong); }
.fb-chip[aria-pressed="true"] { background: var(--accent); color: var(--on-accent); border-color: transparent; font-weight: 700; }
.fb-field { display: grid; gap: 3px; font-size: .8125rem; color: var(--ink-muted); }
.fb-field input { width: 100%; min-width: 0; color: var(--ink); }
.fb-field input[aria-invalid="true"] { border-color: var(--danger); }
.fb-note { margin: 0; font-size: .75rem; color: var(--ink-faint); }
.fb-err { margin: 0; color: var(--danger); font-size: .8125rem; min-height: 1.1em; }
.fb-err:empty { min-height: 0; }
.fb-apply { min-height: 40px; }
.fb-keys { margin: 0; padding-top: var(--s-2); border-top: 1px solid var(--line); font-size: .75rem; color: var(--ink-faint); }
.fb-opts { display: flex; flex-direction: column; gap: 2px; }
.fb-opt { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; min-height: 44px; padding: 6px 10px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--ink); cursor: pointer; text-align: left; font: inherit; }
.fb-opt:hover { background: var(--surface-raised); }
.fb-opt[aria-pressed="true"] { background: var(--accent-soft); }
.fb-opt-t { display: flex; flex-direction: column; min-width: 0; line-height: 1.2; }
.fb-opt-n { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fb-opt-m { font-size: .75rem; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fb-tick { display: inline-flex; color: var(--accent); visibility: hidden; }
.fb-tick svg { width: 16px; height: 16px; }
.fb-opt[aria-pressed="true"] .fb-tick { visibility: visible; }
.fb-opt:first-child { border-bottom: 1px solid var(--line); border-radius: var(--radius-sm) var(--radius-sm) 0 0; margin-bottom: 2px; }
/* summary line */
.slice-sum { display: flex; align-items: center; gap: var(--s-2) var(--s-3); flex-wrap: wrap; min-width: 0; }
.slice-txt { margin: 0; color: var(--ink-muted); font-size: .8125rem; min-width: 0; flex: 1 1 auto; }
.slice-txt strong { color: var(--ink); font-weight: 600; }
.slice-tools { display: inline-flex; gap: var(--s-1); flex: none; }
.fb-mode { display: inline-flex; align-items: center; gap: 6px; margin-right: 4px; padding: 1px 8px; border-radius: 999px; font-size: .6875rem; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; vertical-align: 1px; }
.fb-mode.is-live { color: var(--ok); background: var(--ok-soft); }
.fb-mode.is-fixed { color: var(--ink-muted); background: var(--surface-raised); border: 1px solid var(--line); }
.fb-pulse { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
.fb-mode.is-live .fb-pulse { animation: fb-pulse 2s ease-in-out infinite; }
@keyframes fb-pulse { 50% { opacity: .3; } }
.fb-link { display: inline-flex; align-items: center; gap: 5px; min-height: 32px; padding: 2px 8px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--accent); font: 600 .8125rem var(--font-sans); cursor: pointer; }
.fb-link[hidden] { display: none; }
.fb-link:hover { background: var(--accent-soft); }
.fb-link svg { width: 15px; height: 15px; }
.fb-scrim { display: none; }
@media (prefers-reduced-motion: reduce) { .fb-mode.is-live .fb-pulse { animation: none; } .slice { transition: none; } }
@media (max-width: 767px) {
.slice { padding: var(--s-2) var(--s-4) var(--s-2); }
.slice-ctl { flex-wrap: nowrap; }
.range-picker { flex: 1 1 60%; }
.host-picker { flex: 1 1 40%; }
.fb-period, .fb-host { flex: 1 1 auto; }
.fb-trigger { gap: 8px; padding: 4px 10px; }
.fb-trigger > svg, .fb-tz { display: none; }
.fb-host .fb-count { display: none; }
.fb-step { display: none; }
.fb-period, .fb-period.is-custom { border-radius: var(--radius-sm) !important; }
.slice-ctl select { flex: 1 1 100%; }
.slice-ctl:has(#domain:not([hidden])) { flex-wrap: wrap; }
.fb-link { min-height: 44px; }
.fb-copy span { display: none; }
/* the sheet opens just above the bottom tab bar (65 px + safe area), never over it */
.fb-pop { position: fixed; left: 0; right: 0; bottom: calc(65px + env(safe-area-inset-bottom, 0px)); top: auto; width: auto; z-index: 61; border-radius: 16px 16px 0 0; border-bottom: 0; max-height: calc(100dvh - 65px - env(safe-area-inset-bottom, 0px) - var(--topbar-h) - 8px); overflow-y: auto; overscroll-behavior: contain;
padding: var(--s-3) var(--s-4) var(--s-4); }
.fb-pop-host { width: auto; padding: var(--s-3) var(--s-4) var(--s-4); gap: var(--s-2); }
.fb-head { display: flex; align-items: center; justify-content: space-between; gap: var(--s-2); }
.fb-head h2 { margin: 0; font: 700 1rem var(--font-display); color: var(--heading); }
.fb-x { width: 44px; min-height: 44px; }
.fb-x svg { width: 18px; height: 18px; }
.fb-cols { grid-template-columns: 1fr; }
.fb-abs { padding-left: 0; border-left: 0; padding-top: var(--s-3); border-top: 1px solid var(--line); }
.fb-grp { grid-template-columns: 1fr; gap: 4px; }
.fb-chips { flex-wrap: wrap; }
.fb-rel { min-width: 0; }
.fb-chip { min-height: 44px; flex: 1 0 calc(20% - 6px); }
.fb-opt { min-height: 52px; }
.fb-apply { min-height: 44px; }
.fb-keys { display: none; }
.fb-scrim:not([hidden]) { display: block; position: fixed; inset: 0; z-index: 60; background: var(--scrim); }
:root.fb-lock, :root.fb-lock body { overflow: hidden; }
}
+4 -1
View File
@@ -28,7 +28,10 @@ type Pos struct {
FPLen int
}
const fpMax = 64
// fpMax covers a whole first line: Traefik's first 64 bytes (client address and
// port of a keep-alive connection) repeat across rotations, so a short head
// cannot tell two generations of the file apart.
const fpMax = 1024
func fingerprint(b []byte) uint64 {
h := uint64(14695981039346656037)
+13
View File
@@ -155,3 +155,16 @@ func TestStalePosAndBackups(t *testing.T) {
t.Fatalf("%v", got)
}
}
// Traefik: the first 64 bytes of each rotated generation were identical (same
// keep-alive client address and port), so the head must cover the whole line.
func TestHeadCoversFirstLine(t *testing.T) {
a := []byte(`{"ClientAddr":"195.200.0.252:34352","ClientHost":"195.200.0.252","StartUTC":"2026-11-16T21:06:20.1Z"}` + "\n")
b := []byte(`{"ClientAddr":"195.200.0.252:34352","ClientHost":"195.200.0.252","StartUTC":"2026-11-16T22:48:21.7Z"}` + "\n")
if fingerprint(a[:64]) != fingerprint(b[:64]) {
t.Fatal("fixture: the first 64 bytes should collide")
}
if fpMax < len(a) || fingerprint(a) == fingerprint(b) {
t.Fatal("head fingerprint must tell the two generations apart")
}
}