Documentation
¶
Overview ¶
verdict.go: a unified PermissionVerdict type that consolidates the outcome shape across all permission subsystems (guardian, rules DSL, boundary checker, tool dispatcher, hooks, etc.).
The existing GuardianDecision struct has the same shape but is tied to the LLM-based guardian. PermissionVerdict is more general: it can be returned by any subsystem and carries a Risk level (low/medium/high/blocked) and a Rule string identifying which check fired.
GrayCode native implementation. hooks/permission.js (PermissionVerdict). Ported to native Go.
Index ¶
- Constants
- Variables
- func DefaultBlockedCommands() []string
- func DefaultBlockedPaths() []string
- func DefaultPath(projectDir string) string
- func DetectEncoding(text string) string
- func DetectSuspiciousPatterns(content string) []string
- func FormatChanges(result *SanitizeResult) string
- func FormatCheckResult(result *CheckResult) string
- func FormatHistory(history []*ApprovalRequest, limit int) string
- func FormatRequest(req *ApprovalRequest) string
- func FormatResult(result *ScanResult) string
- func FormatViolation(v *BoundaryViolation) string
- func IsSuspicious(content string) bool
- func SanitizeFilePath(path string) (string, error)
- func SanitizeJSON(input string) string
- func Save(path string, rules []Rule) error
- func StripANSI(text string) string
- func WrapExternalContent(content string, opts WrapOptions) string
- func WrapWebContent(content string, source ContentSource) string
- type Action
- type ApprovalPolicy
- type ApprovalRequest
- type ApprovalWorkflow
- func (wf *ApprovalWorkflow) AddPolicy(policy ApprovalPolicy)
- func (wf *ApprovalWorkflow) Approve(id, reason string) error
- func (wf *ApprovalWorkflow) CheckPolicy(tool string, risk string) *ApprovalPolicy
- func (wf *ApprovalWorkflow) Deny(id, reason string) error
- func (wf *ApprovalWorkflow) ExpirePending()
- func (wf *ApprovalWorkflow) GetPending() []*ApprovalRequest
- func (wf *ApprovalWorkflow) IsApproved(id string) bool
- func (wf *ApprovalWorkflow) RequestApproval(tool string, args map[string]interface{}, risk string) (*ApprovalRequest, error)
- type AskRecord
- type AutoModeState
- type BoundaryChecker
- func (bc *BoundaryChecker) CheckCommand(command string) *BoundaryViolation
- func (bc *BoundaryChecker) CheckEnvironment(key string) *BoundaryViolation
- func (bc *BoundaryChecker) CheckFileCount() *BoundaryViolation
- func (bc *BoundaryChecker) CheckFileSize(path string, size int64) *BoundaryViolation
- func (bc *BoundaryChecker) CheckNetwork(host string, port int) *BoundaryViolation
- func (bc *BoundaryChecker) CheckPath(path string) *BoundaryViolation
- func (bc *BoundaryChecker) IsWithinProject(path string) bool
- func (bc *BoundaryChecker) RecordModification(path string)
- func (bc *BoundaryChecker) RecordViolation(v *BoundaryViolation)
- func (bc *BoundaryChecker) Summary() string
- type BoundaryViolation
- type BypassKillswitch
- type Canonicalizer
- func (c *Canonicalizer) Canonicalize(command string) string
- func (c *Canonicalizer) ExtractBaseCommand(command string) string
- func (c *Canonicalizer) ExtractSubcommand(command string) string
- func (c *Canonicalizer) GeneratePattern(command string) string
- func (c *Canonicalizer) IsBannedPrefix(command string) bool
- func (c *Canonicalizer) IsEquivalent(cmd1, cmd2 string) bool
- type CheckResult
- type Classifier
- type ContentSource
- type Destination
- type EgressAttempt
- type EgressInspector
- func (e *EgressInspector) AddAllowed(domain string)
- func (e *EgressInspector) AddBlocked(domain string)
- func (e *EgressInspector) ExtractNetcat(command string) []string
- func (e *EgressInspector) ExtractSSHDests(command string) []string
- func (e *EgressInspector) ExtractURLs(command string) []string
- func (e *EgressInspector) FormatAttempt(attempt *EgressAttempt) string
- func (e *EgressInspector) Inspect(command string) *EgressAttempt
- func (e *EgressInspector) IsAllowed(host string) bool
- func (e *EgressInspector) IsSuspicious(command string) bool
- type Guardian
- type GuardianDecision
- type GuardianRequest
- type InjectionPattern
- type InjectionScanner
- type InputSanitizer
- type MalwareEntry
- type OSVChecker
- func (c *OSVChecker) CheckCommand(command string) *CheckResult
- func (c *OSVChecker) CheckPackage(name, ecosystem string) *CheckResult
- func (c *OSVChecker) DetectSuspiciousName(name string) []string
- func (c *OSVChecker) IsTyposquat(name, ecosystem string) bool
- func (c *OSVChecker) RefreshDatabase() error
- type PermissionVerdict
- type Risk
- type Rule
- type RuleSet
- type SanitizeChange
- type SanitizeResult
- type ScanResult
- type ShadowedRuleDetector
- type Threat
- type WrapOptions
Constants ¶
const ( RiskLow = contracts.RiskLow RiskMedium = contracts.RiskMedium RiskHigh = contracts.RiskHigh RiskBlocked = contracts.RiskBlocked )
Variables ¶
var Allow = contracts.Allow
Allow returns a permissive verdict.
var BannedPrefixes = []string{
"bash",
"sh",
"zsh",
"fish",
"dash",
"python",
"node",
"ruby",
"perl",
"lua",
"eval",
"exec",
"source",
}
BannedPrefixes lists patterns that should NEVER be saved as approved commands.
var Deny = contracts.Deny
Deny returns a reject verdict with the given reason and rule.
var ErrCircuitBreakerOpen = errors.New("guardian circuit breaker open: too many consecutive denials, falling back to user")
ErrCircuitBreakerOpen is returned when the guardian has denied too many consecutive requests and should fall back to user prompting.
var ErrGuardianUnparseable = errors.New("guardian: no parseable JSON in LLM response")
ErrGuardianUnparseable is returned by parseGuardianResponse when the LLM's response does not contain a parseable JSON object. A parseable response is one with a brace-balanced `{...}` substring that decodes as a GuardianDecision. This is a distinct error from transport/timeout failures so callers (and tests) can distinguish "the LLM gave us garbage" from "the LLM call failed entirely".
var ParseRisk = contracts.ParseRisk
ParseRisk parses a risk name (case-insensitive) into a Risk value.
var RequireApproval = contracts.RequireApproval
RequireApproval returns a "needs human approval" verdict. Allowed is false; the caller can use Confidence < 1.0 to indicate the request is plausible but uncertain.
Functions ¶
func DefaultBlockedCommands ¶
func DefaultBlockedCommands() []string
DefaultBlockedCommands returns the default list of commands that should be blocked.
func DefaultBlockedPaths ¶
func DefaultBlockedPaths() []string
DefaultBlockedPaths returns the default list of paths that should be blocked.
func DefaultPath ¶
DefaultPath returns the default permissions file path for a project directory.
func DetectEncoding ¶
DetectEncoding determines the encoding category of text. Returns "utf8", "ascii", "binary", or "mixed".
func FormatChanges ¶
func FormatChanges(result *SanitizeResult) string
FormatChanges produces a human-readable summary of all sanitization changes.
func FormatCheckResult ¶
func FormatCheckResult(result *CheckResult) string
FormatCheckResult produces a human-readable report for a check result.
func FormatHistory ¶
func FormatHistory(history []*ApprovalRequest, limit int) string
FormatHistory formats the approval history for display.
func FormatRequest ¶
func FormatRequest(req *ApprovalRequest) string
FormatRequest formats an approval request for display to the user.
func FormatResult ¶
func FormatResult(result *ScanResult) string
FormatResult produces a human-readable string representation of a ScanResult.
func FormatViolation ¶
func FormatViolation(v *BoundaryViolation) string
FormatViolation formats a BoundaryViolation into a human-readable string.
func IsSuspicious ¶
func SanitizeFilePath ¶
SanitizeFilePath validates and normalizes a file path, preventing traversal attacks.
func SanitizeJSON ¶
SanitizeJSON removes potentially dangerous keys from JSON input. It strips __proto__, constructor, and prototype keys to prevent prototype pollution.
func WrapExternalContent ¶
func WrapExternalContent(content string, opts WrapOptions) string
func WrapWebContent ¶
func WrapWebContent(content string, source ContentSource) string
Types ¶
type Action ¶
type Action string
Action represents the permission action to take for a tool invocation.
type ApprovalPolicy ¶
type ApprovalPolicy struct {
Name string
Tools []string
RiskLevel string
AutoApprove bool
RequireReason bool
Timeout time.Duration
MaxPending int
}
ApprovalPolicy defines rules for how approval requests are handled.
type ApprovalRequest ¶
type ApprovalRequest struct {
ID string
Tool string
Args map[string]interface{}
Risk string
Description string
CreatedAt time.Time
Status string // "pending", "approved", "denied", "expired"
ExpiresAt time.Time
Reason string
}
ApprovalRequest represents a request for approval of a high-risk operation.
type ApprovalWorkflow ¶
type ApprovalWorkflow struct {
Policies []ApprovalPolicy
Pending []*ApprovalRequest
History []*ApprovalRequest
PromptFn func(*ApprovalRequest) (bool, string)
// contains filtered or unexported fields
}
ApprovalWorkflow manages the approval process for destructive or high-risk operations.
func NewApprovalWorkflow ¶
func NewApprovalWorkflow(promptFn func(*ApprovalRequest) (bool, string)) *ApprovalWorkflow
NewApprovalWorkflow creates an ApprovalWorkflow with default policies and the given prompt function.
func (*ApprovalWorkflow) AddPolicy ¶
func (wf *ApprovalWorkflow) AddPolicy(policy ApprovalPolicy)
AddPolicy adds a new approval policy to the workflow.
func (*ApprovalWorkflow) Approve ¶
func (wf *ApprovalWorkflow) Approve(id, reason string) error
Approve approves the pending request with the given ID.
func (*ApprovalWorkflow) CheckPolicy ¶
func (wf *ApprovalWorkflow) CheckPolicy(tool string, risk string) *ApprovalPolicy
CheckPolicy finds the matching policy for a tool and risk level.
func (*ApprovalWorkflow) Deny ¶
func (wf *ApprovalWorkflow) Deny(id, reason string) error
Deny denies the pending request with the given ID.
func (*ApprovalWorkflow) ExpirePending ¶
func (wf *ApprovalWorkflow) ExpirePending()
ExpirePending marks all expired pending requests.
func (*ApprovalWorkflow) GetPending ¶
func (wf *ApprovalWorkflow) GetPending() []*ApprovalRequest
GetPending returns all currently pending approval requests.
func (*ApprovalWorkflow) IsApproved ¶
func (wf *ApprovalWorkflow) IsApproved(id string) bool
IsApproved returns true if the request with the given ID has been approved.
func (*ApprovalWorkflow) RequestApproval ¶
func (wf *ApprovalWorkflow) RequestApproval(tool string, args map[string]interface{}, risk string) (*ApprovalRequest, error)
RequestApproval creates an approval request for the given tool invocation. If the matching policy auto-approves, the request is approved immediately. Otherwise, the PromptFn is called to ask the user.
type AutoModeState ¶
type AutoModeState struct {
// contains filtered or unexported fields
}
AutoModeState tracks auto-allow decisions for learning user preferences.
func NewAutoModeState ¶
func NewAutoModeState() *AutoModeState
NewAutoModeState creates a new auto-mode state.
func (*AutoModeState) Record ¶
func (a *AutoModeState) Record(toolName, summary string, allowed bool)
Record records a permission decision.
func (*AutoModeState) ShouldAutoAllow ¶
func (a *AutoModeState) ShouldAutoAllow(toolName, summary string) (bool, bool)
ShouldAutoAllow checks if a tool should be automatically allowed.
type BoundaryChecker ¶
type BoundaryChecker struct {
ProjectRoot string
AllowedPaths []string
BlockedPaths []string
AllowedCommands []string
BlockedCommands []string
MaxFileSize int64
MaxFiles int
FilesModified int
// contains filtered or unexported fields
}
BoundaryChecker enforces safety boundaries that prevent the agent from performing actions outside its authorized scope.
func NewBoundaryChecker ¶
func NewBoundaryChecker(projectRoot string) *BoundaryChecker
NewBoundaryChecker creates a new BoundaryChecker with sensible defaults.
func (*BoundaryChecker) CheckCommand ¶
func (bc *BoundaryChecker) CheckCommand(command string) *BoundaryViolation
CheckCommand verifies that a command is not in the blocked list and does not attempt privilege escalation or dangerous system operations.
func (*BoundaryChecker) CheckEnvironment ¶
func (bc *BoundaryChecker) CheckEnvironment(key string) *BoundaryViolation
CheckEnvironment verifies that access to sensitive environment variables is blocked.
func (*BoundaryChecker) CheckFileCount ¶
func (bc *BoundaryChecker) CheckFileCount() *BoundaryViolation
CheckFileCount verifies that the number of modified files has not exceeded the session limit.
func (*BoundaryChecker) CheckFileSize ¶
func (bc *BoundaryChecker) CheckFileSize(path string, size int64) *BoundaryViolation
CheckFileSize verifies that a file write does not exceed the maximum allowed size.
func (*BoundaryChecker) CheckNetwork ¶
func (bc *BoundaryChecker) CheckNetwork(host string, port int) *BoundaryViolation
CheckNetwork verifies that network connections are not targeting internal/private networks or cloud metadata endpoints.
func (*BoundaryChecker) CheckPath ¶
func (bc *BoundaryChecker) CheckPath(path string) *BoundaryViolation
CheckPath verifies that a given path is within the authorized project boundary.
func (*BoundaryChecker) IsWithinProject ¶
func (bc *BoundaryChecker) IsWithinProject(path string) bool
IsWithinProject checks whether a path resolves to within the project root.
func (*BoundaryChecker) RecordModification ¶
func (bc *BoundaryChecker) RecordModification(path string)
RecordModification tracks a file modification for MaxFiles enforcement.
func (*BoundaryChecker) RecordViolation ¶
func (bc *BoundaryChecker) RecordViolation(v *BoundaryViolation)
RecordViolation stores a violation for tracking purposes.
func (*BoundaryChecker) Summary ¶
func (bc *BoundaryChecker) Summary() string
Summary returns a summary of the current session's boundary state.
type BoundaryViolation ¶
type BoundaryViolation struct {
Type string // "path", "command", "size", "count", "network", "env"
Description string
Attempted string
Allowed string
Severity string // "LOW", "MEDIUM", "HIGH", "CRITICAL"
}
BoundaryViolation represents a single boundary violation detected by the checker.
type BypassKillswitch ¶
type BypassKillswitch struct {
// contains filtered or unexported fields
}
BypassKillswitch disables permission checks globally.
func NewBypassKillswitch ¶
func NewBypassKillswitch() *BypassKillswitch
NewBypassKillswitch creates a new bypass killswitch.
func (*BypassKillswitch) Disable ¶
func (b *BypassKillswitch) Disable()
Disable disables the bypass killswitch.
func (*BypassKillswitch) Enable ¶
func (b *BypassKillswitch) Enable()
Enable enables the bypass killswitch.
func (*BypassKillswitch) IsEnabled ¶
func (b *BypassKillswitch) IsEnabled() bool
IsEnabled checks if the bypass killswitch is enabled.
type Canonicalizer ¶
type Canonicalizer struct{}
Canonicalizer normalizes shell commands for stable approval caching. It is stateless and safe for concurrent use.
func NewCanonicalizer ¶
func NewCanonicalizer() *Canonicalizer
NewCanonicalizer creates a new Canonicalizer instance.
func (*Canonicalizer) Canonicalize ¶
func (c *Canonicalizer) Canonicalize(command string) string
Canonicalize normalizes a shell command for consistent matching.
func (*Canonicalizer) ExtractBaseCommand ¶
func (c *Canonicalizer) ExtractBaseCommand(command string) string
ExtractBaseCommand returns just the binary name from a command.
func (*Canonicalizer) ExtractSubcommand ¶
func (c *Canonicalizer) ExtractSubcommand(command string) string
ExtractSubcommand returns the binary name plus its first non-flag argument.
func (*Canonicalizer) GeneratePattern ¶
func (c *Canonicalizer) GeneratePattern(command string) string
GeneratePattern creates a glob pattern that would match this command and similar ones.
func (*Canonicalizer) IsBannedPrefix ¶
func (c *Canonicalizer) IsBannedPrefix(command string) bool
IsBannedPrefix checks if a command starts with a banned prefix.
func (*Canonicalizer) IsEquivalent ¶
func (c *Canonicalizer) IsEquivalent(cmd1, cmd2 string) bool
IsEquivalent checks if two commands are semantically the same for permission purposes.
type CheckResult ¶
type CheckResult struct {
Package string
Safe bool
Advisories []string
Severity string
Recommendation string
CheckedAt time.Time
}
CheckResult represents the outcome of a package safety check.
type Classifier ¶
type Classifier struct {
// contains filtered or unexported fields
}
Classifier classifies commands as safe or dangerous.
func NewClassifier ¶
func NewClassifier() *Classifier
NewClassifier creates a new permission classifier.
func (*Classifier) Classify ¶
func (c *Classifier) Classify(command string) string
Classify classifies a command as safe, unsafe, or unknown.
type ContentSource ¶
type ContentSource string
const ( SourceEmail ContentSource = "email" SourceWebhook ContentSource = "webhook" SourceAPI ContentSource = "api" SourceBrowser ContentSource = "browser" SourceWebSearch ContentSource = "web_search" SourceWebFetch ContentSource = "web_fetch" SourceUnknown ContentSource = "unknown" )
type Destination ¶
Destination represents a network destination extracted from a command.
type EgressAttempt ¶
type EgressAttempt struct {
Command string
Destinations []Destination
Allowed bool
Reason string
}
EgressAttempt represents the result of inspecting a command for egress activity.
type EgressInspector ¶
type EgressInspector struct {
AllowedDomains []string
BlockedDomains []string
AllowedProtocols []string
// contains filtered or unexported fields
}
EgressInspector detects and blocks data exfiltration attempts in shell commands by checking outbound network destinations before execution.
func NewEgressInspector ¶
func NewEgressInspector() *EgressInspector
NewEgressInspector creates an EgressInspector with sensible defaults.
func (*EgressInspector) AddAllowed ¶
func (e *EgressInspector) AddAllowed(domain string)
AddAllowed adds a domain to the allowed list.
func (*EgressInspector) AddBlocked ¶
func (e *EgressInspector) AddBlocked(domain string)
AddBlocked adds a domain to the blocked list.
func (*EgressInspector) ExtractNetcat ¶
func (e *EgressInspector) ExtractNetcat(command string) []string
ExtractNetcat parses nc/netcat host port patterns.
func (*EgressInspector) ExtractSSHDests ¶
func (e *EgressInspector) ExtractSSHDests(command string) []string
ExtractSSHDests parses ssh user@host, scp user@host:path patterns.
func (*EgressInspector) ExtractURLs ¶
func (e *EgressInspector) ExtractURLs(command string) []string
ExtractURLs finds all URLs in the command (http://, https://, git://, ssh://).
func (*EgressInspector) FormatAttempt ¶
func (e *EgressInspector) FormatAttempt(attempt *EgressAttempt) string
FormatAttempt produces a human-readable report of an egress inspection.
func (*EgressInspector) Inspect ¶
func (e *EgressInspector) Inspect(command string) *EgressAttempt
Inspect analyzes a command for network egress destinations and returns an EgressAttempt indicating whether the command is allowed.
func (*EgressInspector) IsAllowed ¶
func (e *EgressInspector) IsAllowed(host string) bool
IsAllowed checks whether a host is permitted based on allow/block lists. Blocked takes precedence over allowed.
func (*EgressInspector) IsSuspicious ¶
func (e *EgressInspector) IsSuspicious(command string) bool
IsSuspicious detects patterns commonly associated with data exfiltration.
type Guardian ¶
type Guardian struct {
Enabled bool
Provider string
Model string
Timeout time.Duration
MaxConsecutiveDenials int
ChatFn func(ctx context.Context, prompt string) (string, error)
// contains filtered or unexported fields
}
Guardian is an LLM-powered automatic permission reviewer that decides permissions on behalf of the user, reducing approval fatigue.
func NewGuardian ¶
NewGuardian creates a new Guardian with sensible defaults.
func (*Guardian) ResetCircuitBreaker ¶
func (g *Guardian) ResetCircuitBreaker()
ResetCircuitBreaker resets the consecutive denial counter.
func (*Guardian) Review ¶
func (g *Guardian) Review(ctx context.Context, req GuardianRequest) (*GuardianDecision, error)
Review evaluates a tool call and returns a decision on whether it should be allowed.
func (*Guardian) SetMaxConsecutiveDenials ¶
SetMaxConsecutiveDenials updates the circuit-breaker cap and clamps it to [minGuardianCap, maxGuardianCap]. The cap is the number of consecutive denials before the guardian opens its circuit and falls back to user prompting. A cap of 1 makes the guardian advisory-only (any single denial breaks the circuit); the default is 5, suitable for typical permission-review workloads where false positives in a row are rare. Returns the clamped value so callers can log the effective cap.
type GuardianDecision ¶
type GuardianDecision = contracts.GuardianDecision
GuardianDecision represents the guardian's decision on a permission request.
type GuardianRequest ¶
type GuardianRequest struct {
ToolName string
Arguments map[string]interface{}
ConversationContext string
ProjectDescription string
}
GuardianRequest represents a permission review request.
type InjectionPattern ¶
type InjectionPattern struct {
Name string
Pattern *regexp.Regexp
Severity string // "critical", "high", "medium", "low"
Category string // "system_override", "data_exfil", "role_hijack", "instruction_leak"
}
InjectionPattern defines a single pattern used to detect prompt injection attempts.
type InjectionScanner ¶
type InjectionScanner struct {
Patterns []*InjectionPattern
Threshold float64
// contains filtered or unexported fields
}
InjectionScanner detects malicious prompt injection attempts in user input and tool outputs.
func NewInjectionScanner ¶
func NewInjectionScanner() *InjectionScanner
NewInjectionScanner creates an InjectionScanner pre-loaded with 30+ detection patterns.
func (*InjectionScanner) DetectUnicodeAttacks ¶
func (s *InjectionScanner) DetectUnicodeAttacks(text string) []Threat
DetectUnicodeAttacks identifies homoglyphs, zero-width characters, bidirectional overrides, and invisible separators.
func (*InjectionScanner) IsHighEntropy ¶
func (s *InjectionScanner) IsHighEntropy(text string) bool
IsHighEntropy detects potential encoded payloads by calculating Shannon entropy. Text with entropy above 4.5 bits per character is considered suspicious.
func (*InjectionScanner) Scan ¶
func (s *InjectionScanner) Scan(text string) *ScanResult
Scan analyzes text for injection attempts and returns a structured result.
func (*InjectionScanner) ScanToolOutput ¶
func (s *InjectionScanner) ScanToolOutput(output string) *ScanResult
ScanToolOutput scans tool output for injection attempts that might be embedded in data returned by external tools (poisoned responses).
type InputSanitizer ¶
type InputSanitizer struct {
MaxLength int
StripInvisible bool
NormalizeUnicode bool
// contains filtered or unexported fields
}
InputSanitizer cleans and validates all inputs before they reach the LLM, preventing injection, encoding attacks, and malformed data.
func NewInputSanitizer ¶
func NewInputSanitizer() *InputSanitizer
NewInputSanitizer creates an InputSanitizer with sensible defaults.
func (*InputSanitizer) Sanitize ¶
func (s *InputSanitizer) Sanitize(input string) *SanitizeResult
Sanitize applies all sanitization steps to the input and returns a detailed result.
type MalwareEntry ¶
type MalwareEntry struct {
Package string
Ecosystem string // "npm", "pypi", "go", "crates"
Advisory string
Severity string // "CRITICAL", "HIGH", "MEDIUM", "LOW"
Description string
DateAdded time.Time
}
MalwareEntry represents a known malicious package in the database.
type OSVChecker ¶
type OSVChecker struct {
KnownMalware map[string]*MalwareEntry
Cache map[string]*CheckResult
CacheTTL time.Duration
// contains filtered or unexported fields
}
OSVChecker checks packages against a known malware database before installation.
func NewOSVChecker ¶
func NewOSVChecker() *OSVChecker
NewOSVChecker creates an OSVChecker pre-populated with known malicious packages.
func (*OSVChecker) CheckCommand ¶
func (c *OSVChecker) CheckCommand(command string) *CheckResult
CheckCommand parses a shell command to extract and check the package being installed.
func (*OSVChecker) CheckPackage ¶
func (c *OSVChecker) CheckPackage(name, ecosystem string) *CheckResult
CheckPackage checks whether a package is known to be malicious.
func (*OSVChecker) DetectSuspiciousName ¶
func (c *OSVChecker) DetectSuspiciousName(name string) []string
DetectSuspiciousName identifies red flags in a package name.
func (*OSVChecker) IsTyposquat ¶
func (c *OSVChecker) IsTyposquat(name, ecosystem string) bool
IsTyposquat checks whether a package name appears to be a typosquat of a popular package.
func (*OSVChecker) RefreshDatabase ¶
func (c *OSVChecker) RefreshDatabase() error
RefreshDatabase is a placeholder for future OSV API integration. In production, this would fetch the latest advisories from https://api.osv.dev/v1/query.
type PermissionVerdict ¶
type PermissionVerdict = contracts.PermissionVerdict
PermissionVerdict is the unified outcome type for any permission subsystem. It is constructed by helpers (Allow, Deny, RequireApproval) and consumed by the tool dispatcher.
type Rule ¶
type Rule struct {
Tool string `json:"tool"` // tool name or "*" for all
Pattern string `json:"pattern"` // glob pattern for arguments (e.g., "/tmp/*", "*.go", "go test*")
Action Action `json:"action"`
Reason string `json:"reason,omitempty"` // optional explanation
}
Rule defines a single permission rule mapping a tool and argument pattern to an action.
func ParseRuleLine ¶
ParseRuleLine parses a single rule line into a Rule. Format: <action> <tool> <pattern> The pattern may be quoted to include spaces.
type RuleSet ¶
type RuleSet struct {
Rules []Rule
// contains filtered or unexported fields
}
RuleSet holds an ordered collection of permission rules.
func (*RuleSet) Evaluate ¶
Evaluate checks the rules in order and returns the action for the given tool and args. First matching rule wins. Returns ActionAsk if no rules match.
func (*RuleSet) LoadFromFile ¶
LoadFromFile parses a .hawk/rules file and populates the RuleSet.
func (*RuleSet) RemoveRule ¶
RemoveRule removes the rule at the given index.
func (*RuleSet) SaveToFile ¶
SaveToFile writes the rules to a file in the .hawk/rules format.
type SanitizeChange ¶
type SanitizeChange struct {
Type string // "stripped", "normalized", "truncated", "escaped"
Position int
Original string
Replacement string
}
SanitizeChange describes a single modification made during sanitization.
func NormalizeHomoglyphs ¶
func NormalizeHomoglyphs(text string) (string, []SanitizeChange)
NormalizeHomoglyphs detects mixed Latin+Cyrillic scripts and replaces Cyrillic lookalikes with Latin equivalents. Pure Cyrillic text is left alone.
func StripInvisibleChars ¶
func StripInvisibleChars(text string) (string, []SanitizeChange)
StripInvisibleChars removes invisible Unicode characters from text. This includes zero-width space/joiner/non-joiner, BOM markers, bidirectional overrides, invisible separators, and tag characters.
Some entries in invisibleRunes (e.g., U+115F Hangul filler, U+17B4 Khmer vowel) are actually visible or semantically meaningful in their native script. To avoid mangling legitimate non-Latin text, characters in invisibleRunes whose Unicode script is in legitimateScriptTables are NOT stripped — they're preserved.
The check is per-character: invisible-rune entries whose script is NOT in the allow-list ARE stripped, since stripping is the safe default for those. Pure Common/Inherited characters (BIDI marks, format chars) are always stripped.
type SanitizeResult ¶
type SanitizeResult struct {
Clean string
Original string
Changes []SanitizeChange
WasModified bool
}
SanitizeResult holds the outcome of sanitizing an input string.
type ScanResult ¶
ScanResult contains the outcome of scanning text for injection attempts.
type ShadowedRuleDetector ¶
type ShadowedRuleDetector struct{}
ShadowedRuleDetector detects when permission rules shadow each other.
func (*ShadowedRuleDetector) DetectShadowedRules ¶
func (d *ShadowedRuleDetector) DetectShadowedRules(allowRules, denyRules []string) []string
DetectShadowedRules finds shadowed permission rules.
type WrapOptions ¶
type WrapOptions struct {
Source ContentSource
Sender string
Subject string
IncludeWarning bool
}