tokenhound

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 15 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 scan --format gha           # GitHub Actions annotations on stdout, summary on stderr
tokenhound report --from r.json        # re-render a saved Report: ./tokenhound.json, no scan, no network
tokenhound report --from r.json --format terminal   # the summary of a saved Report
tokenhound report --format json,terminal -o reports # scan . and route like scan
tokenhound fix th_3f9a0c1d2e4b5a69     # the fix plan of one finding (re-scans .; add a path or scan flags)
tokenhound fix <id> --from r.json      # the fix plan from a saved JSON Report, no scan, no network
tokenhound fix <id> --open             # also open the revoke page in your browser
tokenhound baseline                    # record today's findings in .tokenhound-baseline.json
tokenhound scan --new-only             # fail only on findings that are not in the baseline
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.

Output routing is the same for scan, agents, report and the bare command. One --format goes to stdout, or to the -o file. Several (--format json,terminal) need -o <dir>; each is written there under its file name and terminal goes to stdout. When stdout carries no terminal summary, the summary goes to stderr unless --quiet. Written files have mode 0600. A binary format alone needs -o or a redirect when stdout is a terminal.

Format File under -o <dir>
terminal stdout
json tokenhound.json
sarif tokenhound.sarif
gha tokenhound.gha.txt
card tokenhound.png (binary PNG)
badge tokenhound.svg

A card also prints Alt text: ... and an <img> snippet on stderr, and scan and report take --card-label <text> for its caption. The other formats arrive with their stories; until then they exit 2 with format <name> is not available in this version. --format takes the closed list terminal, json, csv, junit, sarif, gha, gitlab, html, card, badge, slack, teams, webhook; any other name exits 2.

tokenhound report [path|-] renders a Report in any of these formats. With --from <file> (- for standard input) it re-renders a saved JSON Report, validated against the schema, with no scan and no network call; otherwise it scans path with the same flags as scan. Without --format it writes the JSON Report to -o (default ./tokenhound.json) and prints Wrote <file>. It exits 0 or 1 by fail_on on the Report and 2 for a usage error or an unreadable, invalid or newer --from file.

The terminal summary opens with a meta line, then, after a blank line and indented two spaces, one headline sentence such as 2 live keys, $3,100 a day at risk, grade D, then ranked rows (status word LIVE, DEAD, UNKNOWN, RATE-LTD or UNVER, provider, redacted key, dollars right-aligned, first location), the reasons for the grade (Why D:) and exactly one Next: line naming one command to run: tokenhound fix <id> for the first live key, the same scan again (without --no-verify; a plain tokenhound scan for report --from) when keys are unverified, tokenhound fix <id> for a dead key (preferring one still in history), and tokenhound hook install when the scan is clean. Counts and dollars use thousands separators. 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, from COLUMNS or the terminal size) stacks each row as key: value lines without indentation. 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).

--format gha prints one GitHub Actions workflow command per location of every finding that is not suppressed, so the leak shows on the pull request line: ::error for a live key, ::warning for an unverified high-confidence key and ::notice otherwise, with file, line and col for files and staged changes, a title such as Live OpenAI key ($2,880/day at risk) and the redacted key plus the first fix step as the message (history, image, surface, archive, notebook and stdin locations are named in the message instead). With no findings it prints nothing. When GITHUB_ACTIONS=true and the terminal summary goes to stdout, the summary is printed in --plain style and the same annotations follow it on stdout (also with --quiet), so a plain tokenhound scan step annotates the pull request.

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.

tokenhound fix <id> [path|-] prints one finding's fix plan: a header (status word as in the summary, provider, redacted key, dollars per day), a How: line showing the dollars arithmetic, and the numbered steps (revoke, replace, purge, check usage, ScopeKeeper) with each command on its own line, ready to paste. The finding comes from a saved Report (--from r.json, - for standard input; validated against the report schema) or from a new scan of path with the same scan flags, which writes nothing. --format json prints {schema_version, id, provider, status, redacted, fix_plan}. TokenHound never revokes a key and never contacts a revoke page: --open only hands the https revoke URL to your OS browser. fix exits 0 when the plan was printed and 2 for a bad or unknown id or an unreadable, invalid or newer --from file.

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, ignore or baseline file, 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 (schema version 1), and every Report golden and end-to-end JSON output in this repository is validated against it.

