tokenhound

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 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.

README

TokenHound

Find leaked AI keys before attackers do.

TokenHound finds leaked AI provider keys wherever developers and coding agents leave them: agent configs and transcripts on your machine, the working tree, staged changes, full git history, container images, archives, notebooks and whole GitHub orgs or GitLab groups. It verifies each key safely with read-only calls, prices the exposure in dollars at risk per day and rolls it all into an A to F grade.

Status: early development. The repository skeleton is in place; scanning arrives in the next releases. See CHANGELOG.md.

Build from source

Requirements: Go 1.27 or later and git.

git clone https://github.com/aiagentpro/tokenhound.git
cd tokenhound
make build            # writes bin/tokenhound (bin/tokenhound.exe on Windows)
./bin/tokenhound --help

Or install straight into your GOBIN:

go install github.com/aiagentpro/tokenhound/cmd/tokenhound@latest

Usage

tokenhound                             # this machine's agent files, plus the current repo (see docs/surfaces.md)
tokenhound agents                      # only the agent files: Claude Code, Codex, Cursor, shell history, .npmrc
tokenhound scan                        # scan the current directory
tokenhound scan path/to/repo           # scan a directory or one file
echo "$TEXT" | tokenhound scan -       # scan standard input
tokenhound scan --history              # also every commit's added lines, with first commit and age
tokenhound scan --since v1.2.0         # history after a tag, branch or commit
tokenhound scan --staged               # also the staged changes (see docs/git.md)
tokenhound scan --format json          # the JSON Report on stdout, summary on stderr
tokenhound scan --format json -o r.json             # the JSON Report to a file
tokenhound scan --format json,terminal -o reports   # reports/tokenhound.json, summary on stdout
tokenhound version                     # version, build and registry snapshot
tokenhound providers                   # providers and detectors this binary knows
tokenhound providers --format json     # the same as JSON
tokenhound providers --spend           # spend tiers, limits and prices behind dollars at risk
tokenhound providers --surfaces        # the agent files each surface reads, per OS

Every command accepts --format, --log-format text|json and -v for debug logs. A usage error prints one line saying what is wrong and the correct form, and exits 2.

The terminal summary opens with a meta line, then one headline sentence such as 2 live keys, $3,100 a day at risk, grade D, then ranked rows (status word, provider, redacted key, dollars, first location), the reasons for the grade (Why D:) and exactly one Next: line. It shows 20 rows and +N more findings; --all shows every row, --quiet prints only the headline, and --plain (or a terminal under 80 columns, read from COLUMNS) stacks each row as key: value lines. Colour follows a TTY and is off for NO_COLOR, TERM=dumb, --no-color and --plain; words and grade letters are always printed. On a TTY, one updating scanning... N files, M commits line goes to stderr (not when CI=true or with --quiet). Each target (repo, machine) gets a grade A to F with a reason, and the overall grade is the worst: F for a live key over grade.f_threshold_usd_per_day (default 500) of dollars at risk per day or in a public target, D for any live key, C for an unverified high-confidence key, B for any other finding, A for none.

scan exit codes: 0 no unsuppressed finding matched fail_on (by default, no live key) and no warning matched fail_on.warnings, 1 at least one did, 2 a usage error, an invalid config, a path that cannot be scanned or a fatal error. Findings from generated test keys are suppressed unless --include-test-keys is given. The JSON Report follows docs/schema/report.v1.json.

Inside a git repository scan reads what git would commit (tracked files plus untracked files that are not ignored); --include-ignored walks everything. --history, --since <ref> and --staged add commit and staged locations, and findings with commit locations get first_seen and age_days. See docs/git.md.

scan also finds keys hidden in base64 (standard and URL-safe), percent-encoding, JSON escapes and env-file values, nested up to limits.decode_max_depth levels, and reports them at the line and column where the encoded form starts. Every finding has a confidence (high, medium or low) computed from the pattern, entropy, keyword context and decoding; a built-in generic.high-entropy detector catches high-entropy values assigned to api_key, token or secret names. The encodings, the generic detector and the confidence rule table are documented in docs/detection.md.

Providers detected today: OpenAI, Anthropic, Google Gemini, Google Vertex AI, Azure OpenAI, AWS (access key pairs and Amazon Bedrock API keys), Mistral AI, Cohere, Groq, xAI, DeepSeek, OpenRouter, Perplexity, Together AI, Fireworks AI, Hugging Face, Replicate, ElevenLabs, Stability AI, Voyage AI, Jina AI, Pinecone, LangSmith, Langfuse, Helicone and Cerebras (tokenhound providers lists them with their detectors). In v1.0 verification covers OpenAI, Anthropic, the Story 1.10 frontier set and Hugging Face; the other twelve (Together AI through Cerebras, without Hugging Face) are detected only. Two-part credentials, an AWS access key id with its secret access key, an Azure OpenAI key with its resource endpoint or a Langfuse secret key with its public key, are reported as one finding when both parts are in the same file; a key id found without its secret is reported alone with confidence: low and status_reason: unpaired.

Configuration

