traffic

package
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package traffic turns Caddy's JSON access log into an answer to "who is hitting my VPS, from where, and which layer served them": real visitors vs verified crawlers vs bots faking a crawler's identity vs scanners, broken down by country and by serving layer (Caddy static, Go sidecar, Node).

Everything here is pure and side-effect free except the DNS verifier and the GeoIP reader, both of which sit behind interfaces so tests stay offline.

Index

Constants

View Source
const (
	// A browser UA that requests this many documents without ever fetching a
	// script, stylesheet, image or RSC payload is a scraper wearing a
	// browser's user agent: real browsers load sub-resources.
	NoAssetPageThreshold = 5
	// This many 4xx-not-found responses, making up most of a client's
	// traffic, is path enumeration.
	NotFoundStormThreshold = 10

	// Cap on DNS verifications per report (each is up to two lookups).
	DefaultMaxVerify = 500
)

Thresholds for the behavioural (per-client) rules. Exported so docs and tests reference one source of truth.

View Source
const (
	GeoSourceCloudflare = "cloudflare-header"
	GeoSourceDB         = "dbip-lite"
	GeoSourceNone       = "none"
)

Country sources, reported so the reader knows how much to trust the column.

View Source
const DefaultAccessLog = "/var/log/caddy/access.log"

DefaultAccessLog is the file every NextDeploy site block logs to.

View Source
const DefaultGeoDBPath = "/var/lib/nextdeploy/geo/dbip-country-lite.mmdb"

DefaultGeoDBPath is where `nextdeployd prepare` installs the DB-IP Lite country database.

View Source
const GeoAttribution = "IP Geolocation by DB-IP (https://db-ip.com)"

GeoAttribution is required by the DB-IP Lite licence (CC BY 4.0) wherever its data is shown.

Variables

AllVisitors is the display order.

Functions

func ClassifyUA

func ClassifyUA(ua string) (UAKind, *Bot)

ClassifyUA reads a user agent string.

func DiscoverLogs

func DiscoverLogs(base string, since time.Time) ([]string, error)

DiscoverLogs returns base plus its logrotate siblings (base.1, base.2.gz, …) oldest first, skipping rotations last written before since — every line in such a file is older than the window.

func Follow

func Follow(ctx context.Context, path string, poll time.Duration, fn func(Entry) error) error

Follow tails path from its end, calling fn for each new entry until ctx is cancelled. It survives logrotate's copytruncate (file shrinks → restart at 0) and rename-style rotation (inode changes → reopen).

func Format

func Format(w io.Writer, r *Report, topN int)

Format renders a human-readable report.

func FormatLive

func FormatLive(e Entry, v Visitor, country string) string

FormatLive renders one classified request for --follow.

func Header(h map[string][]string, name string) string

Header returns the first value of a header, case-insensitively (Caddy logs Go-canonicalised keys such as "Cf-Ipcountry" / "X-Nextdeploy-Handler").

func IsAsset

func IsAsset(e Entry) bool

IsAsset reports whether a request is a page sub-resource a real browser fetches after the document: hashed chunks, images, RSC payloads, fonts.

func IsProbePath

func IsProbePath(path string) bool

IsProbePath reports whether a request path is a vulnerability probe.

func ResolveCountry

func ResolveCountry(e Entry, geo CountryLookup) (country, source string)

ResolveCountry picks the best country for a request and says where it came from. CF-IPCountry wins, but ONLY when the TCP peer is a Cloudflare edge: a client connecting straight to the origin can send any CF-IPCountry it likes. "T1" (Tor) is kept as a pseudo-country because it is useful signal.

func UpdateGeoDB

func UpdateGeoDB(ctx context.Context, client *http.Client, path string, now time.Time) (string, error)

UpdateGeoDB downloads the current DB-IP Lite country database to path, falling back to last month's edition early in a month before the new one is published. The file is validated by opening it before an atomic rename, so a bad download never replaces a working database.

Types

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer accumulates a two-pass analysis. Use Analyze unless streaming.

func NewAnalyzer

func NewAnalyzer(opts Options) *Analyzer

NewAnalyzer creates an empty analyzer.

func (*Analyzer) Accept