Silence false positives and accepted findings with a .tokenhound-ignore file at the scan root (or the file ignore_file names) and inline tokenhound:allow comments on the match line or the line above it. Rules are path:<glob>, loc:<path>:<line>, id:th_<16 hex> and detector:<id>; <user config dir>/tokenhound/ignore holds rules for machine locations. id: and detector: suppress the whole finding; path:, loc: and inline markers suppress it only when every location is covered, so a key also present in an unignored file stays active. Suppressed findings are never verified, sort last, are left out of the grade and fail_on, and the terminal shows them as one <n> suppressed (see --format json) line. A malformed rule or a missing configured ignore file exits 2. See docs/schema/ignore.v1.md.

Roll out on an existing repository without red CI on day one: tokenhound baseline [path] scans like scan (keys are not verified, fail_on is not applied, any existing baseline is never read) and writes every unsuppressed finding to .tokenhound-baseline.json at the scan root, or to the baseline config path. The file follows docs/schema/baseline.v1.json: {schema_version: 1, tool_version, registry_snapshot, findings[{id, provider, detector, redacted}]} sorted by id, with no status, locations or timestamps, so an unchanged repository gives a byte-identical file. It prints Wrote 12 findings to .tokenhound-baseline.json (--format json: {"path": ..., "count": ...}). Commit it. Every later scan sets new_vs_baseline on unsuppressed findings (false when the id is in the baseline); baselined findings are still verified, graded and shown. scan --new-only (or new_only: true in the user file, or TOKENHOUND_NEW_ONLY) leaves them out of fail_on, and the terminal adds 12 baselined findings not counted for failure (--new-only). Without a baseline file every finding counts and a baseline_missing warning is added (it fails the run only when listed in fail_on.warnings). An invalid baseline, or one with a newer schema_version, exits 2 with <file>: <field>: <message>. A project tokenhound.yaml cannot set new_only: true (it would loosen the gate).

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; also spelled --project-config) replaces it, and relative paths inside it resolve against the scan root;
  5. defaults.

On scan, report and the bare command, --ignore-file <file> and --baseline <file> (relative to the working directory) replace the project ignore file and the baseline file. CI passes the base branch copies of all three files this way (the GitHub Action does), so a pull request cannot silence its own leak.

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 }
new_only: false                   # true: baselined findings do not fail; not from tokenhound.yaml
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, ignore_file, baseline, new_only and limits.max_file_bytes change what a scan does today. verify, grade, network, hook, alerts, ping, 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
TOKENHOUND_NEW_ONLY new_only (true, false, 1, 0)

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 new_only: true or 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 cover-library    # fails if the public Go library 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 Source constructors (Path, Staged, History, Since, AgentSurfaces, MachineSurfaces, ProjectSurfaces, Stdin, Reader), FixPlan, the Finding and Report model, the progress Event types and the sentinel errors. The CLI and every other front door call this package and never import the engine or the pipeline stages directly.

A scan streams progress on Results.Events (finding-detected, location-added and status-updated; progress, never final) and ends at a single barrier: Results.Wait returns the final sorted Report and Results.Findings ranges over its findings. No type of this package holds key material; findings and events carry only the redacted form, for example "sk-pro...a1b2 (51)".

The library reads no config file and no environment variable on its own (the config package resolves tokenhound.yaml, user config and TOKENHOUND_* variables into Options), and it makes network calls only to verify keys, through Options.Network.

Experimental: the Go API may change in a minor release until the library gets a semver guarantee. The stable v1.0 contracts are the CLI verbs, flags and exit codes and the JSON Report (schema_version 1). See docs/library.md.

Example (Scan)

Example_scan scans this machine's agent surfaces and the working directory, verifies every key found and prints the first fix step of each finding.

package main

import (
	"context"
	"fmt"

	"github.com/aiagentpro/tokenhound"
)

// exampleNetwork routes verification to the loopback server (set by TestMain).
var exampleNetwork tokenhound.NetworkOptions

