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
- Variables
- func ClassifyUA(ua string) (UAKind, *Bot)
- func DiscoverLogs(base string, since time.Time) ([]string, error)
- func Follow(ctx context.Context, path string, poll time.Duration, fn func(Entry) error) error
- func Format(w io.Writer, r *Report, topN int)
- func FormatLive(e Entry, v Visitor, country string) string
- func Header(h map[string][]string, name string) string
- func IsAsset(e Entry) bool
- func IsProbePath(path string) bool
- func ResolveCountry(e Entry, geo CountryLookup) (country, source string)
- func UpdateGeoDB(ctx context.Context, client *http.Client, path string, now time.Time) (string, error)
- type Analyzer
- type Bot
- type BotStat
- type Count
- type CountryLookup
- type CountryStat
- type DNSVerifier
- type Entry
- type FileSource
- type GeoInfo
- type Layer
- type LayerStat
- type Live
- type MMDBLookup
- type Options
- type Report
- type Resolver
- type Served
- type SidecarStat
- type Source
- type Suspect
- type UAKind
- type Verdict
- type Verifier
- type Visitor
- type VisitorStat
Constants ¶
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.
const ( GeoSourceCloudflare = "cloudflare-header" GeoSourceDB = "dbip-lite" GeoSourceNone = "none" )
Country sources, reported so the reader knows how much to trust the column.
const DefaultAccessLog = "/var/log/caddy/access.log"
DefaultAccessLog is the file every NextDeploy site block logs to.
const DefaultGeoDBPath = "/var/lib/nextdeploy/geo/dbip-country-lite.mmdb"
DefaultGeoDBPath is where `nextdeployd prepare` installs the DB-IP Lite country database.
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 ¶
var AllVisitors = []Visitor{VisitorHuman, VisitorVerifiedBot, VisitorDeclaredBot, VisitorFakeBot, VisitorScanner, VisitorAutomation}
AllVisitors is the display order.
Functions ¶
func DiscoverLogs ¶
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 ¶
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 FormatLive ¶
FormatLive renders one classified request for --follow.
func Header ¶
Header returns the first value of a header, case-insensitively (Caddy logs Go-canonicalised keys such as "Cf-Ipcountry" / "X-Nextdeploy-Handler").
func IsAsset ¶
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 ¶
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 (*Analyzer) FinalizeClients ¶
FinalizeClients labels every client. Crawler claims are DNS-verified here (bounded by MaxVerify, busiest claimants first).
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 ¶
IdentifyBot returns the crawler a user agent claims to be, or nil.
func (*Bot) Verifiable ¶
Verifiable reports whether the bot's identity can be proven via DNS.
type CountryLookup ¶
CountryLookup maps an IP to an ISO 3166-1 alpha-2 code ("" if unknown).
type CountryStat ¶
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:
- reverse-resolve the IP (PTR) and require a name under the operator's domain (e.g. crawl-66-249-66-1.googlebot.com);
- 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.
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 ¶
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) ViaCloudflare ¶
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 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 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).
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 (*MMDBLookup) Close ¶
func (m *MMDBLookup) Close() error
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.
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 ¶
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 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 )