func (a *Analyzer) Accept(e Entry) bool

Accept applies the time window and host filter.

func (*Analyzer) FinalizeClients

func (a *Analyzer) FinalizeClients(ctx context.Context)

FinalizeClients labels every client. Crawler claims are DNS-verified here (bounded by MaxVerify, busiest claimants first).

func (*Analyzer) Observe

func (a *Analyzer) Observe(e Entry)

Observe is pass 1: build per-client behaviour profiles.

func (*Analyzer) Report

func (a *Analyzer) Report() *Report

Report finalises and returns the report.

func (*Analyzer) Tally

func (a *Analyzer) Tally(e Entry)

Tally is pass 2: count every request under its client's final label.

type Bot

type Bot struct {
	Name     string
	Operator string
	// RDNSSuffixes, when set, make the bot verifiable: a reverse lookup of the
	// IP must end in one of these AND the name must resolve back to the IP
	// (forward-confirmed reverse DNS, the method Google/Bing/Apple document).
	RDNSSuffixes []string
}

Bot is a known crawler identified by its user agent.

func IdentifyBot

func IdentifyBot(ua string) *Bot

IdentifyBot returns the crawler a user agent claims to be, or nil.

func (*Bot) Verifiable

func (b *Bot) Verifiable() bool

Verifiable reports whether the bot's identity can be proven via DNS.

type BotStat

type BotStat struct {
	Name       string `json:"name"`
	Operator   string `json:"operator"`
	Requests   int64  `json:"requests"`
	Verified   int64  `json:"verified"`
	Unverified int64  `json:"unverified"`
	Fake       int64  `json:"fake"`
}

type Count

type Count struct {
	Key   string `json:"key"`
	Count int64  `json:"count"`
}

type CountryLookup

type CountryLookup interface {
	Country(ip netip.Addr) string
	Close() error
}

CountryLookup maps an IP to an ISO 3166-1 alpha-2 code ("" if unknown).

type CountryStat

type CountryStat struct {
	Country  string `json:"country"` // ISO-3166 alpha-2, "T1" = Tor, "??" = unknown
	Requests int64  `json:"requests"`
	Human    int64  `json:"human"`
	Bots     int64  `json:"bots"` // all non-human, including fake + scanner
	Fake     int64  `json:"fake"`
	Scanner  int64  `json:"scanner"`
}

type DNSVerifier

type DNSVerifier struct {
	Resolver Resolver
	Timeout  time.Duration
	// contains filtered or unexported fields
}

DNSVerifier implements forward-confirmed reverse DNS, the verification method Google, Bing and Apple document for their crawlers:

  1. reverse-resolve the IP (PTR) and require a name under the operator's domain (e.g. crawl-66-249-66-1.googlebot.com);
  2. resolve that name forward and require it to map back to the same IP.

Step 2 matters: anyone can set a PTR record on their own IP block that claims to be googlebot.com, but they can't make googlebot.com resolve to it.

func NewDNSVerifier

func NewDNSVerifier() *DNSVerifier

NewDNSVerifier uses the system resolver with a 2s per-lookup timeout.

func (*DNSVerifier) Verify

func (v *DNSVerifier) Verify(ctx context.Context, ip netip.Addr, bot *Bot) Verdict

type Entry

type Entry struct {
	Time       time.Time
	RemoteIP   string // TCP peer (a Cloudflare edge when proxied)
	ClientIP   string // real visitor once trusted_proxies is configured
	Method     string
	Host       string
	URI        string
	Path       string
	Proto      string
	Status     int
	Size       int64
	Duration   time.Duration
	ReqHeaders map[string][]string
	ResHeaders map[string][]string
}

Entry is the subset of a Caddy access-log line the analyzer needs.

func ParseLine

func ParseLine(line []byte) (Entry, bool, error)

ParseLine decodes one Caddy JSON access-log line. ok=false for blank lines and non-access entries (Caddy writes other loggers to the same file on some setups); err only for malformed JSON.

func (Entry) Addr

func (e Entry) Addr() netip.Addr

Addr parses the visitor IP; invalid → zero Addr.

func (Entry) UserAgent

func (e Entry) UserAgent() string

UserAgent is the request's User-Agent ("" when absent).