func main() {
	results, err := tokenhound.Scan(context.Background(), tokenhound.Options{
		Sources: []tokenhound.Source{tokenhound.AgentSurfaces(), tokenhound.Path(".")},
		// The fixture holds generated test keys, which are suppressed by default.
		IncludeTestKeys: true,
		// Verification goes to a loopback server here; omit Network in real use.
		Network: exampleNetwork,
		// Byte-identical Reports for the same input.
		Deterministic: true,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	for f := range results.Findings {
		plan := tokenhound.FixPlan(f)
		fmt.Println(f.Provider, f.Status, *f.DollarsAtRiskPerDay, plan.Steps[0].Title)
	}
}
Output:
openai live 28800 Revoke the key
openai live 28800 Revoke the key

Index

Examples

Constants

View Source
const (
	IgnorePath     = model.IgnorePath
	IgnoreID       = model.IgnoreID
	IgnoreDetector = model.IgnoreDetector
	IgnoreLoc      = model.IgnoreLoc
)

Ignore rule kinds.

View Source
const (
	IgnoreScopeProject = model.IgnoreScopeProject
	IgnoreScopeMachine = model.IgnoreScopeMachine
)

Ignore scopes.

View Source
const (
	ReasonIgnoreID          = model.ReasonIgnoreID
	ReasonIgnoreDetector    = model.ReasonIgnoreDetector
	ReasonIgnorePath        = model.ReasonIgnorePath
	ReasonIgnoreLoc         = model.ReasonIgnoreLoc
	ReasonInlineAllow       = model.ReasonInlineAllow
	ReasonTestMarker        = model.ReasonTestMarker
	ReasonImportedAllowlist = model.ReasonImportedAllowlist
)

Suppression reasons of Finding.SuppressionReason, in precedence order.

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

Surface statuses of Report.SurfacesChecked.

View Source
const (
	FixRevoke      = model.FixRevoke
	FixReplace     = model.FixReplace
	FixPurge       = model.FixPurge
	FixCheckUsage  = model.FixCheckUsage
	FixScopeKeeper = model.FixScopeKeeper
)

Fix step kinds, in plan order.

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
	// CodeBaselineMissing is a run with new_only on and no baseline file; every
	// finding then counts for fail_on.
	CodeBaselineMissing = model.CodeBaselineMissing
)

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. It is
	// progress, never final: the finding may still be suppressed or merged.
	EventFindingDetected = model.EventFindingDetected
	// EventLocationAdded is sent for every later sighting of a known credential. It
	// is progress, never final.
	EventLocationAdded = model.EventLocationAdded
	// EventStatusUpdated is sent when verification changes a finding's status. It is
	// progress, never final.
	EventStatusUpdated = model.EventStatusUpdated
)

Event kinds: the only three kinds Results.Events sends. Every event is progress, never final; the final result is the Report that Results.Wait returns.

View Source
const BaselineSchemaVersion = model.BaselineSchemaVersion

BaselineSchemaVersion is the version of the baseline file schema (docs/schema/baseline.v1.json) this model reads and writes.

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 (
	// ErrInvalidOptions: the Options cannot be used. Scan checks them before it starts
	// any work; the error also matches the specific sentinel below when there is one
	// (ErrNoSources, ErrInvalidSource, ErrInvalidIgnoreRule, ErrInvalidBaseline).
	ErrInvalidOptions = errors.New("tokenhound: invalid options")
	// 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 or HistoryOptions.Until is not an acceptable
	// ref or does not resolve to a commit.
	ErrInvalidRef = errors.New("tokenhound: invalid ref")
	// ErrInvalidIgnoreRule: an Options.Ignore rule is invalid. The error names the
	// rule's index, never its value.
	ErrInvalidIgnoreRule = errors.New("tokenhound: invalid ignore rule")
	// ErrInvalidBaseline: Options.Baseline has a SchemaVersion newer than
	// BaselineSchemaVersion or a finding id that is not th_ plus 16 lowercase hex
	// characters. The error names the finding's index, never its value.
	ErrInvalidBaseline = errors.New("tokenhound: invalid baseline")
)

Errors returned by Scan. Every error caused by the Options themselves (no sources, an invalid Source, a negative duration or limit, an invalid ignore rule or baseline) also matches ErrInvalidOptions with errors.Is, besides its specific sentinel. Error messages name the offending field or index, never a value.

Functions

func SuppressionReasons added in v0.2.0

func SuppressionReasons() []string

SuppressionReasons returns every suppression reason in precedence order.

func WarningCodes

func WarningCodes() []string

WarningCodes returns every documented warning code, sorted.

Types

type AlertsOptions

