tokenhound

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package 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/pkg/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
	// CodeBenchmarkNetworkBlocked is a request a benchmark build refused before any
	// dial (every purpose but verify). Default builds never emit it.
	CodeBenchmarkNetworkBlocked = model.CodeBenchmarkNetworkBlocked
)

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 ReasonNotInGroundTruth = model.ReasonNotInGroundTruth

ReasonNotInGroundTruth is the status_reason of an unknown finding in a benchmark build whose credential the ground truth does not list. Default builds never set it.

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

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

type Baseline = model.Baseline

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

type BaselineFinding

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

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

type FixKind = model.FixKind

FixKind is the kind of a fix plan step.

type FixPlanResult

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/pkg/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

type IgnoreKind = model.IgnoreKind

IgnoreKind is the kind of an ignore rule.

type IgnoreRule

type IgnoreRule = model.IgnoreRule

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

type IgnoreScope

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/pkg/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/internal/registry"
	"github.com/aiagentpro/tokenhound/pkg/tokenhound"
	"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

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

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

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

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.

Jump to

Keyboard shortcuts

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