Commit Graph
73 Commits
Author SHA1 Message Date
Willie cc68f54338 refactor(audit): split audit.go by responsibility
audit.go had grown to 1821 lines mixing result scoring, skill and content
scanning, markdown link checks and content integrity. Each now lives in
its own file, matching how the tests were already split. Code is moved
verbatim; only package and import headers were added.
2026-09-30 02:21:11 +08:00
Willie ece7090b1b fix: write every YAML file with 2-space indentation
yaml.Marshal defaults to 4 spaces, and only the config package forced 2.
Saving a plugin re-encodes the whole config.yaml, so installing one
reindented a user's entire file; skill/agent frontmatter and
audit-rules.yaml were written with 4 spaces too.

Route all YAML writers (config, registry, plugins, MCP, frontmatter,
audit rules) through one utils.MarshalYAML so they cannot drift apart.
2026-09-21 16:54:13 +08:00
Willie f52ae74c5f feat(audit): remember findings accepted via --force across updates
Overriding the audit gate with --force was per-invocation, so skills that
legitimately quote attack strings (security scanners, red-team docs) had to
be forced on every `update --all`. The only alternative, disabling the rule,
was global and turned it off for every skill.

Record the accepted findings (rule + file + matched text, no line number) in
.metadata.json under `audit_accepted`, keyed by skill relPath so it survives
entry rewrites and works for tracked repos. Later updates mark matching
findings as acknowledged and exclude them from the block decision; any new
finding, or the same rule matching different text, still blocks.

Staged installs audit a temp directory, so InstallOptions gains an
AuditAcceptRoot/AuditAcceptPath override pointing at the final destination.