type AlertsOptions struct {
	// SlackWebhookEnv names the environment variable holding the Slack webhook URL.
	SlackWebhookEnv string
	// TeamsWebhookEnv names the environment variable holding the Teams webhook URL.
	TeamsWebhookEnv string
	// WebhookURLEnv names the environment variable holding a generic webhook URL.
	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 Baseline added in v0.2.0

type Baseline = model.Baseline

Baseline is an accepted set of findings (docs/schema/baseline.v1.json).

type BaselineFinding added in v0.2.0

type BaselineFinding = model.BaselineFinding

BaselineFinding is one accepted finding of a Baseline.

type Confidence

type Confidence = model.Confidence

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

type CredentialPart added in v0.2.0

type CredentialPart = model.CredentialPart

CredentialPart is the redacted form of one part of a multi-part credential.

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 sent on Results.Events. It is progress, never final, and carries the redacted form of a key only.

type EventKind

type EventKind = model.EventKind

EventKind is the kind of a scan progress event: EventFindingDetected, EventLocationAdded or EventStatusUpdated.

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
	// NewOnly (--new-only, user-tier new_only) leaves findings in the baseline out of
	// Statuses and MinDollarsAtRisk: a finding whose NewVsBaseline is false never
	// fails the run. Findings without the field (no baseline loaded) still count.
	NewOnly bool
}

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 FixKind added in v0.2.0

type FixKind = model.FixKind

FixKind is the kind of a fix plan step.

type FixPlanResult added in v0.2.0

type FixPlanResult = model.FixPlan

FixPlanResult is the ordered list of steps to contain a finding (model.FixPlan), as FixPlan returns it.

func FixPlan

func FixPlan(f Finding) FixPlanResult

FixPlan returns the fix plan of f: f.FixPlan when it is set (every finding of a Report has one), else the plan the scan would have built, from the embedded registry. Both paths give identical plans for the same finding. It returns an empty plan only when the embedded registry fails to load. It never makes a network call and never reads key material.

Example

ExampleFixPlan prints the fix plan of a finding built by hand. FixPlan uses the embedded registry and makes no network call.

package main

import (
	"fmt"

	"github.com/aiagentpro/tokenhound"
)

func main() {
	f := tokenhound.Finding{
		ID:       "th_0123456789abcdef",
		Provider: "openai",
		Detector: "openai-project-key",
		Redacted: "sk-pro...a1b2 (51)",
		Status:   tokenhound.StatusLive,
		Locations: []tokenhound.Location{{
			Target: tokenhound.Target{Kind: tokenhound.TargetRepo, ID: "example"},
			Kind:   tokenhound.LocationFile, Path: ".env", Line: 1,
		}},
	}
	for _, step := range tokenhound.FixPlan(f).Steps {
		fmt.Println(step.N, step.Kind, step.Title)
	}
}
Output:
1 revoke Revoke the key
2 replace Replace the key everywhere it is used
3 check_usage Check usage for abuse
4 scopekeeper Replace the raw key with a ScopeKeeper credential

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 Until (HEAD when empty) but not
	// from this ref (a hex commit id, branch or tag). Empty scans every commit of
	// every ref, unless Until or ExcludeRemotes is set. An invalid or unresolvable ref
	// makes Scan return ErrInvalidRef.
	Since string
	// Until is the tip commit the scan ends at (a hex commit id, branch or tag).
	// Empty means HEAD, or every ref when Since is empty and ExcludeRemotes is false.
	// With an empty Since it scans every ancestor of Until. An invalid or
	// unresolvable ref makes Scan return ErrInvalidRef.
	Until string
	// ExcludeRemotes also leaves out every commit reachable from a remote-tracking
	// ref (refs/remotes/*). With an empty Since it scans the commits of Until (HEAD
	// when empty) that no remote-tracking ref has, instead of every ref: the commits
	// a push of a new branch would add.
	ExcludeRemotes bool
}

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
	// SessionScan is hook.session_scan: the Claude Code SessionEnd hook scans the
	// session's Claude Code files. The config package sets it true unless the user
	// config turns it off; Scan does not read it.
	SessionScan bool
}

HookOptions configures the git hook.

type IgnoreKind added in v0.2.0

type IgnoreKind = model.IgnoreKind

IgnoreKind is the kind of an ignore rule.

type IgnoreRule added in v0.2.0

type IgnoreRule = model.IgnoreRule

IgnoreRule is one parsed ignore rule (docs/schema/ignore.v1.md).

type IgnoreScope added in v0.2.0

type IgnoreScope = model.IgnoreScope