Every command resolves its configuration once, from these layers (highest first):

  1. flags: --no-verify (--no-verify=false changes nothing), --config, and on scan --fail-on-status, --fail-on-warnings, --fail-on-min-dollars and --timeout;
  2. TOKENHOUND_* environment variables;
  3. the user file <user config dir>/tokenhound/config.yaml (for example ~/.config/tokenhound/config.yaml on Linux);
  4. the project file tokenhound.yaml at the scan root (scan <dir>, a scanned file's directory, or the working directory for scan - and other commands); --config <file> (relative to the working directory) replaces it, and relative paths inside it resolve against the scan root;
  5. defaults.

Each set value replaces the one below it; lists replace whole. The exceptions are the gate keys of the project file (see trust tiers below): a project fail_on is unioned on top of every other layer, flags included, so it can only add statuses or warning codes or lower the minimum; a project limits.* or verify.timeout value applies only when it is higher than the value from the other layers (a limit at most to 4x its default), and a project grade.f_threshold_usd_per_day or verify.max_concurrency only when it is lower. Config files must be regular files. The schema is docs/schema/config.v1.json; a missing version means 1. An invalid config fails every command with exit 2 and one line per problem, for example tokenhound.yaml:7: fail_on.status[1]: value must be one of live, dead, unknown, rate-limited, not-verified.

version: 1
verify: true                      # or {enabled, max_concurrency: 8, timeout: 10s}
fail_on: { status: [live], min_dollars_at_risk: 0, warnings: [] }
ignore_file: .tokenhound-ignore
baseline: .tokenhound-baseline.json
import: { gitleaks: .gitleaks.toml, trufflehog: .trufflehog-ignore }
custom_detectors: detectors/
timeout: 120s                     # absent: no timeout; not from tokenhound.yaml
grade: { f_threshold_usd_per_day: 500 }
limits: { max_file_bytes: 10485760, archive_max_bytes: 268435456, archive_max_depth: 5,
          archive_max_entries: 10000, decode_max_depth: 3 }
# User file only:
alerts: { slack_webhook_env: SLACK_WEBHOOK }
network:
  https_proxy: ${HTTPS_PROXY}
  no_proxy: internal.example
  ca_bundle: /etc/ssl/corp.pem
  allow_hosts: [llm.internal.example]
hook: { mode: block, on_error: warn-allow }
ping: false

This release resolves and validates every key, but only fail_on, timeout and limits.max_file_bytes change what a scan does today. verify, grade, network, hook, alerts, ping, ignore_file, baseline, import and custom_detectors are resolved now and used by later releases. Integer keys accept integral floats such as 8.0. ${NAME} may appear anywhere a string can, including inside a one-line { ... } mapping such as network: { https_proxy: ${HTTPS_PROXY}, ca_bundle: /etc/ssl/corp.pem }.

Durations are Go duration strings such as 90s or 2m30s. timeout, verify.timeout and alerts.timeout must be greater than 0, and verify.timeout and alerts.timeout at most 5m. verify.max_concurrency is at most 64.

Every tier, the project file included, is bounded by the schema maxima: limits.max_file_bytes at most 1073741824 (1 GiB), archive_max_bytes at most 4294967296 (4 GiB), archive_max_depth at most 20, archive_max_entries at most 1000000 and decode_max_depth at most 10. A larger value is a config error. The project file may raise a limit only to 4x its default: max_file_bytes 41943040 (40 MiB), archive_max_bytes 1073741824 (1 GiB), archive_max_depth 20, archive_max_entries 40000 and decode_max_depth 10; a higher project value is ignored with an untrusted_config_key warning (detail project_limit_cap).

These are the only environment variables read; other TOKENHOUND_* names are ignored. A variable that is set but empty counts as unset, except TOKENHOUND_FAIL_ON_WARNINGS, where empty means no warning codes. An empty --fail-on-status is a usage error.

Variable Key
TOKENHOUND_VERIFY verify (true, false, 1, 0)
TOKENHOUND_VERIFY_MAX_CONCURRENCY verify.max_concurrency
TOKENHOUND_VERIFY_TIMEOUT verify.timeout
TOKENHOUND_FAIL_ON_STATUS fail_on.status (comma separated)
TOKENHOUND_FAIL_ON_MIN_DOLLARS_AT_RISK fail_on.min_dollars_at_risk
TOKENHOUND_FAIL_ON_WARNINGS fail_on.warnings (comma separated; empty means none)
TOKENHOUND_TIMEOUT timeout
TOKENHOUND_GRADE_F_THRESHOLD_USD_PER_DAY grade.f_threshold_usd_per_day
TOKENHOUND_HOOK_MODE hook.mode
TOKENHOUND_HOOK_ON_ERROR hook.on_error
TOKENHOUND_PING ping
TOKENHOUND_NETWORK_HTTPS_PROXY network.https_proxy
TOKENHOUND_NETWORK_NO_PROXY network.no_proxy
TOKENHOUND_NETWORK_CA_BUNDLE network.ca_bundle
TOKENHOUND_NETWORK_ALLOW_HOSTS network.allow_hosts (comma separated)
TOKENHOUND_LIMITS_MAX_FILE_BYTES limits.max_file_bytes

With CI=true, fail_on.warnings defaults to [timeout, file_too_large], so a scan cut short by its timeout, or one that skipped a file over limits.max_file_bytes (a key in it would go unseen), fails the build. A project tokenhound.yaml cannot drop either; set TOKENHOUND_FAIL_ON_WARNINGS or the flag in your own environment to change it.

Trust tiers: a repository can be hostile, so the project file cannot redirect network traffic or weaken your gate. From tokenhound.yaml, network.*, alerts.*, hook.* and ping are ignored; it cannot disable verification (verify: false), set timeout, lower a limits.* value or verify.timeout (higher values apply, a limit at most to 4x its default) or raise grade.f_threshold_usd_per_day or verify.max_concurrency (lower values apply); fail_on may only tighten (add statuses or warning codes, lower the minimum); and paths must stay inside the project root. Each ignored value becomes an untrusted_config_key warning (detail project_tier, gate_loosening, project_limit_cap or fail_on_loosening) or a config_path_outside_root warning, naming the key (never its value), logged and added to the Report. A ${NAME} reference in the project file is not expanded: the value is kept as a literal, with an untrusted_config_key warning (detail env_reference). In the user file, ${NAME} expands from the environment (an unset name expands to nothing).

Files larger than limits.max_file_bytes (and stdin over it) are skipped with a file_too_large warning and do not fail the run by default (they do under CI=true); add file_too_large to fail_on.warnings to fail on it elsewhere. Files with a NUL byte in their first 8 KiB are skipped as binary without a warning and counted in meta.binary_skipped. For a .ipynb notebook the limit applies to the cell text (image outputs do not count; the raw file may be up to 8 times larger).

With --deterministic the JSON Report is byte-identical across runs and operating systems: paths use forward slashes (machine paths start with ~/), output uses LF only, and every list and map is sorted with a total order (byte order of the full key, no locale, no file system order). A corpus test pins this against a golden on macOS, Linux and Windows. If --timeout expires, the Report holds what was found, one timeout warning per incomplete source and the terminal line "Partial results: scan stopped at Ns. N sources incomplete."; the exit code follows fail_on (1 when fail_on.warnings lists timeout, the default under CI=true).

Development

make help             # list targets
make tools            # install the pinned golangci-lint
make release-tools    # install the pinned goreleaser (for make snapshot)
make test             # unit tests with the race detector
make lint             # golangci-lint, including the architecture rules
make lint-selftest    # prove every architecture lint rule still fires
make dash-lint        # no em dashes, en dashes or ellipsis characters
make leak-test        # no output ever shows more of a key than its redacted form
make self-scan        # scan this repository; fails on any unsuppressed finding
make cover            # per-package coverage
make cover-core       # fails if a core package is below COVER_MIN (default 85) percent
make snapshot         # local cross-builds into dist/, nothing is published

See CONTRIBUTING.md before opening a pull request.

Security

Please report vulnerabilities privately through GitHub security advisories. See SECURITY.md.

License

TokenHound is licensed under the Apache License 2.0. The registry data under registry/ is dedicated to the public domain under CC0 1.0. See NOTICE.

Documentation

Overview

Package tokenhound finds leaked AI keys, verifies them safely and prices the exposure.

It is the public library API: Scan, Options, the Finding and Report model and the source constructors. The CLI and every other front door call this package and never import the engine or the pipeline stages directly.

Index

Constants

View Source
const (
	SurfaceFound        = model.SurfaceFound
	SurfaceNotInstalled = model.SurfaceNotInstalled
	SurfaceUnreadable   = model.SurfaceUnreadable
	SurfaceNotVisited   = model.SurfaceNotVisited
)

Surface statuses of Report.SurfacesChecked.

View Source
const (
	StatusLive        = model.StatusLive
	StatusDead        = model.StatusDead
	StatusUnknown     = model.StatusUnknown
	StatusRateLimited = model.StatusRateLimited
	StatusNotVerified = model.StatusNotVerified
)

Verification statuses.

View Source
const (
	ClassLive       = model.ClassLive
	ClassUnverified = model.ClassUnverified
	ClassDead       = model.ClassDead
)

Status classes. Unverified covers not-verified, unknown and rate-limited.

View Source
const (
	ConfidenceHigh   = model.ConfidenceHigh
	ConfidenceMedium = model.ConfidenceMedium
	ConfidenceLow    = model.ConfidenceLow
)

Confidence levels.

View Source
const (
	GradeA = model.GradeA
	GradeB = model.GradeB
	GradeC = model.GradeC
	GradeD = model.GradeD
	GradeF = model.GradeF
)

Grades, best to worst.

View Source
const (
	LocationFile     = model.LocationFile
	LocationStaged   = model.LocationStaged
	LocationCommit   = model.LocationCommit
	LocationImage    = model.LocationImage
	LocationArchive  = model.LocationArchive
	LocationNotebook = model.LocationNotebook
	LocationSurface  = model.LocationSurface
	LocationStdin    = model.LocationStdin
)

Location kinds.

View Source
const (
	TargetRepo    = model.TargetRepo
	TargetMachine = model.TargetMachine
	TargetImage   = model.TargetImage
	TargetOrgRepo = model.TargetOrgRepo
	TargetStdin   = model.TargetStdin
)

Target kinds.

View Source
const (
	VisibilityPublic  = model.VisibilityPublic
	VisibilityPrivate = model.VisibilityPrivate
	VisibilityUnknown = model.VisibilityUnknown
)

Visibilities.

View Source
const (
	// CodeFileUnreadable is a file that could not be opened or read.
	CodeFileUnreadable = model.CodeFileUnreadable
	// CodeInternalError is an error no other code describes.
	CodeInternalError = model.CodeInternalError
	// CodeReadFailed is a file, blob or stream that could not be read.
	CodeReadFailed = model.CodeReadFailed
	// CodeRegistryEntrySkipped is a registry file skipped while the rest loaded.
	CodeRegistryEntrySkipped = model.CodeRegistryEntrySkipped
	// CodeTimeout is a scan stopped by its timeout with partial results.
	CodeTimeout = model.CodeTimeout
	// CodeUntrustedConfigKey is a config value ignored because of its tier.
	CodeUntrustedConfigKey = model.CodeUntrustedConfigKey
	// CodeConfigPathOutsideRoot is a project config path outside the project root.
	CodeConfigPathOutsideRoot = model.CodeConfigPathOutsideRoot
	// CodeFileTooLarge is a file or stream over limits.max_file_bytes, skipped.
	CodeFileTooLarge = model.CodeFileTooLarge
	// CodeGitNotFound is a scan root inside a git repository that was walked without
	// git, so .gitignore was not applied.
	CodeGitNotFound = model.CodeGitNotFound
)

Warning codes. Every code is listed in docs/schema/report.v1.json.

View Source
const (
	// VerificationOn: keys were verified with read-only calls.
	VerificationOn = model.VerificationOn
	// VerificationOff: the run was offline and nothing was verified.
	VerificationOff = model.VerificationOff
)

Verification values of Meta.Verification.

View Source
const (
	// EventFindingDetected is sent the first time a credential is seen.
	EventFindingDetected = model.EventFindingDetected
	// EventLocationAdded is sent for every later sighting of a known credential.
	EventLocationAdded = model.EventLocationAdded
	// EventStatusUpdated is sent when verification changes a finding's status.
	EventStatusUpdated = model.EventStatusUpdated
)

Event kinds.

View Source
const SchemaVersion = model.SchemaVersion

SchemaVersion is the version of the JSON Report schema (docs/schema/report.v1.json) that this model marshals to.

Variables

View Source
var (
	// ErrNoSources: Options.Sources is empty.
	ErrNoSources = errors.New("tokenhound: no sources to scan")
	// ErrInvalidSource: a Source is the zero value, has no path or reader, or names a
	// path that cannot be scanned at all.
	ErrInvalidSource = errors.New("tokenhound: invalid source")
	// ErrRegistry: the embedded provider registry failed to load. It is a defect of the
	// build, not of the input.
	ErrRegistry = errors.New("tokenhound: registry failed to load")
	// ErrGitNotFound: a History or Staged source needs git and no git binary is on PATH.
	ErrGitNotFound = errors.New("tokenhound: git not found")
	// ErrNotGitRepo: the repository of a History or Staged source is not inside a git
	// work tree.
	ErrNotGitRepo = errors.New("tokenhound: not a git repository")
	// ErrInvalidRef: HistoryOptions.Since is not an acceptable ref or does not resolve
	// to a commit.
	ErrInvalidRef = errors.New("tokenhound: invalid ref")
)

Errors returned by Scan.

Functions

func WarningCodes

func WarningCodes() []string

WarningCodes returns every documented warning code, sorted.

Types

type AlertsOptions

type AlertsOptions struct {
	SlackWebhookEnv string
	TeamsWebhookEnv string
	WebhookURLEnv   string
	// OnStatuses are the statuses that trigger an alert.
	OnStatuses []Status
	// Timeout bounds one alert call.
	Timeout time.Duration
}

AlertsOptions configures alerts. The webhook URLs are read from the named environment variables when an alert is sent.

type Confidence

type Confidence = model.Confidence

Confidence is how sure detection is that a match is a real key.

type DetectorInfo

type DetectorInfo = model.DetectorInfo

DetectorInfo describes a detector referenced by a finding.

type DollarsMethod

type DollarsMethod = model.DollarsMethod

DollarsMethod lists the inputs behind a dollars-at-risk figure.

type Event

type Event = model.Event

Event is a scan progress event. It carries the redacted form of a key only.

type EventKind

type EventKind = model.EventKind

EventKind is the kind of a scan progress event.

type FailOn

type FailOn struct {
	// Statuses fail the run when an unsuppressed finding has one of them and its
	// dollars at risk per day (missing counts as 0) is at least MinDollarsAtRisk.
	Statuses []Status
	// MinDollarsAtRisk is the minimum dollars at risk per day of a failing finding.
	MinDollarsAtRisk float64
	// Warnings fail the run when the Report has a warning with one of these codes.
	Warnings []string
}

FailOn is the policy that makes a run fail (exit code 1 in the CLI).

type Finding

type Finding = model.Finding

Finding is one unique credential with every place it was seen.

type FirstSeen

type FirstSeen = model.FirstSeen

FirstSeen is the earliest commit that introduced a key.

type FixPlan

type FixPlan = model.FixPlan

FixPlan is the ordered list of steps to contain a finding.

type FixStep

type FixStep = model.FixStep

FixStep is one fix plan step.

type Grade

type Grade = model.Grade

Grade is an A to F exposure grade for a target or the whole report.

type GradeOptions

type GradeOptions struct {
	// FThresholdUSDPerDay is the live dollars at risk per day at which a target gets
	// grade F (default 500).
	FThresholdUSDPerDay float64
}

GradeOptions configures grading.

type HistoryOptions

type HistoryOptions struct {
	// Since limits the scan to commits reachable from HEAD but not from this ref (a
	// hex commit id, branch or tag). Empty scans every commit of every ref. An
	// invalid or unresolvable ref makes Scan return ErrInvalidRef.
	Since string
}

HistoryOptions configures History.

type HookOptions

type HookOptions struct {
	// Mode is "block" (default) or "warn".
	Mode string
	// OnError is "warn-allow" (default) or "block".
	OnError string
}

HookOptions configures the git hook.

type Limits

type Limits struct {
	// MaxFileBytes is the largest file or stream scanned; larger ones are skipped
	// with a file_too_large warning (default 10 MiB).
	MaxFileBytes int64
	// ArchiveMaxBytes bounds the expanded size of one archive (default 256 MiB).
	ArchiveMaxBytes int64
	// ArchiveMaxDepth bounds archive nesting (default 5).
	ArchiveMaxDepth int
	// ArchiveMaxEntries bounds the members of one archive (default 10000).
	ArchiveMaxEntries int
	// DecodeMaxDepth bounds nested decoding (default 3).
	DecodeMaxDepth int
}

Limits bound what one scan reads.

type Location

type Location = model.Location

Location is one place a finding was seen. It never carries file content.

type LocationKind

type LocationKind = model.LocationKind

LocationKind is where in a target a finding was seen.

type Meta

type Meta = model.Meta

Meta describes the run that produced a Report.

type NetworkOptions

type NetworkOptions struct {
	// HTTPSProxy is the proxy URL for HTTPS calls; empty means none (or the
	// environment when FromEnv is set).
	HTTPSProxy string
	// NoProxy lists hosts that bypass the proxy, comma separated.
	NoProxy string
	// CABundle holds extra PEM root certificates (the file's bytes, not its path).
	CABundle []byte
	// AllowHosts are extra hosts outgoing calls may reach.
	AllowHosts []string
	// FromEnv lets the network client read the standard proxy environment
	// variables. The library never reads them otherwise.
	FromEnv bool
}

NetworkOptions configures outgoing HTTPS calls.

type Options

type Options struct {
	// Sources lists what to scan, for example Path(".") and Stdin().
	Sources []Source
	// IncludeTestKeys keeps findings from generated test keys (those carrying the
	// TOKENHOUNDTEST marker) unsuppressed.
	IncludeTestKeys bool
	// Timeout stops the scan and returns partial results with a timeout warning per
	// incomplete source; 0 means no timeout.
	Timeout time.Duration
	// IncludeIgnored makes a Path source walk every file, including ones .gitignore
	// excludes. By default, inside a git work tree with git installed, a Path source
	// reads only what git would commit: tracked files plus untracked files that are not
	// ignored. Outside a work tree, and for a single file, it always reads everything.
	IncludeIgnored bool
	// Now pins Meta.GeneratedAt, and so the age_days of first_seen, when not zero.
	// The zero value means the wall clock (the Unix epoch under Deterministic).
	Now time.Time
	// Deterministic pins Meta.GeneratedAt to the Unix epoch and Meta.DurationMS to 0,
	// so the same input gives byte-identical Reports.
	Deterministic bool
	// ToolVersion is reported in Meta.ToolVersion ("dev" when empty).
	ToolVersion string

	// Verify configures verification.
	Verify VerifyOptions
	// FailOn is the policy that fails a run. Scan does not apply it; front doors do.
	FailOn FailOn
	// Grade configures grading.
	Grade GradeOptions
	// Limits bound what the scan reads.
	Limits Limits
	// Network configures outgoing HTTPS calls.
	Network NetworkOptions
	// Hook configures the git hook.
	Hook HookOptions
	// Alerts configures alerts.
	Alerts AlertsOptions
	// Ping allows the opt-in ping call.
	Ping bool
	// Warnings are added to the Report as they are (for example config warnings).
	Warnings []Warning
}

Options configures a scan.

type ProviderInfo

type ProviderInfo = model.ProviderInfo

ProviderInfo describes a provider referenced by a finding.

type Report

type Report = model.Report

Report is the canonical result of a scan.

type Results

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

Results is a running scan.

func Scan

func Scan(ctx context.Context, opts Options) (*Results, error)

Scan starts a scan of opts.Sources and returns at once. Read progress from Results.Events and the final Report from Results.Wait. The scan stops at opts.Timeout or when ctx is done and then returns partial results.

func (*Results) Events

func (r *Results) Events() <-chan Event

Events returns the progress events: finding-detected the first time a key is seen and location-added for every later sighting. Events carry the redacted key only. The channel closes after the final Report is built and every event was delivered. A caller may ignore events without blocking the scan.

func (*Results) Findings

func (r *Results) Findings(yield func(Finding) bool)

Findings yields the findings of the final Report in final order, waiting for the scan first. Use it as: for f := range results.Findings { ... }.

func (*Results) Progress

func (r *Results) Progress() (files, commits int)

Progress returns how many files and streams have reached detection so far and how many commits were scanned, for a progress display. It is safe to call while the scan runs.

func (*Results) Wait

func (r *Results) Wait() *Report

Wait blocks until the scan is done and returns the final Report, built once at the barrier. Every call returns the same Report.

type Source

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

Source is one thing to scan. Build it with Path, Stdin or Reader; the zero value is invalid.

func History

func History(repo string, opts HistoryOptions) Source

History scans the added lines of every commit of the git repository at repo (git log -p --all, or the range after opts.Since), with locations of kind commit that carry the commit, author name and UTC date. The target is the one Path(repo) reports. Scan returns ErrGitNotFound without git and ErrNotGitRepo outside a work tree. Findings get first_seen and age_days from their earliest commit.

func MachineSurfaces

func MachineSurfaces() Source

MachineSurfaces scans the files coding agents keep in the user's home directory: Claude Code, Codex and Cursor settings, MCP config, auth files and transcripts, shell histories (bash, zsh, fish, PowerShell), and the per-user .npmrc, .yarnrc and .pypirc. Locations have kind surface and the machine target; Report.SurfacesChecked lists each agent as found, not installed or unreadable. The home directory comes from the operating system (HOME, or USERPROFILE on Windows).

func Path

func Path(p string) Source

Path scans the directory p as a working tree, or the single file p. The walk skips .git, never follows symlinks inside the tree and reads plain files only (no archive expansion); p itself is followed if it is a symlink.

func ProjectSurfaces

func ProjectSurfaces(root string) Source

ProjectSurfaces scans the agent files below the directory root: .env files, project .npmrc, .yarnrc and .pypirc, and project agent config such as .cursor/mcp.json and .claude/settings.local.json. Files are opened only through root, so a symlink cannot leave it; .git and node_modules are skipped. The target is the one Path(root) reports, so a file that Path also reads (a .env) gives one location, of kind surface. A root that is the home directory is skipped: MachineSurfaces reads it.

func Reader

func Reader(name string, r io.Reader) Source

Reader scans the stream r, reported under name (path "-" when name is empty) with target stdin.

func Staged

func Staged(repo string) Source

Staged scans the added lines of the staged changes (the index against HEAD) of the git repository at repo, with locations of kind staged. repo is a directory inside a git work tree; its target is the one Path(repo) reports, so the locations merge. Scan returns ErrGitNotFound without git and ErrNotGitRepo outside a work tree.

func Stdin

func Stdin() Source

Stdin scans standard input. Its locations have path "-".

func (Source) String

func (s Source) String() string

String returns the source's display name.

type Status

type Status = model.Status

Status is the verification status of a finding.

type StatusClass

type StatusClass = model.StatusClass

StatusClass groups statuses for ranking, grading and fail_on.

type SurfaceStatus

type SurfaceStatus = model.SurfaceStatus

SurfaceStatus is whether one agent surface was found, not installed or unreadable.

type Target

type Target = model.Target

Target is one scanned thing: a repo, this machine, an image, an org repo or stdin.

type TargetGrade

type TargetGrade = model.TargetGrade

TargetGrade is the grade of one target with the reasons that set it.

type TargetKind

type TargetKind = model.TargetKind

TargetKind is the kind of thing a scan target is.

type Timestamp

type Timestamp = model.Timestamp

Timestamp is a point in time that marshals as RFC 3339 in UTC.

type USD

type USD = model.USD

USD is an amount in US dollars that marshals with exactly two decimals.

type VerifyEvidence

type VerifyEvidence = model.VerifyEvidence

VerifyEvidence is what a live verification response revealed.

type VerifyOptions

type VerifyOptions struct {
	// Disabled turns verification off (offline): every finding is not-verified.
	Disabled bool
	// MaxConcurrency caps concurrent verification calls per run (default 8).
	MaxConcurrency int
	// Timeout bounds one verification call (default 10s).
	Timeout time.Duration
}

VerifyOptions configures key verification.

type Visibility

type Visibility = model.Visibility

Visibility is whether a target is publicly readable.

type Warning

type Warning = model.Warning

Warning is a non-fatal problem: a documented code, a location and a detail code.

Directories

Path Synopsis
cmd
tokenhound command
Command tokenhound finds leaked AI keys before attackers do.
Command tokenhound finds leaked AI keys before attackers do.
Package config resolves configuration once, with precedence flags, then TOKENHOUND_* environment, then user config, then project tokenhound.yaml, then defaults, into tokenhound.Options.
Package config resolves configuration once, with precedence flags, then TOKENHOUND_* environment, then user config, then project tokenhound.yaml, then defaults, into tokenhound.Options.
docs
schema
Package schema embeds the published JSON Schemas: the Report (report.v1.json) and the tokenhound.yaml config (config.v1.json).
Package schema embeds the published JSON Schemas: the Report (report.v1.json) and the tokenhound.yaml config (config.v1.json).
internal
candidate
Package candidate defines the stage envelopes: Chunk, which carries content from source through decode to detect, and Candidate, which detect hands on toward verify with a Finding, its secret.Secret key material and the precomputed suppression context.
Package candidate defines the stage envelopes: Chunk, which carries content from source through decode to detect, and Candidate, which detect hands on toward verify with a Finding, its secret.Secret key material and the precomputed suppression context.
cli
Package cli is the command line front door: it defines the Cobra commands, maps results to exit codes and carries the build version, commit and date injected by ldflags.
Package cli is the command line front door: it defines the Cobra commands, maps results to exit codes and carries the build version, commit and date injected by ldflags.
config
Package config resolves TokenHound configuration once per run.
Package config resolves TokenHound configuration once per run.
decode
Package decode is the second pipeline stage: it decodes base64, URL, JSON-escaped and env-file encodings and expands archives in memory within configured size, depth and entry limits.
Package decode is the second pipeline stage: it decodes base64, URL, JSON-escaped and env-file encodings and expands archives in memory within configured size, depth and entry limits.
detect
Package detect is the third pipeline stage: it matches registry patterns, entropy and keyword context, computes the fingerprint id and confidence, and emits candidate.Candidate envelopes.
Package detect is the third pipeline stage: it matches registry patterns, entropy and keyword context, computes the fingerprint id and confidence, and emits candidate.Candidate envelopes.
engine
Package engine wires the scan pipeline: it connects the stages (source, decode, detect, suppress, verify, enrich, grade, fixplan) over bounded channels, runs the worker pools and the single barrier after enrich, applies timeouts and sorts findings once.
Package engine wires the scan pipeline: it connects the stages (source, decode, detect, suppress, verify, enrich, grade, fixplan) over bounded channels, runs the worker pools and the single barrier after enrich, applies timeouts and sorts findings once.
enrich
Package enrich is the sixth pipeline stage: it derives tier, scopes, org, first_seen, age and dollars at risk per day from verify evidence and the spend registry.
Package enrich is the sixth pipeline stage: it derives tier, scopes, org, first_seen, age and dollars at risk per day from verify evidence and the spend registry.
fixplan
Package fixplan runs once after the engine barrier: it builds the fix plan for each finding (rotate, purge and prevent steps).
Package fixplan runs once after the engine barrier: it builds the fix plan for each finding (rotate, purge and prevent steps).
gitx
Package gitx is the only package that runs the system git binary, with argument slices, validated refs and hardened flags and environment.
Package gitx is the only package that runs the system git binary, with argument slices, validated refs and hardened flags and environment.
gitx/gitxtest
Package gitxtest builds throwaway git repositories for tests.
Package gitxtest builds throwaway git repositories for tests.
grade
Package grade runs once after the engine barrier: it computes the A to F grade per target and overall, with the reasons for each grade.
Package grade runs once after the engine barrier: it computes the A to F grade per target and overall, with the reasons for each grade.
lintcheck
Package lintcheck owns the lint self-test fixtures under testdata.
Package lintcheck owns the lint self-test fixtures under testdata.
netx
Package netx is the only package that builds HTTP clients and transports: HTTPS only, a closed purpose enum, registry-declared hosts for verification, no redirects for verify, proxy and custom CA support.
Package netx is the only package that builds HTTP clients and transports: HTTPS only, a closed purpose enum, registry-declared hosts for verification, no redirects for verify, proxy and custom CA support.
netx/netxtest
Package netxtest holds loopback test wiring for code that talks through internal/netx: a throwaway certificate authority, TLS test servers whose leaf certificates name any host, and a CONNECT-only proxy.
Package netxtest holds loopback test wiring for code that talks through internal/netx: a throwaway certificate authority, TLS test servers whose leaf certificates name any host, and a CONNECT-only proxy.
ownership
Package ownership is a test helper for AD-2 field ownership: each Finding field is set only by its owning stage.
Package ownership is a test helper for AD-2 field ownership: each Finding field is set only by its owning stage.
registry
Package registry loads and validates the provider, surface and spend registries (YAML validated by JSON Schema) from the embedded snapshot or a refreshed copy.
Package registry loads and validates the provider, surface and spend registries (YAML validated by JSON Schema) from the embedded snapshot or a refreshed copy.
secret
Package secret holds credential material in an opaque Secret type whose formatting and marshalling methods return only the redacted form.
Package secret holds credential material in an opaque Secret type whose formatting and marshalling methods return only the redacted form.
source
Package source is the first pipeline stage: adapters read files, staged changes, git history, images, notebooks, agent surfaces, stdin and forge orgs, and emit content chunks with their Location.
Package source is the first pipeline stage: adapters read files, staged changes, git history, images, notebooks, agent surfaces, stdin and forge orgs, and emit content chunks with their Location.
source/fs
Package fs is the working tree source adapter ("fs"): it walks a directory, or reads one file, and emits each regular file as one chunk.
Package fs is the working tree source adapter ("fs"): it walks a directory, or reads one file, and emits each regular file as one chunk.
source/git
Package git holds the git source adapters.
Package git holds the git source adapters.
source/stdin
Package stdin is the stream source adapter ("stdin"): it reads one stream, such as standard input, whole and emits it as one chunk with Location kind stdin and target {stdin, stdin, unknown}.
Package stdin is the stream source adapter ("stdin"): it reads one stream, such as standard input, whole and emits it as one chunk with Location kind stdin and target {stdin, stdin, unknown}.
source/surface
Package surface is the agent surface source adapter ("surface"): it reads the files coding agents keep on disk (settings, allowlists, MCP config, transcripts) as the registry describes them, parses each with the format's structure-aware parser and emits one chunk per extracted entry with a Location of kind surface (surface id, path, field) so that credentials in one entry pair under same-surface-entry.
Package surface is the agent surface source adapter ("surface"): it reads the files coding agents keep on disk (settings, allowlists, MCP config, transcripts) as the registry describes them, parses each with the format's structure-aware parser and emits one chunk per extracted entry with a Location of kind surface (surface id, path, field) so that credentials in one entry pair under same-surface-entry.
source/surface/parse
Package parse reads the file formats of agent surfaces (json, jsonc, jsonl, toml, yaml, ini, dotenv, shell-history and ipynb) into a small tree that keeps the 1-based source line of every value, and selects string values from it with field selectors.
Package parse reads the file formats of agent surfaces (json, jsonc, jsonl, toml, yaml, ini, dotenv, shell-history and ipynb) into a small tree that keeps the 1-based source line of every value, and selects string values from it with field selectors.
stagereg
Package stagereg is the adapter registry every pipeline stage package uses: adapters register a factory under a name at init(), and the engine looks factories up by name.
Package stagereg is the adapter registry every pipeline stage package uses: adapters register a factory under a name at init(), and the engine looks factories up by name.
suppress
Package suppress is the fourth pipeline stage: it alone decides whether a candidate is suppressed (test keys, inline allows, allowlists, ignore files, baselines) and records the reason.
Package suppress is the fourth pipeline stage: it alone decides whether a candidate is suppressed (test keys, inline allows, allowlists, ignore files, baselines) and records the reason.
verify
Package verify is the fifth pipeline stage: it checks keys with read-only, registry-declared requests through netx and sets status, status_reason and verify_evidence.
Package verify is the fifth pipeline stage: it checks keys with read-only, registry-declared requests through netx and sets status, status_reason and verify_evidence.
warnx
Package warnx builds report warnings from errors as {code, location, detail_code}, so foreign error text never reaches warnings, logs or MCP output.
Package warnx builds report warnings from errors as {code, location, detail_code}, so foreign error text never reaches warnings, logs or MCP output.
yamlschema
Package yamlschema parses single-document YAML files and validates them against a JSON Schema, reporting every problem as "file:line: field: message".
Package yamlschema parses single-document YAML files and validates them against a JSON Schema, reporting every problem as "file:line: field: message".
Package model is the TokenHound Finding and Report model: statuses and their classes, confidence, grades, targets, locations, warnings, progress events and the canonical JSON Report (docs/schema/report.v1.json).
Package model is the TokenHound Finding and Report model: statuses and their classes, confidence, grades, targets, locations, warnings, progress events and the canonical JSON Report (docs/schema/report.v1.json).
Package registry embeds the TokenHound registry data: the snapshot manifest, the JSON Schemas and the provider, spend and surface YAML files.
Package registry embeds the TokenHound registry data: the snapshot manifest, the JSON Schemas and the provider, spend and surface YAML files.
Package report renders a tokenhound.Report.
Package report renders a tokenhound.Report.
tools
covercore command
Command covercore runs `go test -cover` on the core packages, prints a per-package coverage table and exits 1 when any package is below the minimum, naming it.
Command covercore runs `go test -cover` on the core packages, prints a per-package coverage table and exits 1 when any package is below the minimum, naming it.
dashlint command
Command dashlint fails on em dash, en dash and ellipsis characters in tracked text files.
Command dashlint fails on em dash, en dash and ellipsis characters in tracked text files.
errtextlint command
Command errtextlint enforces the AD-3 text hygiene rule that forbidigo cannot see: outside internal/warnx and _test.go files, an error value must not be passed to a fmt print function (Sprint*, Print*, Fprint*, Append*) or to any log or log/slog function, method or attribute constructor.
Command errtextlint enforces the AD-3 text hygiene rule that forbidigo cannot see: outside internal/warnx and _test.go files, an error value must not be passed to a fmt print function (Sprint*, Print*, Fprint*, Append*) or to any log or log/slog function, method or attribute constructor.
registryids command
Command registryids is the registry id stability check (AD-4).
Command registryids is the registry id stability check (AD-4).
selfscan command
Command selfscan checks a TokenHound JSON Report for unsuppressed findings, so the CI self-scan needs no jq (AD-16).
Command selfscan checks a TokenHound JSON Report for unsuppressed findings, so the CI self-scan needs no jq (AD-16).
testkeys command
Command testkeys prints synthetic test keys generated from the embedded registry.
Command testkeys prints synthetic test keys generated from the embedded registry.
testkeys/keygen
Package keygen generates synthetic test keys from registry patterns (AD-16).
Package keygen generates synthetic test keys from registry patterns (AD-16).

Jump to

Keyboard shortcuts

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