Refs #279
2026-09-17 10:24:18 +08:00
Rusty ShacklefordandWillie 60e19f96d5 feat(project): support a visible skillshare/ project directory (#256) (#258)
* fix(project): refuse to re-init a project that lost its config.yaml

Every project-mode command auto-initializes when .skillshare/config.yaml
is missing. That is right for a repository with no project directory at
all, and for the shared skills repo produced by 'init -p --config local',
which gitignores config.yaml so each developer regenerates their own.

It was wrong for the case in between. A .skillshare/ that already held
skills or agents, whose config.yaml was simply gone, was re-initialized
into an empty config. Every configured target was dropped, the target
symlinks were left behind pointing at a project the config no longer
described, and the command exited 0. Nothing said anything had happened.

Add ensureProjectConfig, which replaces the open-coded auto-init at every
project command entry point. It initializes as before when there is no
project directory, and when config.yaml is gitignored, so both intentional
cases keep working untouched. When the directory holds skills or agents
and its config is neither present nor gitignored, it now returns an error
pointing at version control or an explicit 'skillshare init -p' instead of
writing over the project.

The gitignore check is treated as inconclusive on error, so a repository
that cannot be inspected is guarded rather than overwritten.

* feat(project): support a visible skillshare/ project directory

Project mode is identified only by .skillshare/config.yaml, and trash,
backups, logs and audit-rules.yaml anchor to that same hidden directory.
The sources option (#153) made project content relocatable, but the
marker and operational state stay hidden, so repositories that treat
skills as reviewable content still carry a hidden directory whose only
job is to hold config.yaml.

Resolve the project directory through a new leaf package that checks
.skillshare/config.yaml first and skillshare/config.yaml second, and
derive every config, state, source-default and gitignore path from the
result. The hidden name wins whenever both exist, so an existing project
never moves and no migration is needed. The package imports nothing else
internal because internal/audit cannot import internal/config without a
cycle.

Add init -p --visible to create the visible layout. Default init -p
behaviour and output are unchanged.

Two ambiguities the visible name introduces:

- The global config directory is also called skillshare
  (<config-home>/skillshare), so the two places that infer scope from a
  config path now exclude the global location by full path rather than
  by directory name. TestLogDir_Global asserted a fixture path without
  declaring a config home, which hid this; it now sets XDG_CONFIG_HOME.
- An unrelated directory named skillshare/ must not be adopted as a
  partially initialized project, so the visible name is only claimed
  when it carries a marker of its own: a skills/ or agents/ directory,
  or a .gitignore that ignores config.yaml.

The missing-config guard added in the previous commit is generalized to
resolve through the new package, so it covers both layouts. The
gitignored-config marker matters there too. A repository shared by
'init -p --visible --config local' before any skill was committed clones
with nothing but that .gitignore, because git drops the empty skills/
and agents/ directories; recognizing it keeps the repair pointed at the
visible directory instead of writing a hidden one beside it.

Refs #256

* fix(project): reconcile visible directory support with main

Consolidate the missing-config guard and regression tests already merged in #260. Preserve both directory layouts and document and test resyncing target links after a rename. Follow-up for #258.

---------

Co-authored-by: Willie <egg358358@gmail.com>
2026-09-05 12:07:00 +08:00
Willie 6e86537987 fix(audit): honor enabled:false for synthetic tier and cross-skill findings
Tier and cross-skill findings are generated programmatically rather than
compiled from the rule list, so they bypassed the disabled-ID filter applied
at rule-compile time. Setting enabled:false in audit-rules.yaml marked the
rule disabled in the listing but the scan still fired it at full severity.

Filter synthetic findings against the disabled-ID set in both the skill-scan
and single-file paths, threading the set through the cross-skill call sites
(analyzer, cmd, server). Fixes #204.
2026-06-05 20:51:32 +08:00
Willie 9a57ca4308 fix(audit): handle uppercase URI schemes in dangling-link check
isExternalOrAnchor passed the raw scheme to isURLScheme which only
accepted lowercase letters, causing uppercase schemes like VSCode://
to be misidentified as dangling links.
2026-05-20 13:56:08 +08:00
kostaandCodex ba7191fbf8 Reduce audit false positives
Tighten publisher claim extraction, skip custom URI schemes in dangling-link checks, avoid treating bracket placeholders as markdown links, and allow common documentation domains for external-link noise reduction.

Co-authored-by: Codex <noreply@openai.com>
2026-05-20 13:10:23 +08:00
kostaandCodex ddeb8e0355 Treat Swift files as audit-scannable
Co-authored-by: Codex <noreply@openai.com>
2026-05-19 09:55:22 +08:00
Willie aaabc3ad88 refactor: simplify audit code — constants, dedup helpers, cache pattern
- Add audit.CrossSkillResultName constant, use in Go + TS
- Merge toAuditInputs/toAgentAuditInputs into one with isFile param
- Extract discoverForKind() and toInputsForKind() to eliminate 5+ if-else branches
- Simplify launchAuditTUIWithTabs with otherKindFilter dispatch
- Use CROSS_SKILL_NAME constant in AuditPage.tsx
2026-04-09 16:23:01 +08:00
Willie 1b9ba78719 fix(audit): scan agents as individual files, not directories
Agents are individual .md files discovered by resource.AgentKind{}.Discover(),
but audit was using collectInstalledSkillPaths() which calls
sync.DiscoverSourceSkillsLite() — designed for skill directories. Then
ParallelScan() called ScanSkill() which expects directories, not files.

Changes:
- Add IsFile flag to audit.SkillInput; when set, ParallelScan uses
  ScanFile/ScanFileForProject instead of ScanSkill variants
- Add collectInstalledAgentPaths() using resource.AgentKind{}.Discover()
  and resource.ActiveAgents() for proper agent file discovery
- Add toAgentAuditInputs() helper that sets IsFile=true
- Branch on kindAgents in auditInstalled(), auditFiltered(), and
  launchAuditTUIWithTabs() to use agent-specific discovery and inputs
- Add discoverAuditAgents() in server handler and update
  resolveAuditSource() to return isAgents flag
- Update handleAuditAll, handleAuditStream to use agent-aware discovery
  and build SkillInput with IsFile=true for agents
2026-04-09 14:45:24 +08:00
Willie baf6b181ae feat(audit): add Kind field to Result, Noun helpers to kind_filter, remove --all flag
- audit.Result gains a Kind string field ("skill"|"agent", set by caller)
  so callers can tag results for display without touching the scan engine
- resourceKindFilter gets Noun(count) and SingularNoun() helpers to produce
  correct singular/plural display nouns per resource type
- audit command switches from parseKindArgWithAll to parseKindArg, dropping
  the --all flag and its two help-text lines; agents subcommand is the way
  to target agents explicitly
2026-04-09 14:18:28 +08:00
Willie d16c4f3812 fix: correct metadata store routing, corruption handling, and lookup depth
Three bugs introduced during centralized metadata migration:

1. Batch agent installs via UI wrote metadata to skills/.metadata.json
   instead of agents/.metadata.json because handleInstallBatch hard-coded
   SourceDir to s.cfg.Source. Override SourceDir with agentsSource() when
   body.Kind is agent.

2. CheckAgents used LoadMetadataOrNew which silently converts parse
   failures into an empty store, making all tracked agents appear local
   and suppressing drift/update diagnostics. Switch to LoadMetadata and
   surface corruption as status=error with the parse error message.

3. findMetaEntry only climbed 3 parent directories when searching for
   .metadata.json, but --into supports arbitrary nesting depth. Raise
   the ceiling to 10 (root sentinel still terminates early).
2026-04-08 18:06:20 +08:00
Willie f95a113fce test: migrate all test metadata to centralized store format
Replace .skillshare-meta.json sidecar writes with centralized
.metadata.json store writes across all test files. Use
install.MetadataFileName constant instead of hardcoded strings.

Updated: audit_test, doctor_test, gitignore_project_test,
install_online_test, list_project_test, sync_symlinked_dir_test,
uninstall_project_test, uninstall_test, uninstall_trash_test,
audit_output_online_test, audit_scan_skill_test, analyzer_metadata_test
2026-04-08 17:43:46 +08:00
Willie 7552c76973 refactor: eliminate sidecar reads and use centralized metadata store
Production code no longer reads or writes .skillshare-meta.json sidecars:
- InstallAgentFromDiscovery: write to centralized store via WriteMetaToStore
- agent_check.go: read from centralized store passed as parameter
- handler_skills.go: read agents from s.agentsStore
- audit.go: readMetaFileHashes reads from parent .metadata.json
- analyzer_metadata.go: extract findMetaEntry to deduplicate walk logic
- uninstall_agents.go: remove entry from centralized store on uninstall
- batchUpdateAgents: pass store to reinstallAgent, remove dead field
- Replace LoadMetadata+nil guard with LoadMetadataOrNew across 6 files
2026-04-08 17:43:30 +08:00
Willie 0d59f15db4 refactor(cli): deduplicate JSON output helpers and fix ResolvePolicy semantics
- Extract writeJSONResult() to replace 5 identical write+silent-error trailers
- Replace local isRepoDirty() with existing git.IsDirty() (8 call sites)
- Use defer for suppressUIToDevnull restore instead of manual calls at each
  return site in install.go and update.go (prevents stdout leak on new paths)
- Fix ResolvePolicy always filling EnabledAnalyzers, which broke the
  nil-means-all contract for ForPolicy; add EffectiveAnalyzers() for display
- Simplify collectOutputJSON double map allocation
- Remove unnecessary string conversion in writeJSONError
2026-03-06 02:15:36 +08:00
Willie b366f619cb chore: formatting alignment and changelog jq example fix
- diff.go: align JSON struct field tags
- CHANGELOG: fix jq example (.errors → .details)
- analyzer_metadata: align map literal and test struct formatting
2026-03-06 02:15:36 +08:00
Willie bcf31d851a fix(audit): show actual active analyzers in status --json output
When no explicit analyzer filter was configured, status --json reported
an empty analyzers array. Now ResolvePolicy backfills the full list of
built-in analyzer IDs so the JSON output reflects what actually runs.

Add Registry.IDs() helper with deduplication (markdownLinkAnalyzer and
staticAnalyzer share the "static" ID).
2026-03-06 02:15:36 +08:00
Willie 6730760215 feat(audit): add hardcoded secret detection (10 rules)
Detect inline API keys, tokens, and passwords in skill files via 10 new
hardcoded-secret-* rules (HIGH severity): Google API keys, AWS access
keys, GitHub PATs (classic + fine-grained), Slack tokens, OpenAI keys,
Anthropic keys, Stripe keys, PEM private key blocks, and generic
api_key/password assignments.

Closes a gap where GitHub Secret Scanning caught a Google API key in a
skill file but our audit engine missed it entirely.
2026-03-05 02:34:24 +08:00
Willie ebf2aaf822 feat(audit): add metadata analyzer for supply-chain trust verification
Add metadataAnalyzer (skill scope) that cross-references SKILL.md
metadata against the actual git source from .skillshare-meta.json:

- publisher-mismatch (HIGH): description claims an org but repo owner
  differs (e.g. "from Acme Corp" but sourced from evil-fork)
- authority-language (MEDIUM): uses "official"/"verified" language but
  source is not a well-known organization

Both rules are disable-able via audit-rules.yaml. The analyzer reads
meta from disk (zero API signature changes) and avoids import cycles
by defining its own minimal metaJSON struct.
2026-03-05 02:13:21 +08:00
Willie 714d5f929d perf(audit): reduce regex scans with conservative prefilters
Add compile-time literal prefilters for audit rules using regexp AST analysis and apply prefilter gating before MatchString in hot scanning loops.

Changes:
- extend compiled rule with prefilter metadata (literal + case-fold flag)
- derive conservative must-match literals via regexp/syntax (fallback to LiteralPrefix)
- apply prefilter checks in unified scanners, legacy ScanContent paths, and markdown link rule checks
- add unit tests for prefilter extraction and case-fold matching

Verification:
- docker compose -f .devcontainer/docker-compose.yml exec -T --user "501:20" skillshare-devcontainer bash -lc 'cd /workspace && GOCACHE=/tmp/go-build go test ./internal/audit -count=1'
- docker compose -f .devcontainer/docker-compose.yml exec -T --user "501:20" skillshare-devcontainer bash -lc 'cd /workspace && GOCACHE=/tmp/go-build go build -o /tmp/skillshare ./cmd/skillshare && SKILLSHARE_TEST_BINARY=/tmp/skillshare GOCACHE=/tmp/go-build go test ./tests/integration -run TestAudit_ -count=1'
2026-03-03 16:08:11 +08:00
Willie 1b284e92b5 feat(audit): add semantic coloring to TUI summary footer
Labels use dim style while values use bold semantic colors, making
counts visually prominent. Threat category breakdown now colors each
category independently (injection=red, exfiltration=orange, etc.)
instead of uniform yellow, so users can distinguish threat types at
a glance.
2026-03-03 16:08:11 +08:00
Willie 459c322308 feat(audit): add category breakdown to summary across all output channels
Surface per-category finding counts (e.g., injection:3 exfiltration:2)
in CLI summary, TUI footer, markdown report, JSON output, and web API.
Adds Result.CountByCategory(), formatCategoryBreakdown() with compact
mode for TUI, and byCategory field to all audit summary structs.
2026-03-03 16:08:11 +08:00
Willie 0d04399ba9 feat(audit): surface Phase 2 fields (ruleId, analyzer, category) across all output channels
Previously the Phase 2 finding fields (ruleId, analyzer, category,
confidence, fingerprint) were only emitted in JSON and SARIF output.
This propagates them to CLI text, TUI detail panel, Markdown reports,
Server API responses, and the React frontend — each channel showing
the subset most useful for its audience.

- Server API: all 5 fields (omitempty) in auditFindingResponse
- CLI text: dim [ruleID / analyzer] line between severity and snippet
- TUI: cyan ruleID / analyzer / category line + search index
- Markdown: Rule ID and Category table columns
- Frontend: ruleId · analyzer · category dim metadata line
2026-03-03 16:08:11 +08:00
Willie 6aac91776b refactor(audit): simplify registry, dedupe, colorize, and API signatures
- Make DefaultRegistry() a singleton (stateless analyzers, safe to share)
- Consolidate duplicate ANSI regex into ui.StripANSI(); broaden pattern
  to match all CSI sequences ([a-zA-Z] terminator, not just 'm')
- Extract shared policyProfileLabel/policyDedupeLabel/policyAnalyzersLabel
  helpers; unify formatPolicyLine and formatPolicyLineFromPolicy
- Remove redundant applyPolicyToSummary calls inside auditInstalled and
  auditFiltered (cmdAudit already applies it centrally)
- Fix double isMarkdown check in scanSkillImpl walk loop
- Convert variadic ...*Registry to regular *Registry parameter across
  scanSkillImpl, ParallelScan, scanSkillPath, and scanPathTarget
- Pre-compute registry.Has() before walk loop to avoid per-file O(n) scan
2026-03-03 16:08:11 +08:00
Willie d1e7f6558a feat(audit): wire --analyzer CLI flag, config field, and update docs
- Add EnabledAnalyzers []string to AuditConfig struct
- Add enabled_analyzers to both JSON schemas (config + project)
- Parse --analyzer repeatable flag in audit command
- Wire config → PolicyInputs → Registry for all scan paths
  (ParallelScan, single skill, single path, filtered)
- Add PolicyAnalyzers to JSON summary output
- Server handler also reads config enabled_analyzers
- Update audit.md: Policy & Profiles section, Finding Schema table,
  --profile/--dedupe/--analyzer in Options table and examples
- Update configuration.md: expanded audit section with all new fields,
  profile table, analyzer IDs, precedence rules
2026-03-03 16:08:11 +08:00
Willie adae3ee0de feat(audit): add Analyzer interface, registry, and pipeline refactoring
Introduce pluggable analyzer architecture for audit scanning:

- Analyzer interface with ID/Scope/Analyze contract
- AnalyzeContext union struct carrying inputs for file/skill/bundle scopes
- 7 analyzer wrappers: static, dataflow, tier, integrity, structure,
  markdownLink, cross-skill
- Registry with DefaultRegistry(), ForPolicy() filtering, and
  scope-based accessors (FileAnalyzers/SkillAnalyzers/BundleAnalyzers)
- Policy.EnabledAnalyzers allowlist (nil = all enabled, backward compat)
- scanSkillImpl refactored to use registry gates for file-scope and
  iterator loop for skill-scope analyzers
- ScanSkillFiltered / ScanSkillFilteredForProject public APIs

All existing tests, integration tests, and 60/60 red team assertions pass.
2026-03-03 16:08:11 +08:00
Willie e7d1018126 feat(audit): add Finding schema fields — RuleID, Analyzer, Category, Confidence, Fingerprint
Phase 2 of the audit policy & dedupe design. Every finding now carries:

- RuleID: stable identifier (from rule.ID or derived)
- Analyzer: source analysis engine (static/dataflow/tier/integrity/structure/cross-skill)
- Category: classification (injection/exfiltration/credential/obfuscation/privilege/integrity/structure/risk)
- Confidence: 0~1 reliability score per analyzer type
- Fingerprint: sha256 stable hash for deduplication

Key changes:
- ComputeFingerprint + StampFingerprints in dedupe.go
- All 22 finding creation points populated with new fields
- SARIF output includes fingerprints and properties (analyzer/category/confidence)
- Markdown table gains Analyzer column
- Dedupe key prefers fingerprint when available, falls back to legacy composite key
- Fingerprints stamped inside ScanSkill/ScanFileWithRules so all callers benefit
2026-03-03 16:08:11 +08:00
Willie ef5a36ce60 feat(audit): change default dedupe mode from legacy to global
Duplicate findings (same pattern+file+line+snippet) are noise.
Global deduplication is now the default for all profiles.
Use --dedupe legacy to opt back into the old behavior.
2026-03-03 16:08:11 +08:00
Willie 07f70abf02 fix(audit): let profile presets set threshold when config has no explicit block_threshold
config.Load() normalized empty block_threshold to "CRITICAL", preventing
ResolvePolicy from applying profile-based thresholds (e.g. strict → HIGH).

Change: normalizeAuditBlockThreshold("") now returns "" instead of "CRITICAL".
All downstream callers (install, update, server) already use
audit.NormalizeThreshold() which handles empty → CRITICAL independently.

Also adds 4 integration tests for --profile, --dedupe, and config-based
profile resolution. Includes gofmt formatting fixes.
2026-03-03 16:08:11 +08:00
Willie d185f21a77 feat(audit): wire --profile/--dedupe flags, dedupe pipeline, and policy output
- CLI: add --profile and --dedupe flags to audit command with help text
- Pipeline: apply DeduplicateGlobal when dedupe_mode=global, recount
  summary after dedup via recountSummary helper
- Output: add policyProfile/policyDedupe to JSON summary and Markdown
  header (non-default profiles only)
- Server: add auditPolicy() method, populate policy fields in API
  responses for both all-skills and single-skill audit endpoints
2026-03-03 16:08:11 +08:00
Willie b5372b1228 feat(audit): add global deduplication with composite key
DeduplicateGlobal removes duplicate findings using
pattern|file|line|normalizedSnippet as key. Higher severity wins on
conflict. Snippet normalization strips ANSI, collapses whitespace.
2026-03-03 16:08:11 +08:00
Willie 47ee1ed3da feat(audit): add Policy type and ResolvePolicy with profile presets
Introduces Profile (default/strict/permissive) and DedupeMode
(legacy/global) types. ResolvePolicy resolves layered inputs from
CLI flags, config, profile presets, and built-in defaults.
2026-03-03 16:08:11 +08:00
Willie bcbbaaf34d refactor(audit): remove noisy rules, recalibrate credential severities
Remove rules that generated excessive false positives:
- source-repository-link (HIGH): legitimate docs links flagged too often;
  external-link (LOW) already covers the same URLs
- env-access (MEDIUM): process.env references are ubiquitous in JS skills
- obfuscation-1 (long base64): caught README badges and binary data

Recalibrate credential-access severity levels to reduce alert fatigue:
- etc-passwd/sudoers: HIGH → MEDIUM (read-only system files, not secrets)
- shell-history, openvpn: MEDIUM → LOW (low-impact reconnaissance)
- auth-log: LOW → INFO (log files, no direct credential exposure)

Update all affected unit tests, integration tests, red team assertions,
skill references, and website docs to match.
2026-03-03 16:08:11 +08:00
Willie 1caba253c6 fix(audit): prevent severity-only merge from wiping rules and enable --pattern from ignoring ID-level disables
P1: mergeYAMLRules Phase 2 used full-object replacement for overlays
without Enabled set, causing severity-only entries ({id, severity}) to
wipe regex/pattern/message from the base rule. compileRules then failed
with "empty regex". Now uses field-level merge: only entries with Regex
do full replacement; otherwise Enabled and Severity are patched
individually.

P2: TogglePattern enable only removed pattern-level disable entries,
leaving ID-level {id: "x", enabled: false} untouched — both builtin
and custom rules. Now clearDisableForPattern matches by builtin ID set
OR by r.Pattern == pattern, covering custom rules in the same group.
2026-03-03 16:08:11 +08:00
Willie a97cf9e34e refactor(audit): simplify rules code, fix N+1 I/O, and extract shared helpers
- Remove duplicate readOrCreateRulesFile (use loadUserRules)
- Consolidate severity normalization with shorthand aliases (c/h/m/l/i)
- Merge enable/disable into shared cmdAuditRulesToggle
- Cache builtinYAML() with sync.Once to avoid repeated YAML parsing
- Cache rulesPath/patterns/sevCounts on TUI model, use SetItems over list.New
- Extract execMutation helper, remove dead expandAll/collapseAll/buildTitle
- Fix TestScanContent_InsecureHTTP test pollution via resetForTest()
- Add batch ToggleRules/SetSeverityBatch to eliminate N+1 file I/O
- Extract shared severity helpers to ui/src/lib/severity.ts
- Merge 9 filter() calls into single-pass useMemo in AuditRulesPage
- Add 7 tests for batch toggle and severity operations
2026-03-03 16:08:11 +08:00
Willie dbe759ecfe feat(audit): add CLI rules subcommand, severity override, reset, and redesign Web UI
- Add `audit rules` CLI subcommand with list, enable, disable, severity,
  and reset commands for managing audit rules without editing YAML
- Add SetSeverity/SetPatternSeverity/ResetRules mutations in audit package
- Redesign TUI with severity tabs, two-level pattern→rule navigation,
  inline severity picker (1-5 keys), and reset-all support
- Add compiled rules API endpoints (GET /api/audit/compiled, PATCH toggle)
- Redesign AuditRulesPage with severity-colored stripes, stat cards,
  expand/collapse, toggle switches, and dark-mode-aware CSS variables
- Redesign LogPage with status-colored row stripes, reusable PillButton,
  improved stats cards with left border stripes, default 10 entries/page
- Remove system-writes audit pattern (noisy, low value)
- Fix dark mode contrast across both pages by replacing hardcoded
  design.ts colors with var(--color-*) CSS variable references
2026-03-03 16:08:11 +08:00
Willie 0b3fc11fba feat(audit): add two-level TUI for audit rules browsing and toggling
Implement a full bubbletea TUI with two navigation levels:
- Level 1 (patterns): shows pattern categories with rule count, disabled
  count, and max severity; press Enter to drill in, d to toggle pattern
- Level 2 (rules): shows individual rules with severity and status; detail
  panel shows full ID, regex, message, source; d toggles single rule,
  D toggles entire pattern, Esc returns to Level 1

Also adds audit.ResetGlobalCache() to clear cached rules after YAML
mutations, enabling live-reload within the TUI session.
2026-03-03 16:08:11 +08:00
Willie 9997114f6d feat(audit): add ToggleRule/TogglePattern for programmatic rule management 2026-03-03 16:08:11 +08:00
Willie 9eabb29ba2 feat(audit): add CompiledRule type with ListRules and PatternSummary
Introduce rules_list.go with exported types and functions for listing
all audit rules with their enable/disable status and source layer
(builtin/global/project). Includes PatternSummary for grouped stats
and UniquePatterns for pattern enumeration. Disabled rules appear in
listings with Enabled=false so UIs can display toggle state.
2026-03-03 16:08:11 +08:00
Willie beb4a1ef8d feat(audit): support pattern-level rules in audit-rules.yaml merge
Extend mergeYAMLRules to handle overlay entries that specify a pattern
but no id — these apply to all base rules sharing that pattern name.

Processing uses two phases:
  1. Pattern-level overlays (bulk disable / severity override)
  2. ID-level overlays (can override pattern-level, e.g. re-enable
     an individual rule after a pattern-level disable)

An explicit enabled:true in an id-level overlay clears a disabled flag
set by a pattern-level overlay.
2026-03-03 16:08:11 +08:00
Willie 885f072d16 feat(audit): add table-driven credential detection and 12 new security rules
Replace hardcoded credential-access YAML rules with a Go data table
(credentials.go) covering 30+ sensitive paths × 5 access methods, with
$HOME variant support, descriptive rule IDs, and an INFO-level heuristic
catch-all for unknown home dotdirs.

Add 12 new detection rules from security gap analysis:
- invisible-payload (CRITICAL): Unicode tag chars U+E0001–E007F
- prompt-injection-4 (CRITICAL): output suppression directives
- hidden-unicode-2 (HIGH): bidi control chars (Trojan Source)
- config-manipulation-0 (HIGH): AI config/memory file poisoning
- hidden-comment-injection-1 (HIGH): markdown reference-link injection
- data-exfiltration-3 (HIGH): DNS exfiltration via dig/nslookup
- self-propagation-0 (HIGH): repository worm instructions
- untrusted-install-0/1 (MEDIUM): npx -y, pip install from URL
- hidden-unicode-3 (MEDIUM): soft hyphens, directional marks

The invisible-payload pattern intentionally bypasses tutorial suppression
so CRITICAL findings are never silenced in educational contexts.
2026-03-03 16:08:11 +08:00
Willie 5d9565098e fix(audit): close regex bypass vulnerabilities and improve code reuse
Security fixes from red-team review of audit rules:
- Prompt injection: add \s* after ^ anchor to prevent whitespace bypass,
  add (?i) for case-insensitive matching, use [^>]* for HTML attributes,
  expand to cover DEV MODE / DEVELOPER_MODE variants
- Credential access: add rules for ln/cp symlink, input redirection,
  dd if=/etc/shadow (previously mislabeled as destructive-commands)
- Data exfiltration: remove exclude pattern that allowed .png?stolen_data
- Interpreter tier: add bun, deno, npx, tsx, pwsh, powershell; add
  version-suffix stripping (python3.11 → python3); handle env prefix

Code quality (from /simplify review):
- Rename crossFinding → syntheticFinding and reuse in TierCombinationFindings
  to eliminate 5 inline Finding literals
- Extract hasFinding() test helper to reduce tier test boilerplate
- Remove unnecessary (?i) from credential-access-3/4 (Unix commands are
  always lowercase)
2026-03-03 16:08:11 +08:00
Willie 7a6ba4546d feat(audit): expand prompt injection detection, add interpreter tier and credential rules
Strengthen the audit engine with new detection capabilities inspired by
skilld's sanitization research and Snyk ToxicSkills findings:

- Expand prompt-injection-1 to detect OVERRIDE:/IGNORE:/ADMIN:/ROOT: prefixes
- Add prompt-injection-2: agent directive XML tags (<system>, <instructions>, etc.)
- Add prompt-injection-3: DEVELOPER MODE, JAILBREAK, DAN MODE directives
- Add data-exfiltration-2: external images with query params (exfil vector)
- Add credential-access-3/4: /etc/shadow, /etc/passwd and related system files
- Add TierInterpreter (T6): classify python/node/ruby/perl/lua/php as
  Turing-complete runtimes separate from build tools
- Add tier-interpreter and tier-interpreter-network combination findings
- Add cross-skill-cred-interpreter rule for credential × interpreter pairs
- Update docs to reflect 38 rules and new tier/cross-skill patterns
2026-03-03 16:08:11 +08:00
Willie ca5a036e58 perf(audit): rewrite cross-skill analysis from O(N²) to O(N)
Replace nested pair-checking loop with set-based approach:
- Single pass builds capability sets (credReaders, netSenders, etc.)
- Each rule checks non-empty sets → one summary finding per rule
- 100k skills: ~15ms vs ~30s+ (benchmark included)
- Use DiscoverSourceSkillsLite for audit discovery (skip frontmatter)
- Use patternDataflowTaint constant instead of raw string
2026-03-02 23:01:30 +08:00
Willie 2fe90526f9 fix(audit): omit SARIF region for line-0 findings and add cross-skill to API
P1: SARIF startLine=0 is invalid per spec — GitHub Code Scanning rejects
it. Use *sarifRegion pointer with omitempty so findings without line
numbers (tier, cross-skill, analyzability, content-integrity) produce
valid SARIF output without a region field.

P2: Server audit endpoint (handleAuditAll) now calls CrossSkillAnalysis
after collecting results, matching CLI behavior. Previously the API
returned only per-skill findings without cross-skill interaction checks.

Also guard fmt.Println() in auditFiltered() for structured output
consistency (same fix as auditInstalled in previous commit).
2026-03-02 23:01:30 +08:00
Willie 89c3586da6 feat(audit): add markdown output format and improve terminal layout
- Add --format markdown for self-contained audit reports (GitHub Issues/PRs)
- Simplify pterm box rendering: replace DefaultBox with separator-line style
- Remove unused SkillBox, SummaryBox, SkillDisplay, wrapText helpers
- Color Box titles cyan (consistent with HeaderBox)
- Add breathing room: blank lines around progress bar and after summary
- Show "skillshare audit (project)" header title in project mode
- Append elapsed time to cross-skill synthetic results to fix slice mismatch
2026-03-02 23:01:30 +08:00
Willie 87268d3098 feat(audit): add cross-skill interaction detection
Two individually harmless skills can form an attack chain when installed
together (e.g., one reads credentials, another has network access).

After per-skill scans complete, the audit engine now extracts a capability
profile from each Result and checks for dangerous cross-skill combinations:

- cross-skill-exfiltration (HIGH): credential reader + network sender
- cross-skill-privilege-network (MEDIUM): privilege commands + network
- cross-skill-stealth (HIGH): stealth skill alongside high-risk skill

Rules only fire for complementary pairs (each skill lacks the other's
capability) to avoid duplicating per-skill findings. Results appear as
synthetic "_cross-skill" entry in all output formats (text, JSON, SARIF, TUI).
2026-03-02 23:01:30 +08:00
Willie 50e5e115c0 feat(audit): add dataflow taint tracking for cross-line exfiltration
Adds forward taint propagation analysis that detects multi-line data
exfiltration patterns where sensitive data flows through variables or
temp files before reaching a network sink.

Tracks three taint sources: credential file reads (~/.ssh, .env, etc.),
sensitive env var references ($TOKEN, $API_KEY, etc.), and command
substitution outputs. Propagates taint through variable assignments,
pipe chains, and temp file redirections. Generates HIGH-severity
dataflow-taint findings when tainted data reaches network commands.

- Add ScanShellDataflow for shell scripts and ScanMarkdownDataflow
  for fenced code blocks in markdown
- Add DeduplicateDataflow to avoid duplicate findings with existing
  per-line pattern rules
- Integrate into scanSkillImpl and ScanFileWithRules scan paths
- Can be disabled via audit-rules.yaml (id: dataflow-taint)
2026-03-02 23:01:30 +08:00
Willie b6652f11a0 feat(audit): add command safety tiering (T0–T5) for behavioral classification
Classify every shell command in skill files into 6 behavioral tiers
(read-only, mutating, destructive, network, privilege, stealth) as an
orthogonal dimension to pattern-based severity. This lets audit report
"what kind of actions" a skill performs, not just "which known patterns
it matches."

- Add tier engine with 80+ command mappings and stealth regex patterns
- Detect tiers in scripts and Markdown fenced code blocks separately
- Generate combination findings: T2+T3→HIGH, T5→CRITICAL, T3>5→MEDIUM
- Display tier profile in CLI text, TUI detail panel, and JSON/API output
- Exclude .skillshare-meta.json from totalBytes to fix analyzability ratio
- Document tier definitions, profile output, and combination findings
2026-03-02 23:01:30 +08:00
Willie 8e83495200 feat(audit): add analyzability score and pre-commit hook
Analyzability score measures what percentage of a skill's content is
auditable plaintext vs binary/non-scannable. Surfaces in CLI text
output, JSON, SARIF, and Web UI API responses.

- Add TotalBytes, AuditableBytes, Analyzability fields to audit.Result
- Emit INFO-level low-analyzability finding when score < 70%
- Show "Auditable: X%" in per-skill and summary text output
- Expose analyzability in server API (auditResultResponse + auditSummary)
- Add .pre-commit-hooks.yaml for pre-commit framework integration
- Add pre-commit hook recipe docs and audit.md cross-references
2026-03-02 23:01:30 +08:00