func (Entry) ViaCloudflare

func (e Entry) ViaCloudflare() bool

ViaCloudflare reports whether the TCP peer is a Cloudflare edge — the only case in which Cloudflare-set request headers (CF-IPCountry) can be trusted.

type FileSource

type FileSource struct {
	Paths       []string
	ParseErrors int64
	// contains filtered or unexported fields
}

FileSource replays a list of (optionally gzipped) Caddy JSON log files.

func (*FileSource) Source

func (f *FileSource) Source() Source

Source adapts the files to traffic.Source. Parse errors are counted on the first pass only so they aren't double-reported.

type GeoInfo

type GeoInfo struct {
	Sources     map[string]int64 `json:"sources"`
	Attribution string           `json:"attribution,omitempty"`
}

type Layer

type Layer string

Layer is which part of the NextDeploy VPS stack answered a request.

const (
	LayerCaddyStatic Layer = "caddy-static" // _next/static or public/ file, Node never woke
	LayerSidecar     Layer = "go-sidecar"   // prerendered HTML/RSC or optimized image from the Go sidecar
	LayerNode        Layer = "node"         // sidecar forwarded to Node (see Fallback for why)
	LayerNodeDirect  Layer = "node-direct"  // Node answered without the sidecar (none deployed, or it was down)
	LayerBlocked     Layer = "blocked"      // rejected before the app (WAF / Caddy 403)
	LayerCaddyError  Layer = "caddy-error"  // upstream unreachable (502/503/504 from Caddy itself)
	LayerOther       Layer = "caddy-other"  // answered by Caddy, origin unclear
)

type LayerStat

type LayerStat struct {
	Layer    Layer   `json:"layer"`
	Requests int64   `json:"requests"`
	Pct      float64 `json:"pct"`
	Humans   int64   `json:"humans"`
	Bots     int64   `json:"bots"`
	P50Ms    float64 `json:"p50_ms"` // bucket upper bound; -1 = over 10s
	P95Ms    float64 `json:"p95_ms"`
}

type Live

type Live struct {
	// contains filtered or unexported fields
}

Live classifies entries one at a time for `--follow`, using whatever it has seen so far about each client (no second pass).

func NewLive

func NewLive(opts Options) *Live

NewLive creates a streaming classifier.

func (*Live) Accept

func (l *Live) Accept(e Entry) bool

Accept exposes the filter for the live path.

func (*Live) Classify

func (l *Live) Classify(ctx context.Context, e Entry) (Visitor, string, string)

Classify observes e and returns the client's current label.

type MMDBLookup

type MMDBLookup struct {
	// contains filtered or unexported fields
}

MMDBLookup reads a MaxMind-format country database (DB-IP Lite or GeoLite2-Country — both use the same "country.iso_code" layout).

func OpenMMDB

func OpenMMDB(path string) (*MMDBLookup, error)

OpenMMDB opens a .mmdb file.

func (*MMDBLookup) Close

func (m *MMDBLookup) Close() error

func (*MMDBLookup) Country

func (m *MMDBLookup) Country(ip netip.Addr) string

type Options

type Options struct {
	Since, Until time.Time
	Hosts        []string // only these hosts (exact, lower-case); empty = all
	Geo          CountryLookup
	Verifier     Verifier
	MaxVerify    int
	TopN         int
}

Options configures an analysis run.

type Report

type Report struct {
	GeneratedAt time.Time `json:"generated_at"`
	From        time.Time `json:"from"`
	To          time.Time `json:"to"`
	Hosts       []string  `json:"hosts,omitempty"`
	Files       []string  `json:"files,omitempty"`
	Lines       int64     `json:"lines"`
	ParseErrors int64     `json:"parse_errors"`

	Requests int64 `json:"requests"`
	Clients  int64 `json:"clients"`
	Bytes    int64 `json:"bytes"`

	Visitors  []VisitorStat       `json:"visitors"`
	Layers    []LayerStat         `json:"layers"`
	Sidecar   SidecarStat         `json:"sidecar"`
	Countries []CountryStat       `json:"countries"`
	Bots      []BotStat           `json:"bots"`
	TopRoutes map[Visitor][]Count `json:"top_routes"`
	Statuses  []Count             `json:"statuses"`
	Suspects  []Suspect           `json:"suspects"`
	Geo       GeoInfo             `json:"geo"`
	Notes     []string            `json:"notes,omitempty"`
}