IgnoreScope says which locations the path and loc rules of an ignore file match.

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
	// Ignore holds the ignore rules (docs/schema/ignore.v1.md) the suppress stage
	// applies. The config package parses ignore files into it; a library caller may
	// build rules itself. Scan returns ErrInvalidIgnoreRule for a rule with an unknown
	// kind or scope, a malformed id, an empty or whitespace detector, an invalid or
	// absolute glob, or a loc rule without a positive line.
	Ignore []IgnoreRule
	// NoInlineAllow makes inline tokenhound:allow markers suppress nothing. Ignore
	// rules, the baseline and the test marker still apply. Agent hooks set it, so
	// content an agent proposes cannot allow its own key.
	NoInlineAllow bool
	// Baseline is the accepted set of findings (docs/schema/baseline.v1.json). When
	// set, the suppress stage sets NewVsBaseline on every unsuppressed finding: false
	// when its final id is in the baseline, true otherwise. Nil leaves the field
	// absent. The config package reads the baseline file into it; a library caller
	// may build one. Scan returns ErrInvalidBaseline for a SchemaVersion above
	// BaselineSchemaVersion or a malformed id.
	Baseline *Baseline
}

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, returned by Scan. Its methods are safe for concurrent use.

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; Wait then returns the partial Report with a timeout warning per incomplete source, and no error is returned for it.

Scan checks opts before it starts any work. Invalid options return nil Results and an error matching ErrInvalidOptions (and the specific sentinel, if any). Scan reads no config file and no environment variable; the network is used only for verification, configured by opts.Network.

func (*Results) Events

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

Events returns the progress event channel. Only three kinds are sent: EventFindingDetected the first time a credential is seen, EventLocationAdded for every later sighting and EventStatusUpdated when verification changes a status. Events are progress, never final: a finding may still be suppressed, merged or re-ranked before the barrier, so read results from Wait or Findings. Events carry the redacted key only, never key material.

The first call starts delivery; every call returns the same channel. It closes after the final Report is built and every queued event was delivered. Events are queued without bound, so a caller that never calls Events, or stops receiving, never blocks or slows the scan.

Example

ExampleResults_Events prints progress while a scan runs, then the final count. Events are progress, never final, and carry only the redacted key.

package main

import (
	"context"
	"fmt"

	"github.com/aiagentpro/tokenhound"
)

func main() {
	results, err := tokenhound.Scan(context.Background(), tokenhound.Options{
		Sources:         []tokenhound.Source{tokenhound.Path(".")},
		IncludeTestKeys: true,
		Verify:          tokenhound.VerifyOptions{Disabled: true},
		Deterministic:   true,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	for e := range results.Events() {
		fmt.Println(e.Kind, e.Provider, e.Redacted)
	}
	fmt.Println(len(results.Wait().Findings), "finding")
}
Output:
finding-detected openai sk-pro...TEST (56)
1 finding

func (*Results) Findings

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

Findings yields the findings of the final Report in final order. It waits for the barrier (Wait) first, so it never yields a provisional finding. The method value results.Findings is an iter.Seq[Finding]: 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 after every source, verification and enrichment finished (or the scan stopped). Findings are in final sorted order. Every call returns the same Report; treat it as read-only. It never blocks on unread events.

Example

ExampleResults_Wait reads the final Report of a scan of a stream, with verification off.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/aiagentpro/tokenhound"
	"github.com/aiagentpro/tokenhound/internal/registry"
	"github.com/aiagentpro/tokenhound/tools/testkeys/keygen"
)

func main() {
	reg, _, err := registry.Default()
	if err != nil {
		fmt.Println(err)
		return
	}
	key, err := keygen.Key(reg, "anthropic", 7)
	if err != nil {
		fmt.Println(err)
		return
	}
	results, err := tokenhound.Scan(context.Background(), tokenhound.Options{
		Sources:         []tokenhound.Source{tokenhound.Reader("prompt.txt", strings.NewReader("ANTHROPIC_API_KEY="+key))},
		IncludeTestKeys: true,
		Verify:          tokenhound.VerifyOptions{Disabled: true},
		Deterministic:   true,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	report := results.Wait()
	for _, f := range report.Findings {
		fmt.Println(f.Provider, f.Status, f.StatusReason, f.Redacted, f.Locations[0].Path)
	}
	fmt.Println(report.Meta.Verification)
}
Output:
anthropic not-verified verification_off sk-ant...BTAA (108) prompt.txt
off

type Source

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

Source is one thing to scan. Build it with Path, Staged, History, Since, AgentSurfaces, MachineSurfaces, ProjectSurfaces, SurfaceFiles, Stdin or Reader; the zero value is invalid.

func AgentSurfaces added in v0.3.0

func AgentSurfaces() Source

AgentSurfaces scans the machine-wide agent surfaces in the user's home directory: the same Source as MachineSurfaces, under the name the library documentation uses.

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 opts.Since, opts.Until and opts.ExcludeRemotes select), 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 Since added in v0.3.0

func Since(repo, ref string) Source

Since scans the added lines of the commits reachable from HEAD but not from ref in the git repository at repo: the same Source as History(repo, HistoryOptions{Since: ref}). An empty ref, as in History, means every commit of every ref. Scan returns ErrInvalidRef when ref is not acceptable or does not resolve to a commit.

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 SurfaceFiles added in v0.3.0

func SurfaceFiles(surface string, files ...string) Source

SurfaceFiles scans exactly the given files, and nothing else, with the parse format and field selectors of the registry surface whose id is surface (for example "claude-code" or "claude-code-transcripts"). No directory is walked and no pattern is expanded. Locations have kind surface, the machine target and the file's absolute path with forward slashes. A file that does not exist is skipped silently; one that is not a regular file (a symlink is never followed) gives a file_unreadable warning. A jsonl file larger than Limits.MaxFileBytes is skipped with a file_too_large warning. Scan returns an error matching ErrInvalidOptions for an unknown surface id or a source without files.

func (Source) String

func (s Source) String() string

String returns the source's display name.

func (Source) WithTargetID added in v0.3.0

func (s Source) WithTargetID(id string) Source

WithTargetID returns a copy of the Reader source s whose findings are reported under a stdin target with this id instead of "stdin", for example "hook:claude-code". Other sources are returned unchanged.

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
	// Deadline bounds all verification, measured from the start of the scan; 0
	// means none. A finding whose verification has not finished by then is reported
	// unknown with status_reason deadline instead of being dropped.
	Deadline 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), the tokenhound.yaml config (config.v1.json) and the baseline file (baseline.v1.json).
Package schema embeds the published JSON Schemas: the Report (report.v1.json), the tokenhound.yaml config (config.v1.json) and the baseline file (baseline.v1.json).
internal
agenthook
Package agenthook installs and uninstalls TokenHound's coding agent hooks in the agent's own settings file (Claude Code's settings.json today).
Package agenthook installs and uninstalls TokenHound's coding agent hooks in the agent's own settings file (Claude Code's settings.json today).
browser
Package browser opens a URL in the operating system's default browser.
Package browser opens a URL in the operating system's default browser.
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 and the location sort: it sets the fix plan of every finding (live, dead, unverified and suppressed alike).
Package fixplan runs once after the engine barrier and the location sort: it sets the fix plan of every finding (live, dead, unverified and suppressed alike).
githook
Package githook installs and uninstalls the TokenHound git pre-commit and pre-push hooks with a single owner (AD-18).
Package githook installs and uninstalls the TokenHound git pre-commit and pre-push hooks with a single owner (AD-18).
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.
hook
Package hook runs TokenHound as a coding agent pre-tool hook.
Package hook runs TokenHound as a coding agent pre-tool hook.
ignore
Package ignore holds the parts of the ignore grammar (docs/schema/ignore.v1.md) that both the config resolver and the suppress stage need: rule validation and the forward-slash glob matcher.
Package ignore holds the parts of the ignore grammar (docs/schema/ignore.v1.md) that both the config resolver and the suppress stage need: rule validation and the forward-slash glob matcher.
lintcheck
Package lintcheck owns the lint self-test fixtures under testdata.
Package lintcheck owns the lint self-test fixtures under testdata.
mcpserver
Package mcpserver is the `tokenhound mcp` front door: a stdio Model Context Protocol server with exactly four tools (scan, verify_status, fix_plan and report).
Package mcpserver is the `tokenhound mcp` front door: a stdio Model Context Protocol server with exactly four tools (scan, verify_status, fix_plan and report).
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).
testkeys/leakcheck
Package leakcheck is the one AD-3 leak checker of the test suites: it looks for more of a generated key than its redacted form in a captured output, raw and in its JSON-escaped, URL-encoded and base64-encoded views, and reports each hit by format, file, byte offset, encoding and finding id, never by the matched text.
Package leakcheck is the one AD-3 leak checker of the test suites: it looks for more of a generated key than its redacted form in a captured output, raw and in its JSON-escaped, URL-encoded and base64-encoded views, and reports each hit by format, file, byte offset, encoding and finding id, never by the matched text.

Jump to

Keyboard shortcuts

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