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 ¶
- Constants
- Variables
- func SuppressionReasons() []string
- func WarningCodes() []string
- type AlertsOptions
- type Baseline
- type BaselineFinding
- type Confidence
- type CredentialPart
- type DetectorInfo
- type DollarsMethod
- type Event
- type EventKind
- type FailOn
- type Finding
- type FirstSeen
- type FixKind
- type FixPlanResult
- type FixStep
- type Grade
- type GradeOptions
- type HistoryOptions
- type HookOptions
- type IgnoreKind
- type IgnoreRule
- type IgnoreScope
- type Limits
- type Location
- type LocationKind
- type Meta
- type NetworkOptions
- type Options
- type ProviderInfo
- type Report
- type Results
- type Source
- func AgentSurfaces() Source
- func History(repo string, opts HistoryOptions) Source
- func MachineSurfaces() Source
- func Path(p string) Source
- func ProjectSurfaces(root string) Source
- func Reader(name string, r io.Reader) Source
- func Since(repo, ref string) Source
- func Staged(repo string) Source
- func Stdin() Source
- func SurfaceFiles(surface string, files ...string) Source
- type Status
- type StatusClass
- type SurfaceStatus
- type Target
- type TargetGrade
- type TargetKind
- type Timestamp
- type USD
- type VerifyEvidence
- type VerifyOptions
- type Visibility
- type Warning
Examples ¶
Constants ¶
const ( IgnorePath = model.IgnorePath IgnoreID = model.IgnoreID IgnoreDetector = model.IgnoreDetector IgnoreLoc = model.IgnoreLoc )
Ignore rule kinds.
const ( IgnoreScopeProject = model.IgnoreScopeProject IgnoreScopeMachine = model.IgnoreScopeMachine )
Ignore scopes.
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.
const ( SurfaceFound = model.SurfaceFound SurfaceNotInstalled = model.SurfaceNotInstalled SurfaceUnreadable = model.SurfaceUnreadable SurfaceNotVisited = model.SurfaceNotVisited )
Surface statuses of Report.SurfacesChecked.
const ( FixRevoke = model.FixRevoke FixReplace = model.FixReplace FixPurge = model.FixPurge FixCheckUsage = model.FixCheckUsage FixScopeKeeper = model.FixScopeKeeper )
Fix step kinds, in plan order.
const ( StatusLive = model.StatusLive StatusDead = model.StatusDead StatusUnknown = model.StatusUnknown StatusRateLimited = model.StatusRateLimited StatusNotVerified = model.StatusNotVerified )
Verification statuses.
const ( ClassLive = model.ClassLive ClassUnverified = model.ClassUnverified ClassDead = model.ClassDead )
Status classes. Unverified covers not-verified, unknown and rate-limited.
const ( ConfidenceHigh = model.ConfidenceHigh ConfidenceMedium = model.ConfidenceMedium ConfidenceLow = model.ConfidenceLow )
Confidence levels.
const ( GradeA = model.GradeA GradeB = model.GradeB GradeC = model.GradeC GradeD = model.GradeD GradeF = model.GradeF )
Grades, best to worst.
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.
const ( TargetRepo = model.TargetRepo TargetMachine = model.TargetMachine TargetImage = model.TargetImage TargetOrgRepo = model.TargetOrgRepo TargetStdin = model.TargetStdin )
Target kinds.
const ( VisibilityPublic = model.VisibilityPublic VisibilityPrivate = model.VisibilityPrivate VisibilityUnknown = model.VisibilityUnknown )
Visibilities.
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.
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.
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.
const BaselineSchemaVersion = model.BaselineSchemaVersion
BaselineSchemaVersion is the version of the baseline file schema (docs/schema/baseline.v1.json) this model reads and writes.
const SchemaVersion = model.SchemaVersion
SchemaVersion is the version of the JSON Report schema (docs/schema/report.v1.json) that this model marshals to.
Variables ¶
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
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 ¶
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 ¶
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 FixPlanResult ¶ added in v0.2.0
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 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 LocationKind ¶
type LocationKind = model.LocationKind
LocationKind is where in a target a finding was seen.
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Reader scans the stream r, reported under name (path "-" when name is empty) with target stdin.
func Since ¶ added in v0.3.0
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 ¶
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 SurfaceFiles ¶ added in v0.3.0
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) WithTargetID ¶ added in v0.3.0
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 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 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 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.
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. |