Report is the JSON contract of `nextdeployd traffic --json` and `nextdeploy logs traffic --json`. Add fields; don't rename them — agents and the MCP tool parse this.

func Analyze

func Analyze(ctx context.Context, src Source, opts Options) (*Report, error)

Analyze runs both passes over src.

type Resolver

type Resolver interface {
	LookupAddr(ctx context.Context, addr string) ([]string, error)
	LookupHost(ctx context.Context, host string) ([]string, error)
}

Resolver is the subset of *net.Resolver the DNS verifier uses.

type Served

type Served struct {
	Layer    Layer
	Handler  string // go-html | go-rsc | go-image | node
	Cache    string // HIT | STALE | MISS-SSR
	Fallback string // why the sidecar forwarded to Node
}

Served describes who answered a request.

func ClassifyServed

func ClassifyServed(e Entry) Served

ClassifyServed reads the attribution headers the Go sidecar stamps on every response it touches (X-NextDeploy-Sidecar/Handler/Cache/Fallback), which Caddy records in resp_headers. Responses without them never reached the sidecar, so they are attributed from path and status.

type SidecarStat

type SidecarStat struct {
	Requests        int64   `json:"requests"` // requests that reached the sidecar
	ServedByGo      int64   `json:"served_by_go"`
	ForwardedToNode int64   `json:"forwarded_to_node"`
	GoPct           float64 `json:"go_pct"`
	Handlers        []Count `json:"handlers"`
	Cache           []Count `json:"cache"`
	FallbackReasons []Count `json:"fallback_reasons"`
}

SidecarStat answers "how much did the Go sidecar serve vs hand to Node".

type Source

type Source func(fn func(Entry) error) error

Source replays the input once per call; Analyze calls it twice.

type Suspect

type Suspect struct {
	IP          string   `json:"ip"`
	Country     string   `json:"country,omitempty"`
	UserAgent   string   `json:"user_agent"`
	Visitor     Visitor  `json:"visitor"`
	Requests    int64    `json:"requests"`
	Reason      string   `json:"reason"`
	SamplePaths []string `json:"sample_paths,omitempty"`
}

type UAKind

type UAKind int

UAKind is the first-pass, per-request reading of a user agent.

const (
	UABrowser UAKind = iota
	UAKnownBot
	UAGenericBot
	UAAttackTool
	UAAutomation
	UAEmpty
	UAUnknown
)

type Verdict

type Verdict int

Verdict is the outcome of checking a crawler's claimed identity.

const (
	VerdictUnknown  Verdict = iota // DNS failed/timed out — never treated as fake
	VerdictVerified                // forward-confirmed reverse DNS matches the operator
	VerdictFake                    // IP provably does not belong to the claimed operator
)

type Verifier

type Verifier interface {
	Verify(ctx context.Context, ip netip.Addr, bot *Bot) Verdict
}

Verifier checks whether ip really belongs to bot's operator.

type Visitor

type Visitor string

Visitor is the kind of client behind a request.

const (
	VisitorHuman       Visitor = "human"        // real browser that behaves like one
	VisitorVerifiedBot Visitor = "verified-bot" // crawler whose IP is proven to belong to its operator
	VisitorDeclaredBot Visitor = "declared-bot" // honest bot user agent, not (or not yet) verifiable
	VisitorFakeBot     Visitor = "fake-bot"     // claims to be Googlebot/Bingbot/… but the IP is not theirs
	VisitorScanner     Visitor = "scanner"      // vulnerability probes, WAF hits, 404 storms
	VisitorAutomation  Visitor = "automation"   // curl/scripts/headless or a browser UA that never loads assets
)

func (Visitor) IsBot

func (v Visitor) IsBot() bool

IsBot reports whether v is non-human traffic.

type VisitorStat

type VisitorStat struct {
	Visitor  Visitor `json:"visitor"`
	Requests int64   `json:"requests"`
	Clients  int64   `json:"clients"`
	Pct      float64 `json:"pct"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL