From 4ededca4dd8101f1fa10b2834325f7ed2222e1ea Mon Sep 17 00:00:00 2001 From: Rusty Shackleford <182032677+salmonumbrella@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:37:33 -0700 Subject: [PATCH] feat(audit): check bundled reference containment (#754) Required local references can currently escape a skill bundle or fail silently when written as images and explicit code paths. Resolve them within the declared root without reading external targets, retain dangling-link compatibility, and share the findings and rule controls with doctor. Keep metadata and integrity fallback reads within the same root so they cannot reopen skipped symlinks. Co-authored-by: GPT-6.1 Sol Co-authored-by: Willie --- .../tests/audit_bundled_references_runbook.md | 125 ++++++ cmd/skillshare/doctor.go | 9 +- cmd/skillshare/doctor_references.go | 83 ++++ cmd/skillshare/doctor_references_test.go | 155 +++++++ internal/audit/analyzer_structure.go | 15 +- internal/audit/analyzers.go | 15 +- internal/audit/audit_follow_test.go | 45 ++ internal/audit/audit_scan_skill.go | 16 + internal/audit/audit_scan_skill_test.go | 26 ++ internal/audit/bundled_references.go | 397 ++++++++++++++++++ .../audit/bundled_references_scan_test.go | 21 + internal/audit/bundled_references_test.go | 356 ++++++++++++++++ internal/audit/markdown_links.go | 140 +++--- scripts/create-demo-content.sh | 6 +- skills/skillshare/references/audit.md | 2 + tests/integration/doctor_test.go | 15 + ui/src/i18n/locales/de.json | 1 + ui/src/i18n/locales/en.json | 1 + ui/src/i18n/locales/es.json | 1 + ui/src/i18n/locales/fa.json | 1 + ui/src/i18n/locales/fr.json | 1 + ui/src/i18n/locales/id.json | 1 + ui/src/i18n/locales/ja.json | 1 + ui/src/i18n/locales/ko.json | 1 + ui/src/i18n/locales/pt-BR.json | 1 + ui/src/i18n/locales/zh-CN.json | 1 + ui/src/i18n/locales/zh-TW.json | 1 + website/docs/learn/with-playground.md | 2 +- .../docs/reference/commands/audit-rules.md | 4 +- website/docs/reference/commands/audit.md | 2 +- website/docs/reference/commands/doctor.md | 2 + website/docs/understand/audit-engine.md | 13 +- .../current/learn/with-playground.md | 2 +- .../current/reference/commands/audit-rules.md | 4 +- .../current/reference/commands/audit.md | 2 +- .../current/reference/commands/doctor.md | 2 + .../current/understand/audit-engine.md | 14 +- .../current/learn/with-playground.md | 2 +- .../current/reference/commands/audit-rules.md | 4 +- .../current/reference/commands/audit.md | 2 +- .../current/reference/commands/doctor.md | 2 + .../current/understand/audit-engine.md | 14 +- .../current/learn/with-playground.md | 2 +- .../current/reference/commands/audit-rules.md | 4 +- .../current/reference/commands/audit.md | 2 +- .../current/reference/commands/doctor.md | 2 + .../current/understand/audit-engine.md | 14 +- .../current/learn/with-playground.md | 2 +- .../current/reference/commands/audit-rules.md | 4 +- .../current/reference/commands/audit.md | 2 +- .../current/reference/commands/doctor.md | 2 + .../current/understand/audit-engine.md | 14 +- 52 files changed, 1448 insertions(+), 108 deletions(-) create mode 100644 ai_docs/tests/audit_bundled_references_runbook.md create mode 100644 cmd/skillshare/doctor_references.go create mode 100644 cmd/skillshare/doctor_references_test.go create mode 100644 internal/audit/bundled_references.go create mode 100644 internal/audit/bundled_references_scan_test.go create mode 100644 internal/audit/bundled_references_test.go diff --git a/ai_docs/tests/audit_bundled_references_runbook.md b/ai_docs/tests/audit_bundled_references_runbook.md new file mode 100644 index 000000000..1f2eda406 --- /dev/null +++ b/ai_docs/tests/audit_bundled_references_runbook.md @@ -0,0 +1,125 @@ +# CLI E2E Runbook: Bundled References + +Validate contained reference checks and doctor parity using synthetic paths only. + +**Origin**: audit improvement item 13 of #746. + +## Scope + +- LOW missing links/images and HIGH parent/symlink escapes +- Explicit code-path forms, benign code examples, and preserved source evidence +- Doctor JSON parity and global rule disables +- Nested code paths use the document for `./` and `../`, and the skill root for other relative paths + +## Environment + +Run inside the devcontainer using mdproof's isolated HOME and TMPDIR. +Never execute fixture content or reference personal files. + +## Steps + +### 1. Audit required references and benign examples + +```bash +set -eu +fixture="$TMPDIR/bundled-references" +mkdir -p "$fixture/references" "$TMPDIR/bundled-external" +printf '# Existing\n' > "$fixture/references/ok.md" +ln -s "$TMPDIR/bundled-external" "$fixture/external.bundle" +cat > "$fixture/SKILL.md" <<'DOC' +--- +name: bundled-references +description: Synthetic reference fixture +--- +[existing](references/ok.md) +![missing](assets/missing.png) +[escape](../outside.md) +[symlink](external.bundle/missing.md) +Read `./missing.md`. +Example: `/example/config.json` and `ordinary.identifier`. +DOC +ss audit -g "$fixture" --analyzer structure --format json +``` + +Expected: +- exit_code: 0 +- jq: [.results[].findings[] | select(.ruleId == "dangling-link")] | length == 2 +- jq: [.results[].findings[] | select(.ruleId == "reference-escapes-root" and .severity == "HIGH")] | length == 2 +- jq: [.results[].findings[] | select(.snippet == "![missing](assets/missing.png)" and .line > 0)] | length == 1 + +### 2. Doctor uses the same checker + +```bash +set -eu +config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/skillshare" +if [ ! -f "$config_dir/config.yaml" ]; then + ss init -g --force --all-targets --no-git --no-skill >/dev/null +fi +fixture="$config_dir/skills/bundled-doctor" +mkdir -p "$fixture" +printf '%s\n' '---' 'name: bundled-doctor' 'description: Synthetic fixture' '---' '![missing](missing.png)' '[escape](../outside.md)' > "$fixture/SKILL.md" +ss doctor -g --json +``` + +Expected: +- exit_code: 1 +- jq: [.checks[] | select(.name == "bundled_references" and .status == "warning" and (.message | contains("dangling-link")))] | length == 1 +- jq: [.checks[] | select(.name == "bundled_references" and .status == "error" and (.message | contains("reference-escapes-root")))] | length == 1 + +### 3. Rule disables apply to audit and doctor + +```bash +set -eu +config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/skillshare" +if [ ! -f "$config_dir/config.yaml" ]; then + ss init -g --force --all-targets --no-git --no-skill >/dev/null +fi +fixture="$config_dir/skills/bundled-controls" +mkdir -p "$fixture" +printf '%s\n' '---' 'name: bundled-controls' 'description: Synthetic fixture' '---' '![missing](missing.png)' '[escape](../outside.md)' > "$fixture/SKILL.md" +cat > "$config_dir/audit-rules.yaml" <<'RULES' +rules: + - id: dangling-link + enabled: false + - id: reference-escapes-root + enabled: false +RULES +ss audit -g "$fixture" --analyzer structure --format json > "$TMPDIR/bundled-audit.json" +ss doctor -g --json > "$TMPDIR/bundled-doctor.json" || test "$?" -eq 1 +jq -n --slurpfile a "$TMPDIR/bundled-audit.json" --slurpfile d "$TMPDIR/bundled-doctor.json" '{audit: $a[0], doctor: $d[0]}' +``` + +Expected: +- exit_code: 0 +- jq: [.audit.results[].findings[]?] | length == 0 +- jq: [.doctor.checks[] | select(.name == "bundled_references")] | length == 0 + +### 4. Nested code paths preserve their explicit base + +```bash +set -eu +printf 'rules: []\n' > "${XDG_CONFIG_HOME:-$HOME/.config}/skillshare/audit-rules.yaml" +fixture="$(mktemp -d "$TMPDIR/bundled-nested.XXXXXX")" +outside="$(mktemp -d "$TMPDIR/bundled-nested-outside.XXXXXX")" +mkdir -p "$fixture/references" "$fixture/scripts" +printf '# Existing\n' > "$fixture/references/auth.md" +printf '# Synthetic script; never executed\n' > "$fixture/scripts/query_design.py" +printf '# Fixture\n' > "$fixture/SKILL.md" +ln -s "$outside" "$fixture/external.bundle" +printf '%s\n' '[sibling](auth.md)' \ + 'Read `references/auth.md` and `scripts/query_design.py`.' \ + 'Also run `../scripts/query_design.py` from here.' 'Sibling `./auth.md`.' \ + 'Read `../../outside.md`.' 'Read `path:external.bundle/missing.md`.' \ + '```skillshare-paths' 'references/auth.md' '../scripts/query_design.py' './auth.md' '```' \ + > "$fixture/references/app-flow.md" +ss audit -g "$fixture" --analyzer structure --format json +``` + +Expected: +- exit_code: 0 +- jq: [.results[].findings[] | select(.ruleId == "dangling-link")] | length == 0 +- jq: [.results[].findings[] | select(.ruleId == "reference-escapes-root" and .severity == "HIGH")] | length == 2 + +## Pass Criteria + +All four steps pass. All inputs are synthetic; referenced files are never executed. diff --git a/cmd/skillshare/doctor.go b/cmd/skillshare/doctor.go index 93bd08452..810e43665 100644 --- a/cmd/skillshare/doctor.go +++ b/cmd/skillshare/doctor.go @@ -214,7 +214,7 @@ func cmdDoctorProject(root string, jsonMode bool) error { Audit: rt.config.Audit, } - runDoctorChecks(cfg, result, true) + runDoctorChecks(cfg, result, true, root) checkExtras(rt.config.Extras, result, true, "", "", root, rt.config.EffectiveExtrasSource(root), func() error { return rt.config.ValidateExtras(root) }) checkNativeResources(nil, root, result) ui.Section("Storage") @@ -232,7 +232,7 @@ func cmdDoctorProject(root string, jsonMode bool) error { return nil } -func runDoctorChecks(cfg *config.Config, result *doctorResult, isProject bool) { +func runDoctorChecks(cfg *config.Config, result *doctorResult, isProject bool, projectRoots ...string) { // Single discovery pass for all checks (with .skillignore stats) sp := ui.StartSpinner("Discovering skills...") walk := cfg.SkillsWalk() @@ -256,6 +256,11 @@ func runDoctorChecks(cfg *config.Config, result *doctorResult, isProject bool) { checkSkillsValidity(cfg.EffectiveSkillsSource(), walk, result, discovered) checkSkillIntegrity(result, discovered, walk.Follow) + projectRoot := "" + if len(projectRoots) > 0 { + projectRoot = projectRoots[0] + } + checkSkillReferences(result, discovered, projectRoot, walk.Follow) checkSkillTargetsField(result, discovered, targetNamesFromConfig(cfg.Targets)) targetCache := checkTargets(cfg, result, isProject) printSymlinkCompatHint(cfg.Targets, cfg.Mode, isProject) diff --git a/cmd/skillshare/doctor_references.go b/cmd/skillshare/doctor_references.go new file mode 100644 index 000000000..d154d7929 --- /dev/null +++ b/cmd/skillshare/doctor_references.go @@ -0,0 +1,83 @@ +package main + +import ( + "fmt" + "strings" + + "skillshare/internal/audit" + "skillshare/internal/sourcewalk" + "skillshare/internal/sync" + "skillshare/internal/ui" +) + +// Use the audit structure analyzer and its normal rule loading in both modes. +func checkSkillReferences(result *doctorResult, skills []sync.DiscoveredSkill, projectRoot string, follow *sourcewalk.Follow) { + disabled := crossSkillDisabledIDs(projectRoot) + if disabled["dangling-link"] && disabled["reference-escapes-root"] && disabled["reference-check-incomplete"] { + if projectRoot != "" { + if _, err := audit.RulesWithProject(projectRoot); err != nil { + result.addWarning() + result.addCheck("bundled_references", checkWarning, "References: could not load rules", []string{err.Error()}) + return + } + } + result.addCheck("bundled_references", checkInfo, "Reference checks disabled", nil) + return + } + registry := audit.DefaultRegistry().ForPolicy(audit.Policy{EnabledAnalyzers: []string{audit.AnalyzerStructure}}) + var projectScans []audit.ScanOutput + var projectErr error + if projectRoot != "" { + paths := make([]string, len(skills)) + for i, skill := range skills { + paths[i] = skill.SourcePath + } + projectScans, projectErr = audit.ScanSkillsFilteredForProject(paths, projectRoot, registry, follow) + } else { + inputs := make([]audit.SkillInput, len(skills)) + for i, skill := range skills { + inputs[i] = audit.SkillInput{Name: skill.RelPath, Path: skill.SourcePath} + } + projectScans = audit.ParallelScan(inputs, "", nil, registry, follow) + } + if projectErr != nil && len(skills) == 0 { + result.addWarning() + result.addCheck("bundled_references", checkWarning, "References: could not load rules", []string{projectErr.Error()}) + return + } + checksBefore := len(result.checks) + for i, skill := range skills { + var scan *audit.Result + var err error + if projectErr != nil { + err = projectErr + } else { + scan, err = projectScans[i].Result, projectScans[i].Err + } + if err != nil { + result.addWarning() + result.addCheck("bundled_references", checkWarning, skill.RelPath+": references could not be checked", []string{err.Error()}) + ui.Row(ui.MarkWarn, "References", skill.RelPath+": could not check", doctorWidth) + continue + } + for _, f := range scan.Findings { + if f.Analyzer != audit.AnalyzerStructure { + continue + } + status, mark := checkWarning, ui.MarkWarn + if f.Severity == audit.SeverityHigh { + status, mark = checkError, ui.MarkFail + result.addError() + } else { + result.addWarning() + } + message := fmt.Sprintf("%s/%s:%d: %s: %s", skill.RelPath, f.File, f.Line, f.RuleID, f.Message) + result.addCheck("bundled_references", status, message, []string{strings.TrimSpace(f.Snippet)}) + ui.Row(mark, "References", message, doctorWidth) + } + } + if len(result.checks) == checksBefore { + result.addCheck("bundled_references", checkPass, "No broken bundled references", nil) + ui.Row(ui.MarkOK, "References", "No broken bundled references", doctorWidth) + } +} diff --git a/cmd/skillshare/doctor_references_test.go b/cmd/skillshare/doctor_references_test.go new file mode 100644 index 000000000..180f381fd --- /dev/null +++ b/cmd/skillshare/doctor_references_test.go @@ -0,0 +1,155 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/audit" + "skillshare/internal/sourcewalk" + "skillshare/internal/sync" +) + +func TestDoctorBundledReferences(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_DATA_HOME", t.TempDir()) + audit.ResetGlobalCache() + t.Cleanup(audit.ResetGlobalCache) + root := t.TempDir() + skill := filepath.Join(root, "fixture") + if err := os.Mkdir(skill, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(skill, "SKILL.md"), []byte("# Fixture\n![image](missing.png)\n[external](../outside.md)"), 0644); err != nil { + t.Fatal(err) + } + skills := []sync.DiscoveredSkill{{SourcePath: skill, RelPath: "fixture"}} + for _, project := range []bool{false, true} { + t.Run(map[bool]string{false: "global", true: "project"}[project], func(t *testing.T) { + projectRoot := "" + if project { + projectRoot = t.TempDir() + } + result := &doctorResult{} + captureStdout(t, func() { checkSkillReferences(result, skills, projectRoot, nil) }) + if result.errors != 1 || result.warnings != 1 || len(result.checks) != 2 { + t.Fatalf("doctor parity: %+v", result) + } + for _, rule := range []string{"dangling-link", "reference-escapes-root"} { + found := false + for _, c := range result.checks { + if strings.Contains(c.Message, rule) { + found = true + } + } + if !found { + t.Errorf("missing %s: %+v", rule, result.checks) + } + } + if !project { + return + } + if err := os.Mkdir(filepath.Join(projectRoot, ".skillshare"), 0755); err != nil { + t.Fatal(err) + } + rules := "rules:\n - id: reference-escapes-root\n enabled: false\n - id: dangling-link\n enabled: false\n" + if err := os.WriteFile(filepath.Join(projectRoot, ".skillshare", "audit-rules.yaml"), []byte(rules), 0644); err != nil { + t.Fatal(err) + } + result = &doctorResult{} + captureStdout(t, func() { checkSkillReferences(result, skills, projectRoot, nil) }) + if len(result.checks) != 1 || result.checks[0].Status != checkPass { + t.Fatalf("doctor ignored project controls: %+v", result) + } + }) + } +} + +func TestDoctorBundledReferencesCleanPass(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + audit.ResetGlobalCache() + t.Cleanup(audit.ResetGlobalCache) + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "SKILL.md"), []byte("# Clean\nText[^1]\n\n[^1]: Some note text\n"), 0644); err != nil { + t.Fatal(err) + } + result := &doctorResult{} + captureStdout(t, func() { + checkSkillReferences(result, []sync.DiscoveredSkill{{SourcePath: root, RelPath: "clean"}}, "", nil) + }) + if len(result.checks) != 1 || result.checks[0].Name != "bundled_references" || result.checks[0].Status != checkPass { + t.Fatalf("clean references: %+v", result.checks) + } +} + +func TestDoctorBundledReferencesFollowedSource(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + audit.ResetGlobalCache() + t.Cleanup(audit.ResetGlobalCache) + root := t.TempDir() + source, checkout := filepath.Join(root, "source"), filepath.Join(root, "checkout") + if err := os.MkdirAll(filepath.Join(checkout, "skill"), 0755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(source, 0755); err != nil { + t.Fatal(err) + } + logical := filepath.Join(source, "_linked") + if err := os.Symlink(checkout, logical); err != nil { + t.Skip(err) + } + if err := os.WriteFile(filepath.Join(checkout, "skill", "ok.md"), []byte("ok"), 0644); err != nil { + t.Fatal(err) + } + ref := filepath.ToSlash(filepath.Join(logical, "skill", "ok.md")) + if err := os.WriteFile(filepath.Join(checkout, "skill", "SKILL.md"), []byte("[ok]("+ref+")"), 0644); err != nil { + t.Fatal(err) + } + result := &doctorResult{} + captureStdout(t, func() { + checkSkillReferences(result, []sync.DiscoveredSkill{{SourcePath: filepath.Join(logical, "skill"), RelPath: "_linked/skill"}}, "", sourcewalk.NewFollow(source, nil)) + }) + if result.errors != 0 || result.warnings != 0 || len(result.checks) != 1 || result.checks[0].Status != checkPass { + t.Fatalf("followed source: %+v", result.checks) + } +} + +func TestDoctorBundledReferencesDisabledSkipsScanning(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + audit.ResetGlobalCache() + t.Cleanup(audit.ResetGlobalCache) + project := t.TempDir() + if err := os.MkdirAll(filepath.Join(project, ".skillshare"), 0755); err != nil { + t.Fatal(err) + } + data := "rules:\n - id: dangling-link\n enabled: false\n - id: reference-escapes-root\n enabled: false\n - id: reference-check-incomplete\n enabled: false\n" + if err := os.WriteFile(filepath.Join(project, ".skillshare", "audit-rules.yaml"), []byte(data), 0644); err != nil { + t.Fatal(err) + } + result := &doctorResult{} + captureStdout(t, func() { + checkSkillReferences(result, []sync.DiscoveredSkill{{SourcePath: filepath.Join(project, "missing"), RelPath: "missing"}}, project, nil) + }) + if result.errors != 0 || result.warnings != 0 || len(result.checks) != 1 || result.checks[0].Status != checkInfo { + t.Fatalf("disabled references: %+v", result.checks) + } +} + +func TestDoctorBundledReferencesInvalidProjectRulesWithoutSkills(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + audit.ResetGlobalCache() + t.Cleanup(audit.ResetGlobalCache) + project := t.TempDir() + if err := os.MkdirAll(filepath.Join(project, ".skillshare"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(project, ".skillshare", "audit-rules.yaml"), []byte("rules: ["), 0644); err != nil { + t.Fatal(err) + } + result := &doctorResult{} + captureStdout(t, func() { checkSkillReferences(result, nil, project, nil) }) + if len(result.checks) != 1 || result.checks[0].Status != checkWarning { + t.Fatalf("invalid rules reported clean: %+v", result.checks) + } +} diff --git a/internal/audit/analyzer_structure.go b/internal/audit/analyzer_structure.go index 6bd847d18..797127ea2 100644 --- a/internal/audit/analyzer_structure.go +++ b/internal/audit/analyzer_structure.go @@ -8,8 +8,19 @@ func (a *structureAnalyzer) ID() string { return AnalyzerStructure } func (a *structureAnalyzer) Scope() AnalyzerScope { return ScopeSkill } func (a *structureAnalyzer) Analyze(ctx *AnalyzeContext) ([]Finding, error) { - if ctx.DisabledIDs["dangling-link"] { + if ctx.DisabledIDs["dangling-link"] && ctx.DisabledIDs["reference-escapes-root"] && ctx.DisabledIDs["reference-check-incomplete"] { return nil, nil } - return checkDanglingLinks(ctx.MDFiles, ctx.MDLinks), nil + root := ctx.ReferenceRoot + if root == "" { + root = ctx.SkillPath + } + findings := checkBundledReferences(root, ctx.MDFiles, ctx.MDLinks, ctx.SkillPath) + kept := findings[:0] + for _, f := range findings { + if !ctx.DisabledIDs[f.RuleID] { + kept = append(kept, f) + } + } + return kept, nil } diff --git a/internal/audit/analyzers.go b/internal/audit/analyzers.go index ddbe192e2..7662361f9 100644 --- a/internal/audit/analyzers.go +++ b/internal/audit/analyzers.go @@ -35,13 +35,14 @@ type AnalyzeContext struct { IsShell bool // --- Skill-scope fields (populated after Walk completes) --- - SkillPath string - SourceURL string // git clone URL from .skillshare-meta.json (empty for local) - MDFiles []mdFileInfo - FileCache map[string][]byte - TierProfile TierProfile - MDLinks map[string][]markdownLink // pre-extracted links per md relPath - AllFiles map[string]bool // all walked file relPaths (for integrity) + ReferenceRoot string // physical bundle root for contained reference checks + SkillPath string + SourceURL string // git clone URL from .skillshare-meta.json (empty for local) + MDFiles []mdFileInfo + FileCache map[string][]byte + TierProfile TierProfile + MDLinks map[string][]markdownLink // pre-extracted links per md relPath + AllFiles map[string]bool // all walked file relPaths (for integrity) // --- Bundle-scope fields (populated after all skills scanned) --- Results []*Result diff --git a/internal/audit/audit_follow_test.go b/internal/audit/audit_follow_test.go index 9e0aafefc..25e98ab71 100644 --- a/internal/audit/audit_follow_test.go +++ b/internal/audit/audit_follow_test.go @@ -75,3 +75,48 @@ func TestScanSkillFollowedRootLogicalMetadata(t *testing.T) { } t.Fatalf("logical source metadata was not checked: %+v", result.Findings) } + +func TestScanSkillFollowedRootBundledReferencesAcceptLogicalSpellings(t *testing.T) { + source := t.TempDir() + target := t.TempDir() + asset := filepath.Join(target, "asset.md") + if err := os.WriteFile(asset, []byte("# Fixture"), 0644); err != nil { + t.Fatal(err) + } + outside := filepath.Join(source, "outside.md") + if err := os.WriteFile(outside, []byte("# Outside"), 0644); err != nil { + t.Fatal(err) + } + link := filepath.Join(source, "single-skill") + if err := os.Symlink(target, link); err != nil { + t.Skip(err) + } + if err := os.Symlink(filepath.Join(link, "asset.md"), filepath.Join(target, "internal-alias")); err != nil { + t.Skip(err) + } + content := "# Fixture\n" + + "[logical root](" + filepath.Join(link, "asset.md") + ")\n" + + "[internal alias](internal-alias)\n" + + "[outside](" + outside + ")\n" + if err := os.WriteFile(filepath.Join(target, "SKILL.md"), []byte(content), 0644); err != nil { + t.Fatal(err) + } + + result, err := ScanSkillWithFollow(link, sourcewalk.NewFollow(source, nil)) + if err != nil { + t.Fatal(err) + } + escapeFound := false + for _, finding := range result.Findings { + if finding.RuleID == "reference-escapes-root" && finding.Line == 4 { + escapeFound = true + continue + } + if finding.RuleID == "reference-escapes-root" || finding.RuleID == "dangling-link" { + t.Errorf("logical source spelling was rejected: %+v", finding) + } + } + if !escapeFound { + t.Fatalf("outside absolute reference was not rejected: %+v", result.Findings) + } +} diff --git a/internal/audit/audit_scan_skill.go b/internal/audit/audit_scan_skill.go index 3fce8e944..8f7cd2052 100644 --- a/internal/audit/audit_scan_skill.go +++ b/internal/audit/audit_scan_skill.go @@ -234,6 +234,7 @@ func scanSkillImpl(skillPath string, activeRules []rule, disabled map[string]boo // --- Skill-scope analyzers (via registry) --- result.TierProfile = skillTierProfile skillCtx := &AnalyzeContext{ + ReferenceRoot: skillPath, SkillPath: logicalPath, // Central metadata belongs to the logical source. MDFiles: mdFiles, FileCache: fileCache, @@ -584,3 +585,18 @@ func truncate(s string, maxLen int) string { } return s[:maxLen-3] + "..." } + +// ScanSkillsFilteredForProject loads project policy once for a set of skills. +// Results retain their input order and per-skill errors. +func ScanSkillsFilteredForProject(paths []string, projectRoot string, registry *Registry, follow *sourcewalk.Follow) ([]ScanOutput, error) { + rules, err := RulesWithProject(projectRoot) + if err != nil { + return nil, fmt.Errorf("load project rules: %w", err) + } + disabled := disabledIDsForProject(projectRoot) + outputs := make([]ScanOutput, len(paths)) + for i, path := range paths { + outputs[i].Result, outputs[i].Err = scanSkillImpl(path, rules, disabled, registry, follow) + } + return outputs, nil +} diff --git a/internal/audit/audit_scan_skill_test.go b/internal/audit/audit_scan_skill_test.go index 784730398..e551514d1 100644 --- a/internal/audit/audit_scan_skill_test.go +++ b/internal/audit/audit_scan_skill_test.go @@ -453,6 +453,32 @@ func TestScanSkill_ExternalLink_ReferenceStyleDetected(t *testing.T) { } } +func TestScanSkill_ExternalLink_ShortcutReferenceDetected(t *testing.T) { + dir := t.TempDir() + skillDir := filepath.Join(dir, "my-skill") + os.MkdirAll(skillDir, 0755) + os.WriteFile(filepath.Join(skillDir, "SKILL.md"), + []byte("# Skill\n\n[docs]\n\n[docs]: https://example.com/docs\n"), 0644) + + result, err := ScanSkill(skillDir) + if err != nil { + t.Fatal(err) + } + + var found bool + for _, f := range result.Findings { + if f.Pattern == "external-link" && f.Severity == "LOW" { + found = true + if f.Line != 3 { + t.Errorf("expected line 3, got %d", f.Line) + } + } + } + if !found { + t.Errorf("expected a LOW external-link finding for shortcut reference link, got findings: %+v", result.Findings) + } +} + func TestScanSkill_SourceRepoLink_FallsBackToExternalLinkLOW(t *testing.T) { dir := t.TempDir() skillDir := filepath.Join(dir, "repo-skill") diff --git a/internal/audit/bundled_references.go b/internal/audit/bundled_references.go new file mode 100644 index 000000000..73330dc8d --- /dev/null +++ b/internal/audit/bundled_references.go @@ -0,0 +1,397 @@ +package audit + +import ( + "fmt" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" +) + +const maxReferencePath = 4096 +const maxReferenceSteps = 256 + +// Code examples count as bundle dependencies only with these explicit prefixes. +var bundledLineSuffix = regexp.MustCompile(`:[0-9]+$`) + +var bundledCodePrefixes = []string{"./", "../", "scripts/", "references/", "assets/"} + +func bundledCodePath(s string) string { + s = filepath.ToSlash(s) + if strings.HasPrefix(s, "path:") { + return strings.TrimPrefix(s, "path:") + } + s = bundledLineSuffix.ReplaceAllString(s, "") + if strings.ContainsAny(s, " \t\r\n*?{}<>$") || len(filepath.Ext(s)) < 2 { + return "" + } + for _, prefix := range bundledCodePrefixes { + if strings.HasPrefix(s, prefix) { + return s + } + } + return "" +} + +type bundledReference struct { + markdownLink + fromRoot bool + implicit bool + markdown bool +} + +func extractBundledPaths(data []byte) []bundledReference { + var refs []bundledReference + fence, paths := "", false + for i, line := range strings.Split(string(data), "\n") { + trimmed := strings.TrimSpace(line) + if marker, ok := detectFenceMarker(line); ok { + if fence == "" { + fence, paths = marker, strings.TrimSpace(strings.TrimPrefix(trimmed, marker)) == "skillshare-paths" + } else if marker == fence { + fence, paths = "", false + } + continue + } + add := func(target string, implicit bool) { + if target != "" { + portable := filepath.ToSlash(target) + fromRoot := !strings.HasPrefix(portable, "./") && !strings.HasPrefix(portable, "../") + refs = append(refs, bundledReference{markdownLink: markdownLink{target: target, line: i + 1, snippet: trimmed}, fromRoot: fromRoot, implicit: implicit}) + } + } + if fence != "" { + if paths { + add(strings.TrimPrefix(trimmed, "path:"), false) + } + continue + } + for _, span := range inlineCodeSpans(line) { + code := strings.Trim(line[span.start:span.end], "`") + add(bundledCodePath(code), !strings.HasPrefix(code, "path:")) + } + } + return refs +} + +func extractMarkdownImageLinks(data []byte) []markdownLink { + lines := strings.Split(string(data), "\n") + defs := parseReferenceDefinitions(lines) + var links []markdownLink + inCodeFence, fenceMarker := false, "" + for i, line := range lines { + if marker, ok := detectFenceMarker(line); ok { + if !inCodeFence { + inCodeFence, fenceMarker = true, marker + continue + } + if marker == fenceMarker { + inCodeFence, fenceMarker = false, "" + continue + } + } + if inCodeFence { + continue + } + + codeSpans := inlineCodeSpans(line) + for start := 0; start+1 < len(line); start++ { + if line[start] != '!' || line[start+1] != '[' || isEscapedMarkdownAt(line, start) || indexInSpans(start, codeSpans) { + continue + } + labelEnd := findMatchingBracket(line, start+1) + if labelEnd == -1 { + continue + } + label := line[start+2 : labelEnd] + next := labelEnd + 1 + target := "" + if next < len(line) && line[next] == '(' { + inside, linkEnd := readParenthesized(line, next) + if linkEnd != -1 { + target = parseMarkdownLinkTarget(inside) + } + } else if next < len(line) && line[next] == '[' { + refEnd := findMatchingBracket(line, next) + if refEnd != -1 { + ref := strings.TrimSpace(line[next+1 : refEnd]) + if ref == "" { + ref = label + } + target = defs[normalizeReferenceLabel(ref)] + } + } else if strings.TrimSpace(line[next:]) == "" && i+1 < len(lines) { + // Preserve multiline destinations supported by the prior image + // parser, while keeping image extraction independent of outer links. + imageLine := line[:start] + line[start+1:] + if multiline, ok := extractMultilineLink(imageLine, lines[i+1], i+1); ok { + target = multiline.target + } + if target == "" { + target = defs[normalizeReferenceLabel(label)] + } + } else { + // Shortcut image references use the image text as the definition label. + target = defs[normalizeReferenceLabel(label)] + } + if target != "" { + links = append(links, markdownLink{ + label: label, + target: target, + line: i + 1, + snippet: strings.TrimSpace(line), + }) + } + } + } + return links +} + +func checkBundledReferences(root string, files []mdFileInfo, mdLinks map[string][]markdownLink, logicalRoots ...string) []Finding { + checker := newBundledPathChecker(root, logicalRoots...) + var findings []Finding + for _, f := range files { + links := mdLinks[f.relPath] + if mdLinks == nil { + links = extractMarkdownLinks(f.data) + } + // Images use the same target grammar; keep static URL rule behavior unchanged. + links = append([]markdownLink(nil), links...) + links = append(links, extractMarkdownImageLinks(f.data)...) + refs := make([]bundledReference, 0, len(links)) + for _, link := range links { + refs = append(refs, bundledReference{markdownLink: link, markdown: true}) + } + refs = append(refs, extractBundledPaths(f.data)...) + seen := map[string]bool{} + for _, link := range refs { + key := fmt.Sprintf("%d|%t|%t|%t|%s", link.line, link.fromRoot, link.implicit, link.markdown, link.target) + if seen[key] { + continue + } + seen[key] = true + target := link.target + // A drive letter is a path, not a URI scheme, on every host. + drive := isDriveReference(target) + if !drive && isExternalOrAnchor(target) { + continue + } + raw := stripFragment(target) + if raw == "" { + continue + } + inspect := func(path string) string { + if !link.fromRoot && !strings.HasPrefix(filepath.ToSlash(path), "/") && !filepath.IsAbs(path) && !isDriveReference(path) && !strings.HasPrefix(path, "~/") { + path = filepath.Join(filepath.Dir(f.relPath), ".") + string(filepath.Separator) + path + } + return checker.inspect(path) + } + status := "" + if decoded, err := url.PathUnescape(raw); link.markdown && err == nil && decoded != raw { + status = inspect(decoded) + if status == "dangling-link" { + if rawStatus := inspect(raw); rawStatus != "dangling-link" { + status = rawStatus + } + } + } else { + status = inspect(raw) + } + if status == "" || (link.implicit && status == "reference-escapes-root") { + continue + } + severity, message := SeverityLow, "broken local link" + if status == "reference-escapes-root" { + severity, message = SeverityHigh, "reference escapes skill root" + } + if status == "reference-check-incomplete" { + message = "reference could not be checked (unreadable, unsupported, or resolution limit)" + } + message = fmt.Sprintf("%s: %q", message, link.target) + if status == "dangling-link" { + message += " not found" + } + findings = append(findings, Finding{Severity: severity, Pattern: status, RuleID: status, Message: message, File: f.relPath, Line: link.line, Snippet: link.snippet, Analyzer: AnalyzerStructure, Category: CategoryStructure, Confidence: 1}) + } + } + return findings +} + +func isDriveReference(target string) bool { + return len(target) > 1 && target[1] == ':' && (target[0] >= 'A' && target[0] <= 'Z' || target[0] >= 'a' && target[0] <= 'z') +} + +type bundledPathChecker struct { + root string + spellings []string +} + +func newBundledPathChecker(root string, logicalRoots ...string) bundledPathChecker { + absoluteRoot, err := filepath.Abs(root) + if err != nil { + return bundledPathChecker{} + } + // Resolve only the declared root and its ancestors, never a referenced + // target. Cache equivalent root spellings once per scan. + physicalRoot, err := filepath.EvalSymlinks(absoluteRoot) + if err != nil { + return bundledPathChecker{} + } + spellings := []string{absoluteRoot, physicalRoot} + for _, logicalRoot := range logicalRoots { + if logicalRoot == "" { + continue + } + logicalAbsolute, err := filepath.Abs(logicalRoot) + if err != nil { + continue + } + logicalPhysical, err := filepath.EvalSymlinks(logicalAbsolute) + if err != nil { + continue + } + if relative, ok := bundledAbsoluteRelative(physicalRoot, logicalPhysical); ok && relative == "." { + spellings = append(spellings, logicalAbsolute) + } + } + for parent, steps := filepath.Dir(absoluteRoot), 0; steps < maxReferenceSteps; steps++ { + physicalParent, err := filepath.EvalSymlinks(parent) + if err != nil { + return bundledPathChecker{} + } + // Preserve a symlinked parent's spelling with the physical root's + // suffix (e.g. /var/.../bundle instead of /private/var/.../bundle). + if suffix, ok := bundledAbsoluteRelative(physicalParent, physicalRoot); ok { + spellings = append(spellings, filepath.Join(parent, suffix)) + } + if suffix, ok := bundledAbsoluteRelative(parent, absoluteRoot); ok { + spellings = append(spellings, filepath.Join(physicalParent, suffix)) + } + next := filepath.Dir(parent) + if next == parent { + return bundledPathChecker{root: absoluteRoot, spellings: spellings} + } + parent = next + } + return bundledPathChecker{} +} + +func (c bundledPathChecker) absoluteRelative(target string) (string, bool) { + for _, root := range c.spellings { + if relative, ok := bundledAbsoluteRelative(root, target); ok { + return relative, true + } + } + return "", false +} + +func inspectBundledPath(root, target string) string { + return newBundledPathChecker(root).inspect(target) +} + +// inspect never opens a referenced file. Root's containment checks also +// protect component operations against concurrent symlink replacement. +func (c bundledPathChecker) inspect(target string) string { + target = filepath.ToSlash(target) + if (strings.HasPrefix(target, "/") || isDriveReference(target)) && !filepath.IsAbs(target) || strings.HasPrefix(target, "~/") { + return "reference-escapes-root" + } + if len(target) > maxReferencePath || strings.ContainsAny(target, "\x00\\") { + return "reference-check-incomplete" + } + if c.root == "" { + return "reference-check-incomplete" + } + if filepath.IsAbs(target) { + relative, ok := c.absoluteRelative(target) + if !ok { + return "reference-escapes-root" + } + target = relative + } + dir, err := os.OpenRoot(c.root) + if err != nil { + return "reference-check-incomplete" + } + defer dir.Close() + parts := strings.Split(filepath.ToSlash(target), "/") + var resolved []string + links := 0 + for step := 0; len(parts) > 0; step++ { + if step >= maxReferenceSteps { + return "reference-check-incomplete" + } + part := parts[0] + parts = parts[1:] + if part == "" || part == "." { + continue + } + if part == ".." { + if len(resolved) == 0 { + return "reference-escapes-root" + } + resolved = resolved[:len(resolved)-1] + continue + } + name := filepath.Join(append(append([]string(nil), resolved...), part)...) + info, err := dir.Lstat(name) + if os.IsNotExist(err) { + return "dangling-link" + } + if err != nil { + return "reference-check-incomplete" + } + if info.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 { + links++ + if links > 40 { + return "reference-check-incomplete" + } + dest, err := dir.Readlink(name) + if err != nil { + return "reference-check-incomplete" + } + dest = filepath.ToSlash(dest) + if (strings.HasPrefix(dest, "/") || isDriveReference(dest)) && !filepath.IsAbs(dest) { + return "reference-escapes-root" + } + if filepath.IsAbs(dest) { + relative, ok := c.absoluteRelative(dest) + if !ok { + return "reference-escapes-root" + } + resolved, dest = nil, relative + } + if len(dest) > maxReferencePath || strings.ContainsAny(dest, "\x00\\") { + return "reference-check-incomplete" + } + parts = append(strings.Split(filepath.ToSlash(dest), "/"), parts...) + continue + } + if len(parts) > 0 && !info.IsDir() { + return "dangling-link" + } + resolved = append(resolved, part) + } + return "" +} + +// Strip only the declared root prefix. filepath.Rel would clean away symlink/.. +// pairs before the component walker can inspect them. +func bundledAbsoluteRelative(root, target string) (string, bool) { + root, target = filepath.ToSlash(root), filepath.ToSlash(target) + equal := func(a, b string) bool { + if filepath.Separator == '\\' { + return strings.EqualFold(a, b) + } + return a == b + } + if equal(root, target) { + return ".", true + } + prefix := strings.TrimRight(root, "/") + "/" + if len(target) < len(prefix) || !equal(target[:len(prefix)], prefix) { + return "", false + } + return target[len(prefix):], true +} diff --git a/internal/audit/bundled_references_scan_test.go b/internal/audit/bundled_references_scan_test.go new file mode 100644 index 000000000..da34d16a0 --- /dev/null +++ b/internal/audit/bundled_references_scan_test.go @@ -0,0 +1,21 @@ +package audit + +import ( + "os" + "path/filepath" + "testing" +) + +func TestScanSkillBundledReferenceEscape(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "SKILL.md"), []byte("# Fixture\n[required](../outside.md)\n"), 0644); err != nil { + t.Fatal(err) + } + scan, err := ScanSkillWithRules(root, nil) + if err != nil { + t.Fatal(err) + } + if !hasFinding(scan.Findings, "reference-escapes-root", SeverityHigh) { + t.Fatalf("missing HIGH escape finding: %+v", scan.Findings) + } +} diff --git a/internal/audit/bundled_references_test.go b/internal/audit/bundled_references_test.go new file mode 100644 index 000000000..1882c4473 --- /dev/null +++ b/internal/audit/bundled_references_test.go @@ -0,0 +1,356 @@ +package audit + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestBundledReferences(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "references"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "references", "ok.md"), []byte("safe"), 0644); err != nil { + t.Fatal(err) + } + for _, name := range []string{"100%.md", "a%20b.md", "space name.md"} { + if err := os.WriteFile(filepath.Join(root, name), []byte("safe"), 0644); err != nil { + t.Fatal(err) + } + } + outside := t.TempDir() + for name, target := range map[string]string{"drive-relative": "C:outside.md", "internal": "references", "external": outside, "absolute-internal": filepath.Join(root, "references"), "loop": "loop", "broken": "absent"} { + if err := os.Symlink(target, filepath.Join(root, name)); err != nil { + t.Fatal(err) + } + } + cases := []struct{ name, text, rule string }{ + {"missing link", "[read](references/missing.md)", "dangling-link"}, + {"percent literal", "[read](100%.md)", ""}, + {"encoded literal fallback", "[read](a%20b.md)", ""}, + {"decoded markdown link", "[read](space%20name.md)", ""}, + {"code literal percent", "Read `path:a%20b.md`", ""}, + {"fence literal percent", "```skillshare-paths\na%20b.md\n```", ""}, + {"existing link", "[read](references/ok.md#part)", ""}, + {"missing image", "![preview](assets/missing.png)", "dangling-link"}, + {"existing image", "![preview](references/ok.md)", ""}, + {"linked image escape", "[![preview](../outside.png)](https://example.invalid)", "reference-escapes-root"}, + {"linked image inside root", "[![preview](references/ok.md)](https://example.invalid)", ""}, + {"multiline image escape", "![preview]\n(../outside.png)", "reference-escapes-root"}, + {"multiline image inside root", "![preview]\n(references/ok.md)", ""}, + {"reference image", "![preview][asset]\n\n[asset]: assets/missing.png", "dangling-link"}, + {"shortcut reference image escape", "![preview]\n\n[preview]: ../outside.png", "reference-escapes-root"}, + {"shortcut reference image inside root", "![preview]\n\n[preview]: references/ok.md", ""}, + {"shortcut reference image missing", "![preview]\n\n[preview]: references/missing.png", "dangling-link"}, + {"shortcut reference link escape", "[read]\n\n[read]: ../outside.md", "reference-escapes-root"}, + {"shortcut reference link inside root", "[read]\n\n[read]: references/ok.md", ""}, + {"shortcut reference link missing", "[read]\n\n[read]: references/missing.md", "dangling-link"}, + {"inline link takes precedence over same-label definition", "[read](references/ok.md)\n\n[read]: ../outside.md", ""}, + {"inline image takes precedence over same-label definition", "![preview](references/ok.md)\n\n[preview]: ../outside.png", ""}, + {"shortcut-looking link title is not a reference", "[open](references/ok.md \"[read]\")\n\n[read]: ../outside.md", ""}, + {"shortcut-looking image title is not a reference", "![preview](references/ok.md \"[read]\")\n\n[read]: ../outside.png", ""}, + {"shortcut-looking multiline link title is not a reference", "[open]\n(references/ok.md \"[read]\")\n\n[read]: ../outside.md", ""}, + {"shortcut-looking multiline image title is not a reference", "![preview]\n(references/ok.md \"[read]\")\n\n[read]: ../outside.png", ""}, + {"active shortcut beside inline title is still checked", "[open](references/ok.md \"[read]\") [read]\n\n[read]: ../outside.md", "reference-escapes-root"}, + {"escaped shortcut link remains literal", "\\[read]\n\n[read]: ../outside.md", ""}, + {"escaped backslash leaves shortcut link active", "\\\\[read]\n\n[read]: ../outside.md", "reference-escapes-root"}, + {"escaped image marker leaves shortcut link active", "\\![preview]\n\n[preview]: ../outside.png", "reference-escapes-root"}, + {"code path", "Read `./missing.md`.", "dangling-link"}, + {"common directory", "Read `references/missing.md`.", "dangling-link"}, + {"explicit path", "Read `path:missing.md`.", "dangling-link"}, + {"prefix examples", "Use `./`, `../`, `scripts/`, `references/`, `assets/`.", ""}, + {"extensionless example", "Use `./path`.", ""}, + {"glob example", "Use `./*.md`.", ""}, + {"template example", "Use `./.md`.", ""}, + {"explicit directory", "Read `path:references/`.", ""}, + {"explicit directory escape", "Read `path:../`.", "reference-escapes-root"}, + {"explicit extensionless", "Read `path:missing`.", "dangling-link"}, + {"code benign twin", "Use `missing.md` or `some.identifier`.", ""}, + {"path fence", "```skillshare-paths\nreferences/missing.md\n```", "dangling-link"}, + {"ordinary fence", "```sh\n./missing.md\n```", ""}, + {"absolute example", "Example: `/example/config.json`", ""}, + {"required absolute", "[read](/example/config.json)", "reference-escapes-root"}, + {"explicit absolute", "Read `path:/example/config.json`", "reference-escapes-root"}, + {"parent escape", "[read](../missing.md)", "reference-escapes-root"}, + {"encoded parent escape", "[read](%2e%2e/missing.md)", "reference-escapes-root"}, + {"home escape", "[read](~/.synthetic/config)", "reference-escapes-root"}, + {"drive relative escape", "[read](C:outside.md)", "reference-escapes-root"}, + {"windows escape", "[read](C:/synthetic/config)", "reference-escapes-root"}, + {"symlinked parent", "[read](external/missing.md)", "reference-escapes-root"}, + {"symlink then parent", "[read](external/../references/ok.md)", "reference-escapes-root"}, + {"absolute internal symlink", "[read](absolute-internal/ok.md)", ""}, + {"absolute symlink then parent", "[read](" + root + "/external/../references/ok.md)", "reference-escapes-root"}, + {"absolute internal path", "[read](" + filepath.Join(root, "references", "ok.md") + ")", ""}, + {"windows backslash escape", "[read](C:\\synthetic\\config)", "reference-escapes-root"}, + {"internal symlink", "[read](internal/ok.md)", ""}, + {"broken symlink", "[read](broken)", "dangling-link"}, + {"drive relative symlink", "[read](drive-relative)", "reference-escapes-root"}, + {"symlink cycle", "[read](loop)", "reference-check-incomplete"}, + {"external exceptions", "[web](https://example.invalid/path) [anchor](#here) [uri](vscode:example)", ""}, + } + if filepath.Separator == '\\' { + cases = append(cases, struct{ name, text, rule string }{"native code path", "Read `references\\missing.md`", "dangling-link"}) + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + findings := checkBundledReferences(root, []mdFileInfo{{relPath: "SKILL.md", absDir: root, data: []byte(tc.text)}}, nil) + if tc.rule == "" { + if len(findings) != 0 { + t.Fatalf("unexpected: %+v", findings) + } + return + } + if len(findings) != 1 || findings[0].RuleID != tc.rule { + t.Fatalf("want %s, got %+v", tc.rule, findings) + } + f := findings[0] + if f.File != "SKILL.md" || f.Line != 1 && tc.name != "path fence" || !strings.Contains(tc.text, f.Snippet) { + t.Fatalf("lost evidence: %+v", f) + } + if tc.rule == "reference-escapes-root" && f.Severity != SeverityHigh { + t.Fatalf("escape severity: %+v", f) + } + }) + } +} + +func TestBundledReferencesControlsAndNestedRoot(t *testing.T) { + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "references"), 0755); err != nil { + t.Fatal(err) + } + files := []mdFileInfo{{relPath: "references/guide.md", absDir: filepath.Join(root, "references"), data: []byte("[inside](../SKILL.md) [outside](../../outside)")}} + if err := os.WriteFile(filepath.Join(root, "SKILL.md"), []byte("# fixture"), 0644); err != nil { + t.Fatal(err) + } + for _, disabled := range []map[string]bool{nil, {"reference-escapes-root": true}, {"dangling-link": true}} { + ctx := &AnalyzeContext{SkillPath: root, MDFiles: files, DisabledIDs: disabled} + findings, err := (&structureAnalyzer{}).Analyze(ctx) + if err != nil { + t.Fatal(err) + } + want := 1 + if disabled["reference-escapes-root"] { + want = 0 + } + if len(findings) != want { + t.Fatalf("disabled=%v: %+v", disabled, findings) + } + } +} + +func TestBundledReferencesNestedCodePaths(t *testing.T) { + root, outside := t.TempDir(), t.TempDir() + for _, dir := range []string{"references", "scripts", "assets"} { + if err := os.Mkdir(filepath.Join(root, dir), 0755); err != nil { + t.Fatal(err) + } + } + for _, file := range []string{"references/auth.md", "scripts/query_design.py", "assets/preview.png"} { + if err := os.WriteFile(filepath.Join(root, file), []byte("synthetic fixture"), 0644); err != nil { + t.Fatal(err) + } + } + if err := os.Symlink(outside, filepath.Join(root, "references", "external.md")); err != nil { + t.Fatal(err) + } + cases := []struct{ target, rule string }{ + {"references/auth.md", ""}, + {"scripts/query_design.py", ""}, + {"assets/preview.png", ""}, + {"../scripts/query_design.py", ""}, + {"./auth.md", ""}, + {"./missing.md", "dangling-link"}, + {"../scripts/missing.py", "dangling-link"}, + {"references/missing.md", "dangling-link"}, + {"../../outside.md", "reference-escapes-root"}, + {"./external.md", "reference-escapes-root"}, + {"./external.md/../auth.md", "reference-escapes-root"}, + {"references/external.md", "reference-escapes-root"}, + } + if filepath.Separator == '\\' { + cases = append(cases, []struct{ target, rule string }{ + {`..\scripts\query_design.py`, ""}, + {`.\auth.md`, ""}, + {`..\scripts\missing.py`, "dangling-link"}, + {`..\..\outside.md`, "reference-escapes-root"}, + }...) + } + for _, tc := range cases { + for _, text := range []string{"See `" + tc.target + "`.", "See `path:" + tc.target + "`.", "```skillshare-paths\n" + tc.target + "\n```"} { + t.Run(text, func(t *testing.T) { + files := []mdFileInfo{{relPath: "references/app-flow.md", data: []byte(text)}} + findings := checkBundledReferences(root, files, nil) + want := tc.rule + if want == "reference-escapes-root" && strings.HasPrefix(text, "See `") && !strings.HasPrefix(text, "See `path:") { + want = "" + } + if want == "" { + if len(findings) != 0 { + t.Fatalf("unexpected bundle reference: %+v", findings) + } + } else if len(findings) != 1 || findings[0].RuleID != want { + t.Fatalf("want %s, got %+v", want, findings) + } + }) + } + } + // Markdown links/images retain document-relative resolution, even when + // the same target is also declared as a code path on the same source line. + files := []mdFileInfo{{relPath: "references/app-flow.md", data: []byte("[local](auth.md) ![image](../assets/preview.png)\n`references/auth.md` [missing](references/auth.md)")}} + findings := checkBundledReferences(root, files, nil) + if len(findings) != 1 || findings[0].RuleID != "dangling-link" || findings[0].Line != 2 || findings[0].Message != `broken local link: "references/auth.md" not found` { + t.Fatalf("Markdown resolution or missing-target message changed: %+v", findings) + } +} + +func TestBundledReferencesSymlinkedRoot(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "bundle") + if err := os.Mkdir(root, 0755); err != nil { + t.Fatal(err) + } + target := filepath.Join(root, "ok.md") + if err := os.WriteFile(target, []byte("synthetic fixture"), 0644); err != nil { + t.Fatal(err) + } + alias := filepath.Join(parent, "alias") + if err := os.Symlink(root, alias); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, filepath.Join(root, "internal")); err != nil { + t.Fatal(err) + } + for _, path := range []string{target, filepath.Join(alias, "ok.md"), "internal", root + "/../outside.md"} { + want := "" + if strings.Contains(path, "/../") { + want = "reference-escapes-root" + } + if got := inspectBundledPath(alias, path); got != want { + t.Errorf("symlinked root: %q classified %q, want %q", path, got, want) + } + } +} + +func TestBundledReferencesSymlinkedParentSpellings(t *testing.T) { + parent := t.TempDir() + physicalParent, err := filepath.EvalSymlinks(parent) + if err != nil { + t.Fatal(err) + } + root := filepath.Join(physicalParent, "physical", "bundle") + if err := os.MkdirAll(root, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "ok.md"), []byte("synthetic fixture"), 0644); err != nil { + t.Fatal(err) + } + parentAlias := filepath.Join(parent, "parent-alias") + for link, dest := range map[string]string{ + parentAlias: filepath.Join(physicalParent, "physical"), + filepath.Join(physicalParent, "physical", "source-alias"): root, + filepath.Join(root, "internal"): filepath.Join(parentAlias, "bundle", "ok.md"), + filepath.Join(root, "external"): t.TempDir(), + } { + if err := os.Symlink(dest, link); err != nil { + t.Fatal(err) + } + } + checker := newBundledPathChecker(filepath.Join(parentAlias, "source-alias")) + for _, spelling := range []string{ + filepath.Join(parentAlias, "bundle"), + filepath.Join(parent, "physical", "bundle"), + root, + } { + for _, tc := range []struct{ suffix, rule string }{ + {"ok.md", ""}, {"internal", ""}, {"missing.md", "dangling-link"}, + {"../outside.md", "reference-escapes-root"}, + {"external/../ok.md", "reference-escapes-root"}, + } { + // Keep symlink/.. components intact for the containment walker. + target := spelling + "/" + tc.suffix + if got := checker.inspect(target); got != tc.rule { + t.Errorf("%q classified %q, want %q", target, got, tc.rule) + } + } + } +} + +func FuzzBundledReferenceContainment(f *testing.F) { + for _, p := range []string{"../escape", "external/../safe", "./ok", "%2e%2e/escape"} { + f.Add(p) + } + root := f.TempDir() + alias := filepath.Join(f.TempDir(), "alias") + if err := os.Symlink(root, alias); err != nil { + f.Fatal(err) + } + checker := newBundledPathChecker(alias) + f.Fuzz(func(t *testing.T, target string) { + // Equivalent root spellings must preserve the component walk's result, + // including missing paths, traversal, and unsupported path syntax. + absolute := root + "/" + target + if !filepath.IsAbs(target) && !isDriveReference(target) && !strings.HasPrefix(target, "~/") && len(absolute) <= maxReferencePath { + if got, want := checker.inspect(absolute), checker.inspect(target); got != want { + t.Fatalf("root spelling changed %q: %s != %s", target, got, want) + } + } + // Lexical parent escapes must never become existence checks outside root. + if !strings.HasPrefix(target, "../") || strings.ContainsAny(target, "\x00?#%\\") { + return + } + status := inspectBundledPath(root, target) + if status != "reference-escapes-root" { + t.Fatalf("escape %q classified %q", target, status) + } + }) +} + +func TestBundledReferenceLimits(t *testing.T) { + root := t.TempDir() + for _, target := range []string{strings.Repeat("x", maxReferencePath+1), strings.Repeat("./", maxReferenceSteps+1)} { + if got := inspectBundledPath(root, target); got != "reference-check-incomplete" { + t.Errorf("limit/unsupported path classified %q", got) + } + } + if got := inspectBundledPath(root, `unsupported\path`); filepath.Separator == '\\' { + if got != "dangling-link" { + t.Errorf("native Windows path classified %q, want dangling-link", got) + } + } else if got != "reference-check-incomplete" { + t.Errorf("unsupported path classified %q, want reference-check-incomplete", got) + } + if got := inspectBundledPath(filepath.Join(root, "missing-root"), "file"); got != "reference-check-incomplete" { + t.Fatalf("unavailable root: %s", got) + } +} + +func TestExtractMarkdownLinksMultilineDestinationKeepsSiblingReference(t *testing.T) { + data := []byte("[open]\n(references/ok.md) ([read][ref])\n\n[ref]: ../outside.md\n") + got := map[string]bool{} + for _, link := range extractMarkdownLinks(data) { + got[link.target] = true + } + for _, want := range []string{"references/ok.md", "../outside.md"} { + if !got[want] { + t.Errorf("missing link target %q in %v", want, got) + } + } +} + +func TestBundledReferenceMaintainerCases(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "scripts"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "scripts", "foo.py"), []byte("pass"), 0644); err != nil { + t.Fatal(err) + } + text := "Text[^1]\n\n[^1]: Some note text\n\nEdit `../package.json` and see `../../CLAUDE.md`.\nRead `scripts/foo.py:12`.\n" + files := []mdFileInfo{{relPath: "SKILL.md", absDir: root, data: []byte(text)}} + if findings := checkBundledReferences(root, files, nil); len(findings) != 0 { + t.Fatalf("ordinary docs: %+v", findings) + } +} diff --git a/internal/audit/markdown_links.go b/internal/audit/markdown_links.go index 74d6d0f21..84ad90ebf 100644 --- a/internal/audit/markdown_links.go +++ b/internal/audit/markdown_links.go @@ -2,8 +2,6 @@ package audit import ( "fmt" - "os" - "path/filepath" "regexp" "strings" "sync" @@ -31,7 +29,7 @@ func globalSplitMarkdownLinkRules() (contentRules []rule, linkRules []rule) { var ( mdAutoLinkRe = regexp.MustCompile(`<((?:https?://)[^>\s]+)>`) - mdRefLinkRe = regexp.MustCompile(`\[([^\]]+)\]\[([^\]]*)\]`) + mdRefLinkRe = regexp.MustCompile(`\[([^\]]+)\](?:\[([^\]]*)\])?`) mdHTMLAnchorRe = regexp.MustCompile(`(?i)]*\bhref\s*=\s*["']([^"']+)["'][^>]*>(.*?)`) mdHTMLTagStrip = regexp.MustCompile(`(?s)<[^>]*>`) mdTutorialMarkerRe = regexp.MustCompile(`(?i)(for\s+example|e\.g\.|example:|examples:|sample:|original:|attacker:|safe:|unsafe:|vulnerable:|pattern:|ruleid:|ok:|sink:|message:)`) @@ -107,46 +105,6 @@ func checkMarkdownLinkRules(files []mdFileInfo, mdLinks map[string][]markdownLin return findings } -// checkDanglingLinks scans collected .md file data for local relative links -// whose targets do not exist on disk. Returns LOW-severity findings. -func checkDanglingLinks(files []mdFileInfo, mdLinks map[string][]markdownLink) []Finding { - var findings []Finding - for _, f := range files { - var links []markdownLink - if mdLinks != nil { - links = mdLinks[f.relPath] - } else { - links = extractMarkdownLinks(f.data) - } - for _, link := range links { - target := link.target - if isExternalOrAnchor(target) { - continue - } - cleaned := stripFragment(target) - if cleaned == "" { - continue - } - abs := filepath.Join(f.absDir, cleaned) - if _, err := os.Stat(abs); err != nil { - findings = append(findings, Finding{ - Severity: SeverityLow, - Pattern: "dangling-link", - Message: fmt.Sprintf("broken local link: %q not found", target), - File: f.relPath, - Line: link.line, - Snippet: link.snippet, - RuleID: "dangling-link", - Analyzer: AnalyzerStructure, - Category: CategoryStructure, - Confidence: 1.0, - }) - } - } - } - return findings -} - func extractMarkdownLinks(data []byte) []markdownLink { lines := strings.Split(string(data), "\n") defs := parseReferenceDefinitions(lines) @@ -186,13 +144,19 @@ func extractMarkdownLinks(data []byte) []markdownLink { } codeSpans := inlineCodeSpans(line) - for _, link := range extractInlineLinksFromLine(line, lineNum, codeSpans) { + inlineLinks, inlineLinkSpans := extractInlineLinksFromLine(line, lineNum, codeSpans) + if i > 0 { + if targetSpan, ok := multilineLinkTargetSpan(lines[i-1], line); ok { + inlineLinkSpans = append(inlineLinkSpans, targetSpan) + } + } + for _, link := range inlineLinks { add(link) } for _, link := range extractAutoLinksFromLine(line, lineNum, codeSpans) { add(link) } - for _, link := range extractReferenceLinksFromLine(line, lineNum, defs, codeSpans) { + for _, link := range extractReferenceLinksFromLine(line, lineNum, defs, codeSpans, inlineLinkSpans) { add(link) } for _, link := range extractHTMLAnchorLinksFromLine(line, lineNum, codeSpans) { @@ -242,7 +206,7 @@ func parseReferenceDefinitions(lines []string) map[string]string { continue } label := normalizeReferenceLabel(trimmed[1:idx]) - if label == "" { + if label == "" || strings.HasPrefix(label, "^") { continue } target := parseMarkdownLinkTarget(strings.TrimSpace(trimmed[idx+2:])) @@ -258,8 +222,9 @@ func normalizeReferenceLabel(label string) string { return strings.ToLower(strings.Join(strings.Fields(strings.TrimSpace(label)), " ")) } -func extractInlineLinksFromLine(line string, lineNum int, codeSpans []span) []markdownLink { +func extractInlineLinksFromLine(line string, lineNum int, codeSpans []span) ([]markdownLink, []span) { var links []markdownLink + var inlineLinkSpans []span for i := 0; i < len(line); i++ { if line[i] != '[' { @@ -268,10 +233,7 @@ func extractInlineLinksFromLine(line string, lineNum int, codeSpans []span) []ma if indexInSpans(i, codeSpans) { continue } - if i > 0 && line[i-1] == '!' && !indexInSpans(i-1, codeSpans) { - // Image link: ![alt](url) - continue - } + isImage := i > 0 && line[i-1] == '!' && !indexInSpans(i-1, codeSpans) labelEnd := findMatchingBracket(line, i) if labelEnd == -1 { continue @@ -289,6 +251,14 @@ func extractInlineLinksFromLine(line string, lineNum int, codeSpans []span) []ma continue } + if !isEscapedMarkdownAt(line, i) { + inlineLinkSpans = append(inlineLinkSpans, span{start: i, end: linkEnd + 1}) + } + if isImage { + i = linkEnd + continue + } + label := strings.TrimSpace(line[i+1 : labelEnd]) target := parseMarkdownLinkTarget(inside) if target != "" { @@ -303,7 +273,7 @@ func extractInlineLinksFromLine(line string, lineNum int, codeSpans []span) []ma i = linkEnd } - return links + return links, inlineLinkSpans } func extractAutoLinksFromLine(line string, lineNum int, codeSpans []span) []markdownLink { @@ -328,26 +298,48 @@ func extractAutoLinksFromLine(line string, lineNum int, codeSpans []span) []mark return links } -func extractReferenceLinksFromLine(line string, lineNum int, defs map[string]string, codeSpans []span) []markdownLink { +func extractReferenceLinksFromLine(line string, lineNum int, defs map[string]string, codeSpans, inlineLinkSpans []span) []markdownLink { var links []markdownLink + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "[") { + if labelEnd := findMatchingBracket(trimmed, 0); labelEnd > 0 && labelEnd+1 < len(trimmed) && trimmed[labelEnd+1] == ':' { + // Definitions name destinations; they are not links themselves. + return nil + } + } matches := mdRefLinkRe.FindAllStringSubmatchIndex(line, -1) for _, m := range matches { if len(m) < 6 { continue } + if isEscapedMarkdownAt(line, m[0]) { + continue + } start := m[0] + if indexInSpans(start, inlineLinkSpans) { + continue + } if indexInSpans(start, codeSpans) { continue } - if start > 0 && line[start-1] == '!' && !indexInSpans(start-1, codeSpans) { + if start > 0 && line[start-1] == '!' && !isEscapedMarkdownAt(line, start-1) && !indexInSpans(start-1, codeSpans) { // Image reference: ![alt][id] continue } label := strings.TrimSpace(line[m[2]:m[3]]) - ref := strings.TrimSpace(line[m[4]:m[5]]) - if ref == "" { - ref = label + if strings.HasPrefix(label, "^") { + continue + } + ref := label + if m[4] >= 0 && m[5] >= 0 { + ref = strings.TrimSpace(line[m[4]:m[5]]) + if ref == "" { + ref = label + } + } else if m[1] < len(line) && line[m[1]] == '(' { + // Inline links take precedence over shortcut references with the same label. + continue } target, ok := defs[normalizeReferenceLabel(ref)] if !ok { @@ -406,10 +398,14 @@ func extractMultilineLink(line, nextLine string, lineNum int) (markdownLink, boo } targetLine := strings.TrimSpace(nextLine) - if !strings.HasPrefix(targetLine, "(") || !strings.HasSuffix(targetLine, ")") { + if !strings.HasPrefix(targetLine, "(") { return markdownLink{}, false } - target := parseMarkdownLinkTarget(strings.TrimSpace(targetLine[1 : len(targetLine)-1])) + inside, end := readParenthesized(targetLine, 0) + if end == -1 { + return markdownLink{}, false + } + target := parseMarkdownLinkTarget(strings.TrimSpace(inside)) if target == "" { return markdownLink{}, false } @@ -422,6 +418,24 @@ func extractMultilineLink(line, nextLine string, lineNum int) (markdownLink, boo }, true } +// multilineLinkTargetSpan returns the span of targetLine consumed by a +// multiline link destination, leaving any sibling references after it visible. +func multilineLinkTargetSpan(line, targetLine string) (span, bool) { + _, ok := extractMultilineLink(line, targetLine, 0) + if !ok { + labelLine := strings.TrimSpace(line) + if !strings.HasPrefix(labelLine, "![") { + return span{}, false + } + if _, ok = extractMultilineLink(strings.TrimPrefix(labelLine, "!"), targetLine, 0); !ok { + return span{}, false + } + } + start := len(targetLine) - len(strings.TrimLeft(targetLine, " \t")) + _, end := readParenthesized(targetLine, start) + return span{start: start, end: end + 1}, true +} + func parseMarkdownLinkTarget(raw string) string { s := strings.TrimSpace(raw) if s == "" { @@ -587,6 +601,14 @@ func indexInSpans(idx int, spans []span) bool { return false } +func isEscapedMarkdownAt(line string, idx int) bool { + backslashes := 0 + for i := idx - 1; i >= 0 && line[i] == '\\'; i-- { + backslashes++ + } + return backslashes%2 == 1 +} + // isExternalOrAnchor returns true for links that should not be checked on disk. func isExternalOrAnchor(target string) bool { lower := strings.ToLower(target) diff --git a/scripts/create-demo-content.sh b/scripts/create-demo-content.sh index 5563e8159..adc062e60 100755 --- a/scripts/create-demo-content.sh +++ b/scripts/create-demo-content.sh @@ -121,12 +121,12 @@ See the official docs for more details: The localhost link above should NOT trigger external-link findings. SKILL_EOF -# security/audit-demo-dangling-link: LOW, broken local markdown links. +# security/audit-demo-dangling-link: LOW missing links and a HIGH escape. mkdir -p "$SKILLS/security/audit-demo-dangling-link" cat > "$SKILLS/security/audit-demo-dangling-link/SKILL.md" << 'SKILL_EOF' --- name: audit-demo-dangling-link -description: "[DEMO] Skill with broken local links (LOW)" +description: "[DEMO] Skill with missing links (LOW) and a root escape (HIGH)" --- # Setup Guide @@ -136,7 +136,7 @@ Follow these steps: 2. Check the [configuration reference](config/reference.md) 3. See [troubleshooting](../troubleshooting.md) -None of these local files exist, so each link produces a dangling-link finding. +The first two links are missing (LOW); the third escapes the skill root (HIGH). SKILL_EOF # devops/deploy-checklist: clean skill in a different category. diff --git a/skills/skillshare/references/audit.md b/skills/skillshare/references/audit.md index 62e7d6455..67531d210 100644 --- a/skills/skillshare/references/audit.md +++ b/skills/skillshare/references/audit.md @@ -2,6 +2,8 @@ Scan skills for prompt injection, data exfiltration, credential access, destructive commands, obfuscation, suspicious URLs, and broken local links. Use `audit rules --no-tui` for the installed rule set. +Local references in Markdown links/images, code paths with a file extension (prefixes `./`, `../`, `scripts/`, `references/`, or `assets/`), explicit `path:` declarations, and `skillshare-paths` fences are checked within the skill directory. Markdown links/images are document-relative. Code paths, `path:` declarations and path fences use the containing document for leading `./` or `../`; other relative code paths use the skill root, even in nested Markdown files. Absolute in-bundle paths accept equivalent spellings derived from the root and its symlinked ancestors. Missing targets remain LOW `dangling-link`; explicit reference escapes are HIGH `reference-escapes-root`; implicit inline-code paths outside the bundle are ignored and trailing `:line` suffixes are stripped; unreadable, unsupported or bounded-out checks are LOW `reference-check-incomplete`. Implicit glob/template and extensionless examples, URLs, anchors, ordinary identifiers and unmarked absolute code examples are excluded. Use `path:` or a path fence for required directories and extensionless files. Disable individual IDs with `enabled: false` in `audit-rules.yaml`. `doctor` uses the same checker and reports escapes as errors, missing/incomplete checks as warnings. + ## Usage ```bash diff --git a/tests/integration/doctor_test.go b/tests/integration/doctor_test.go index 5debd5384..ea8406d7f 100644 --- a/tests/integration/doctor_test.go +++ b/tests/integration/doctor_test.go @@ -991,3 +991,18 @@ targets: result.AssertSuccess(t) result.AssertOutputNotContains(t, "not synced") } + +func TestDoctorBundledReferencesCleanJSON(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + sb.CreateSkill("clean-reference", map[string]string{"SKILL.md": "---\nname: clean-reference\n---\n# Clean\n"}) + sb.WriteConfig("source: " + sb.SourcePath + "\ntargets: {}\n") + got := sb.RunCLI("doctor", "--json") + checks := parseDoctorJSON(t, got.Stdout).Checks + for _, check := range checks { + if check.Name == "bundled_references" && check.Status == "pass" { + return + } + } + t.Fatalf("clean bundled references pass missing: %+v", checks) +} diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index 83db7d114..4a4f7523a 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -350,6 +350,7 @@ "doctor.check.agents_source": "Agents-Quelle", "doctor.check.backup": "Backups", "doctor.check.broken_symlinks": "Defekte Symlinks", + "doctor.check.bundled_references": "Referenzen im Skill-Paket", "doctor.check.cli_version": "CLI-Version", "doctor.check.duplicate_skills": "Doppelte Skills", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index f67ce6529..db0ac87a6 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -479,6 +479,7 @@ "doctor.check.targets": "Targets", "doctor.check.sync_drift": "Sync Status", "doctor.check.broken_symlinks": "Broken Symlinks", + "doctor.check.bundled_references": "Bundled References", "doctor.check.duplicate_skills": "Duplicate Skills", "doctor.check.extras": "Extras", "doctor.check.mcp": "MCP Servers", diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index a0f57adb6..7c9d83800 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -344,6 +344,7 @@ "doctor.check.agents_source": "Agentes Source", "doctor.check.backup": "Backups", "doctor.check.broken_symlinks": "Broken Symlinks", + "doctor.check.bundled_references": "Referencias del paquete", "doctor.check.cli_version": "CLI Version", "doctor.check.duplicate_skills": "Duplicate Skills", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index a6e23da96..297c7704b 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -344,6 +344,7 @@ "doctor.check.agents_source": "منبع عامل‌ها", "doctor.check.backup": "پشتیبان‌گیری", "doctor.check.broken_symlinks": "Symlink‌های شکسته", + "doctor.check.bundled_references": "ارجاع‌های بستهٔ مهارت", "doctor.check.cli_version": "نسخه CLI", "doctor.check.duplicate_skills": "اسکیل‌های تکراری", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index daf4aa31a..abfbd04ed 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -344,6 +344,7 @@ "doctor.check.agents_source": "Source des agents", "doctor.check.backup": "Sauvegardes", "doctor.check.broken_symlinks": "Liens symboliques cassés", + "doctor.check.bundled_references": "Références du paquet", "doctor.check.cli_version": "Version CLI", "doctor.check.duplicate_skills": "Skills en double", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index 13ac69608..d6e7d074b 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -345,6 +345,7 @@ "doctor.check.agents_source": "Sumber Agen", "doctor.check.backup": "Cadangan", "doctor.check.broken_symlinks": "Symlink Rusak", + "doctor.check.bundled_references": "Referensi dalam paket", "doctor.check.cli_version": "Versi CLI", "doctor.check.duplicate_skills": "Skill Duplikat", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 1b9444b50..3e6df15e3 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -350,6 +350,7 @@ "doctor.check.agents_source": "エージェントソース", "doctor.check.backup": "バックアップ", "doctor.check.broken_symlinks": "壊れたシンボリックリンク", + "doctor.check.bundled_references": "バンドル内の参照", "doctor.check.cli_version": "CLI バージョン", "doctor.check.duplicate_skills": "重複スキル", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index f246c63ab..29d703b83 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -355,6 +355,7 @@ "doctor.check.agents_source": "에이전트 소스", "doctor.check.backup": "백업", "doctor.check.broken_symlinks": "깨진 심볼릭 링크", + "doctor.check.bundled_references": "번들 내 참조", "doctor.check.cli_version": "CLI 버전", "doctor.check.duplicate_skills": "중복 Skills", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index 8a3fcaf9f..a93988b1b 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -344,6 +344,7 @@ "doctor.check.agents_source": "Fonte dos Agentes", "doctor.check.backup": "Backups", "doctor.check.broken_symlinks": "Symlinks Quebrados", + "doctor.check.bundled_references": "Referências do pacote", "doctor.check.cli_version": "Versão da CLI", "doctor.check.duplicate_skills": "Skills Duplicadas", "doctor.check.extras": "Extras", diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index 3f7245411..774341e58 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -350,6 +350,7 @@ "doctor.check.agents_source": "Agent 来源", "doctor.check.backup": "备份", "doctor.check.broken_symlinks": "失效符号链接", + "doctor.check.bundled_references": "技能包内引用", "doctor.check.cli_version": "CLI 版本", "doctor.check.duplicate_skills": "重复 Skill", "doctor.check.extras": "附加设置", diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 17658be05..6c3c88c67 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -363,6 +363,7 @@ "doctor.check.targets": "目標", "doctor.check.sync_drift": "同步狀態", "doctor.check.broken_symlinks": "失效符號連結", + "doctor.check.bundled_references": "技能套件內參照", "doctor.check.duplicate_skills": "重複 Skill", "doctor.check.extras": "附加設定", "doctor.check.mcp": "MCP 伺服器", diff --git a/website/docs/learn/with-playground.md b/website/docs/learn/with-playground.md index c218e7c50..1a53e97c9 100644 --- a/website/docs/learn/with-playground.md +++ b/website/docs/learn/with-playground.md @@ -38,7 +38,7 @@ This single command: | `audit-demo-ci-release` | `security/` | HIGH + MEDIUM (sudo, external URLs) | | `audit-demo-debug-exfil` | `security/` | CRITICAL (credential exfiltration) | | `audit-demo-external-link` | `security/` | LOW (external URLs) | -| `audit-demo-dangling-link` | `security/` | LOW (broken local links) | +| `audit-demo-dangling-link` | `security/` | LOW (missing links) + HIGH (root escape) | ### Demo Project (`~/demo-project`) diff --git a/website/docs/reference/commands/audit-rules.md b/website/docs/reference/commands/audit-rules.md index d4c584e5f..39cdcb3f4 100644 --- a/website/docs/reference/commands/audit-rules.md +++ b/website/docs/reference/commands/audit-rules.md @@ -284,7 +284,7 @@ The file-level `whitespace-padding` detector is also registered in `rules.yaml`. :::note Structural, tier, and cross-skill checks -`dangling-link`, `content-tampered`, `content-oversize`, `content-missing`, and `content-unexpected` are **structural checks** (filesystem lookups and hash comparisons, not regex). `low-analyzability` is an **analyzability finding** generated from the [Analyzability Score](/docs/understand/audit-engine#analyzability-score). `tier-stealth`, `tier-destructive-network`, `tier-network-heavy`, `tier-interpreter`, and `tier-interpreter-network` are **tier combination findings** generated from [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) profiles. `cross-skill-*` findings are generated from [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection). All of these appear in the table below but are not defined in `rules.yaml`. +`dangling-link`, `reference-escapes-root`, `reference-check-incomplete`, `content-tampered`, `content-oversize`, `content-missing`, and `content-unexpected` are **structural checks** (filesystem lookups and hash comparisons, not regex). `low-analyzability` is an **analyzability finding** generated from the [Analyzability Score](/docs/understand/audit-engine#analyzability-score). `tier-stealth`, `tier-destructive-network`, `tier-network-heavy`, `tier-interpreter`, and `tier-interpreter-network` are **tier combination findings** generated from [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) profiles. `cross-skill-*` findings are generated from [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection). All of these appear in the table below but are not defined in `rules.yaml`. ::: @@ -384,6 +384,8 @@ The file-level `whitespace-padding` detector is also registered in `rules.yaml`. | `insecure-http-0` | insecure-http | LOW | | `external-link-0` | external-link | LOW | | `dangling-link` | dangling-link | LOW | +| `reference-escapes-root` | reference-escapes-root | HIGH | +| `reference-check-incomplete` | reference-check-incomplete | LOW | | `content-tampered` | content-tampered | MEDIUM | | `content-oversize` | content-oversize | MEDIUM | | `content-missing` | content-missing | LOW | diff --git a/website/docs/reference/commands/audit.md b/website/docs/reference/commands/audit.md index 948bf741c..a56cc3168 100644 --- a/website/docs/reference/commands/audit.md +++ b/website/docs/reference/commands/audit.md @@ -137,7 +137,7 @@ skillshare audit --analyzer static --analyzer dataflow # Multiple analyzers | `tier` | Per-skill | Capability tier combination risk analysis | | `integrity` | Per-skill | Content hash verification (`file_hashes` in SKILL.md) | | `metadata` | Per-skill | Supply-chain trust verification (publisher mismatch, authority claims) | -| `structure` | Per-skill | Dangling markdown link detection | +| `structure` | Per-skill | Checks missing and out-of-root Markdown links/images and declared bundled paths | | `cross-skill` | Bundle | Cross-skill exfiltration and privilege escalation analysis | You can also set this in config: diff --git a/website/docs/reference/commands/doctor.md b/website/docs/reference/commands/doctor.md index 1acbdc6e3..bf355c33c 100644 --- a/website/docs/reference/commands/doctor.md +++ b/website/docs/reference/commands/doctor.md @@ -59,6 +59,8 @@ Next For tracked repositories with agent variants, the Source line shows `N skills, M variants`: logical skills and physical copies. The `variant_routing` check warns when symlink mode exposes all variants instead of selecting by agent; use merge or copy mode for selective routing. +Bundled references use the audit structural checker in both modes: missing or incomplete checks are warnings, root escapes are errors. Global/project `audit-rules.yaml` disables apply. JSON entries use `bundled_references` and include the rule ID, source file, line and snippet. See [bundled reference checks](../../understand/audit-engine.md). + ## When to Use - Something isn't working and you don't know why diff --git a/website/docs/understand/audit-engine.md b/website/docs/understand/audit-engine.md index b653188ae..412dc7bf0 100644 --- a/website/docs/understand/audit-engine.md +++ b/website/docs/understand/audit-engine.md @@ -86,6 +86,7 @@ These patterns warrant **careful review**. They can indicate dangerous behavior | `data-exfiltration` | DNS data exfiltration via `dig`/`nslookup`/`host` with command substitution in subdomain | | `self-propagation` | Self-replication instructions that spread payload to other files or projects | | `hardcoded-secret` | Inline API keys, tokens, and passwords: Google API keys (`AIza...`), AWS access keys (`AKIA...`), GitHub PATs (`ghp_`/`ghs_`/`github_pat_`), Slack tokens (`xox[bporas]-`), OpenAI keys, Anthropic keys, Stripe keys, PEM private key blocks, and generic `api_key`/`secret_key`/`password` assignments with high-entropy values | +| `reference-escapes-root` | Explicit bundled references that resolve outside the skill directory | > **Why high?** Hidden Unicode characters can make malicious instructions invisible during code review. Bidirectional text control characters can reorder visible text to disguise malicious code (Trojan Source). Base64 obfuscation is a common technique to bypass human inspection. Destructive commands like `rm -rf /` can cause irreversible damage. `curl | bash` is the classic remote code execution vector — fetched content runs directly in your shell. Config/memory file poisoning persists across AI sessions. DNS exfiltration encodes stolen data in subdomain queries. Self-propagation instructions create repository worms. Hardcoded secrets (API keys, tokens, private keys) in skill files indicate either leaked credentials or intentional credential exposure — both are supply-chain risks that should be reviewed. @@ -147,18 +148,22 @@ These are lower-severity indicators that contribute to risk scoring and reportin - `LOW`: weaker suspicious patterns (e.g., non-HTTPS URLs in commands — potential for man-in-the-middle attacks) - `LOW`: **external links** — markdown links pointing to external URLs (`https://...`), which may indicate prompt injection vectors or unnecessary token consumption; localhost links are excluded -- `LOW`: **dangling local links** — broken relative markdown links whose target file or directory does not exist on disk +- `LOW`: **bundled references** — missing local targets (`dangling-link`) and paths that could not be checked (`reference-check-incomplete`) - `LOW`: **content-missing** / **content-unexpected** — content integrity issues (see above) - `INFO`: contextual hints like shell chaining patterns (for triage / visibility) - `INFO`: **low analyzability** — less than 70% of the skill's content is auditable text (see [Analyzability Score](#analyzability-score)) > These findings don't block installation but raise the overall risk score. A skill with many LOW/INFO findings may warrant closer inspection. -#### Dangling Link Detection +#### Bundled Reference Checks -The audit engine also performs a **structural check** on `.md` files: it extracts all inline markdown links (`[label](target)`) and verifies that local relative targets exist on disk. External links (`http://`, `https://`, `mailto:`, etc.) and pure anchors (`#section`) are skipped. +The structural analyzer checks local Markdown links and images, including reference-style links. It also checks inline code paths starting with `./`, `../`, `scripts/`, `references/`, or `assets/` (with a file extension, without whitespace, glob or template syntax), inline `path:` declarations, and one path per line in a fence labelled `skillshare-paths`. Implicit extensionless examples, ordinary identifiers, other code fences, unmarked absolute code examples, URLs (including `file:` URIs), and pure anchors are intentional exceptions. A required absolute path belongs in a Markdown link or an explicit `path:` declaration. Markdown links and images resolve relative to their containing document. Inline code paths, `path:` declarations, and `skillshare-paths` entries beginning with `./` or `../` also resolve from the containing document; other relative code paths resolve from the skill root, including in nested Markdown files. For example, `../scripts/query_design.py` in `references/guide.md` names the same bundle member as `scripts/query_design.py`. -This catches common quality issues like missing referenced files, renamed paths, or incomplete skill packaging. Each broken link produces a `LOW` severity finding with pattern `dangling-link`. +Missing targets retain the LOW `dangling-link` identity. Explicit Markdown links, images, `path:` declarations and path-fence entries that leave the skill directory produce HIGH `reference-escapes-root` findings. Implicit inline-code examples that leave the bundle are ignored; a trailing `:line` is stripped from implicit file paths. Absolute paths inside the bundle are allowed, including equivalent spellings derived from the declared root and its symlinked ancestors (such as `/var` and `/private/var` on macOS). Checks use bounded `lstat`/`readlink` operations inside the declared root; referenced file contents are never read. Unsupported paths, unreadable metadata, symlink cycles, or resolution limits produce LOW `reference-check-incomplete`, rather than claiming the target is missing or safe. Limits are 4,096 bytes per path, 256 component steps, and 40 symlink hops; native Windows separators are normalized; on other hosts, backslash paths are unsupported except recognized Windows drive escapes. Source line numbers and original snippets are preserved. + +Site-root links such as `/docs/foo` are explicit absolute paths: when outside the skill root they now produce HIGH `reference-escapes-root` findings instead of LOW `dangling-link`. This can block scans at `--threshold high`. + +All three rule IDs support `enabled: false` in `audit-rules.yaml`, using the same global/project rule layers as other structural checks. `doctor` reuses this analyzer: missing or incomplete references are warnings, escapes are errors, and `doctor --json` records them under `bundled_references`. These checks apply to discovered skills in both modes. ## Threat Categories Deep Dive diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/learn/with-playground.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/learn/with-playground.md index c00c02597..825dcfb89 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/learn/with-playground.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/learn/with-playground.md @@ -38,7 +38,7 @@ make playground | `audit-demo-ci-release` | `security/` | HIGH + MEDIUM(sudo、外部 URL) | | `audit-demo-debug-exfil` | `security/` | CRITICAL(認証情報の流出) | | `audit-demo-external-link` | `security/` | LOW(外部 URL) | -| `audit-demo-dangling-link` | `security/` | LOW(壊れたローカルリンク) | +| `audit-demo-dangling-link` | `security/` | LOW(欠落したリンク)+ HIGH(ルート外への参照) | ### デモプロジェクト(`~/demo-project`) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md index 1f699879f..9d2b9320c 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md @@ -284,7 +284,7 @@ skillshare audit --json | jq '.skills[].findings' # findings をプログラム :::note 構造チェック、tier チェック、Skill 間チェック -`dangling-link`、`content-tampered`、`content-oversize`、`content-missing`、`content-unexpected` は**構造チェック**です(正規表現ではなく、ファイルシステムの検索とハッシュ比較)。`low-analyzability` は [Analyzability Score](/docs/understand/audit-engine#analyzability-score) から生成される**分析可能性の finding** です。`tier-stealth`、`tier-destructive-network`、`tier-network-heavy`、`tier-interpreter`、`tier-interpreter-network` は、[Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) プロファイルから生成される**ティアの組み合わせの finding** です。`cross-skill-*` の findings は、[Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection) から生成されます。これらはすべて下記の表に記載されていますが、`rules.yaml` には定義されていません。 +`dangling-link`、`reference-escapes-root`、`reference-check-incomplete`、`content-tampered`、`content-oversize`、`content-missing`、`content-unexpected` は**構造チェック**です(正規表現ではなく、ファイルシステムの検索とハッシュ比較)。`low-analyzability` は [Analyzability Score](/docs/understand/audit-engine#analyzability-score) から生成される**分析可能性の finding** です。`tier-stealth`、`tier-destructive-network`、`tier-network-heavy`、`tier-interpreter`、`tier-interpreter-network` は、[Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) プロファイルから生成される**ティアの組み合わせの finding** です。`cross-skill-*` の findings は、[Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection) から生成されます。これらはすべて下記の表に記載されていますが、`rules.yaml` には定義されていません。 ::: @@ -384,6 +384,8 @@ skillshare audit --json | jq '.skills[].findings' # findings をプログラム | `insecure-http-0` | insecure-http | LOW | | `external-link-0` | external-link | LOW | | `dangling-link` | dangling-link | LOW | +| `reference-escapes-root` | reference-escapes-root | HIGH | +| `reference-check-incomplete` | reference-check-incomplete | LOW | | `content-tampered` | content-tampered | MEDIUM | | `content-oversize` | content-oversize | MEDIUM | | `content-missing` | content-missing | LOW | diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit.md index 256068ef8..f8b63018e 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/audit.md @@ -137,7 +137,7 @@ skillshare audit --analyzer static --analyzer dataflow # 複数の analyzer | `tier` | Skill 単位 | Capability tier の組み合わせリスク分析 | | `integrity` | Skill 単位 | コンテンツハッシュ検証(SKILL.md の `file_hashes`) | | `metadata` | Skill 単位 | サプライチェーンの信頼性検証(publisher の不一致、権威の主張) | -| `structure` | Skill 単位 | markdown のダングリングリンク検出 | +| `structure` | Skill 単位 | ローカル Markdown リンク/画像と明示されたバンドル内パスの欠落、ルート外参照を検出 | | `cross-skill` | バンドル単位 | Skill 間のデータ流出・権限昇格分析 | config で設定することもできます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/doctor.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/doctor.md index 29b8fee32..a52086fa7 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/doctor.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/reference/commands/doctor.md @@ -59,6 +59,8 @@ Next エージェント別バリアントを含む追跡リポジトリでは、Source 行に `N skills, M variants`(論理スキル数と物理コピー数)が表示されます。`variant_routing` チェックは、symlink モードがエージェント別に選択せず全バリアントを公開する場合に警告します。選択的なルーティングには merge または copy モードを使用してください。 +バンドル参照は両モードで audit の構造チェックを使用します。不在・未完了は警告、ルート外への脱出はエラーです。グローバル/プロジェクトの `audit-rules.yaml` による無効化も適用されます。JSON の `bundled_references` にはルール ID、ファイル、行番号、スニペットを含みます。[参照チェック](../../understand/audit-engine.md)を参照してください。 + ## 使うタイミング - 何かがうまく動かないが、原因がわからないとき diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/understand/audit-engine.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/understand/audit-engine.md index e357b9e15..32d3a80f9 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/understand/audit-engine.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/understand/audit-engine.md @@ -86,6 +86,7 @@ Audit エンジンは、skill ディレクトリ内のすべてのテキスト | `data-exfiltration` | サブドメイン内のコマンド置換を使った `dig`/`nslookup`/`host` による DNS データ流出 | | `self-propagation` | ペイロードを他のファイルやプロジェクトに拡散させる自己複製の指示 | | `hardcoded-secret` | インラインの API キー、トークン、パスワード:Google API キー(`AIza...`)、AWS アクセスキー(`AKIA...`)、GitHub PAT(`ghp_`/`ghs_`/`github_pat_`)、Slack トークン(`xox[bporas]-`)、OpenAI キー、Anthropic キー、Stripe キー、PEM 秘密鍵ブロック、および高エントロピー値を持つ汎用的な `api_key`/`secret_key`/`password` 代入 | +| `reference-escapes-root` | 明示的な参照が skill ディレクトリの外へ出る場合 | > **なぜ HIGH なのか?** 隠された Unicode 文字は、コードレビュー時に悪意ある指示を見えなくすることがあります。双方向テキスト制御文字は、表示上のテキストを並べ替えて悪意あるコードを偽装できます(Trojan Source)。Base64 難読化は人間による検査を回避する一般的な手法です。`rm -rf /` のような破壊的コマンドは取り返しのつかない被害をもたらす可能性があります。`curl | bash` は古典的なリモートコード実行のベクターであり、取得したコンテンツがあなたのシェルで直接実行されます。設定/メモリファイルの汚染は AI セッションをまたいで持続します。DNS 流出はサブドメインクエリに盗まれたデータをエンコードします。自己拡散の指示はリポジトリ型ワームを生み出します。skill ファイル内のハードコードされたシークレット(API キー、トークン、秘密鍵)は、漏洩した認証情報か意図的な認証情報の露出のいずれかを示しており、どちらもレビューすべきサプライチェーンリスクです。 @@ -146,19 +147,24 @@ Authority language のチェックは、よく知られた組織(Anthropic、O これらは深刻度の低い指標であり、リスクスコアリングとレポートに寄与します。 - `LOW`:より弱い不審なパターン(例:コマンド内の非 HTTPS URL — 中間者攻撃の可能性) +- `LOW`: 検査できない参照も LOW `reference-check-incomplete` として報告します。 - `LOW`:**外部リンク** — 外部 URL(`https://...`)を指す markdown リンク。プロンプトインジェクションのベクターや不要なトークン消費を示す可能性がある。localhost へのリンクは除外される -- `LOW`:**ダングリングなローカルリンク** — 対象のファイルやディレクトリがディスク上に存在しない、壊れた相対 markdown リンク +- `LOW`:**欠落した同梱参照** — Markdown リンク、画像、明示的またはインラインのパスの対象が存在しない場合 - `LOW`:**content-missing** / **content-unexpected** — コンテンツ完全性の問題(上記参照) - `INFO`:シェルの連結パターンなどの文脈的なヒント(トリアージ/可視性のため) - `INFO`:**analyzability の低さ** — skill のコンテンツのうち audit 可能なテキストが 70% 未満([Analyzability Score](#analyzability-score) を参照) > これらの finding はインストールをブロックしませんが、全体のリスクスコアを引き上げます。LOW/INFO の finding が多い skill は、より詳しく確認する価値があるかもしれません。 -#### ダングリングリンクの検出 +#### バンドル参照のチェック -Audit エンジンは `.md` ファイルに対して **構造チェック**も行います。インラインの markdown リンク(`[label](target)`)をすべて抽出し、ローカルの相対的なターゲットがディスク上に存在するかを確認します。外部リンク(`http://`、`https://`、`mailto:` など)と純粋なアンカー(`#section`)はスキップされます。 +構造アナライザーはローカルの Markdown リンクと画像(参照形式も含む)を検査します。インラインコードでは、空白・glob・テンプレート構文を含まず、ファイル拡張子があり `./`、`../`、`scripts/`、`references/`、`assets/` で始まるパスと、明示的な `path:` を検査します。`skillshare-paths` と指定したフェンスでは、1 行につき 1 パスを検査します。暗黙の拡張子なしのコード例、通常の識別子、その他のコードフェンス、明示指定のない絶対パスのコード例、URL(`file:` URI を含む)、アンカーのみの参照は意図的に除外します。必須の絶対パスは Markdown リンクまたは `path:` 宣言で指定します。 Markdown リンクと画像は記載された文書のディレクトリを基準に解決します。インラインコードのパス、`path:` 宣言、`skillshare-paths` の項目も、`./` または `../` で始まる場合は記載された文書を基準に解決します。その他の相対コードパスは、ネストした Markdown ファイルでも skill ルートを基準に解決します。 -これにより、参照されているファイルの欠落、パスのリネーム、不完全な skill パッケージングといった、よくある品質問題を検出できます。壊れたリンクごとに、パターン `dangling-link` を持つ `LOW` 深刻度の finding が生成されます。 +存在しない対象は従来どおり LOW の `dangling-link` です。親への移動、ホームパス、Windows ドライブパス、シンボリックリンクの構成要素が skill ディレクトリの外へ出る場合は HIGH の `reference-escapes-root` になります。バンドル内の絶対パスは許可され、宣言されたルートとそのシンボリックリンクを含む親から導出した同等の表記(macOS の `/var` と `/private/var` など)も認識します。宣言されたルート内で回数を制限した `lstat`/`readlink` を使用し、参照先ファイルの内容は読みません。未対応のパス、読み取れないメタデータ、リンクの循環、解決回数の上限は LOW の `reference-check-incomplete` として報告し、不在や安全とは判断しません。上限はパスあたり 4,096 バイト、256 構成要素ステップ、40 リンクホップです。Windows の区切り文字は正規化します。他のホストでは、認識可能な Windows ドライブの脱出を除き、バックスラッシュのパスは未対応です。元の行番号とスニペットを保持します。 暗黙のインラインコード例が外へ出る場合は無視し、末尾の `:line` は除去します。 + +`/docs/foo` のようなサイトルートリンクがスキル外を指す場合、従来の LOW `dangling-link` ではなく HIGH `reference-escapes-root` になります。`--threshold high` ではブロックされることがあります。 + +3 つのルール ID はすべて `audit-rules.yaml` の `enabled: false` に対応し、他の構造チェックと同じグローバル/プロジェクト設定を使います。`doctor` も同じアナライザーを使い、不在・未完了は警告、脱出はエラーとして扱います。`doctor --json` では `bundled_references` に記録します。両モードで検出された skill に適用します。 ## 脅威カテゴリの詳細 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/learn/with-playground.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/learn/with-playground.md index 8170fbdfd..7e53cf940 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/learn/with-playground.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/learn/with-playground.md @@ -38,7 +38,7 @@ make playground | `audit-demo-ci-release` | `security/` | HIGH + MEDIUM (sudo, 외부 URL) | | `audit-demo-debug-exfil` | `security/` | CRITICAL (자격 증명 유출) | | `audit-demo-external-link` | `security/` | LOW (외부 URL) | -| `audit-demo-dangling-link` | `security/` | LOW (깨진 로컬 링크) | +| `audit-demo-dangling-link` | `security/` | LOW (누락된 링크) + HIGH (루트 이탈) | ### 데모 프로젝트 (`~/demo-project`) diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md index 3a5fbf8c0..7be815276 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md @@ -284,7 +284,7 @@ skillshare audit --json | jq '.skills[].findings' # findings를 프로그래밍 :::note 구조적, tier, cross-skill 검사 -`dangling-link`, `content-tampered`, `content-oversize`, `content-missing`, `content-unexpected`는 (정규식이 아닌 파일시스템 조회와 해시 비교를 수행하는) **구조적 검사**입니다. `low-analyzability`는 [Analyzability Score](/docs/understand/audit-engine#analyzability-score)에서 생성되는 **analyzability finding**입니다. `tier-stealth`, `tier-destructive-network`, `tier-network-heavy`, `tier-interpreter`, `tier-interpreter-network`는 [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) 프로파일에서 생성되는 **tier 조합 findings**입니다. `cross-skill-*` findings는 [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection)에서 생성됩니다. 이들은 모두 아래 표에 나타나지만 `rules.yaml`에는 정의되어 있지 않습니다. +`dangling-link`, `reference-escapes-root`, `reference-check-incomplete`, `content-tampered`, `content-oversize`, `content-missing`, `content-unexpected`는 (정규식이 아닌 파일시스템 조회와 해시 비교를 수행하는) **구조적 검사**입니다. `low-analyzability`는 [Analyzability Score](/docs/understand/audit-engine#analyzability-score)에서 생성되는 **analyzability finding**입니다. `tier-stealth`, `tier-destructive-network`, `tier-network-heavy`, `tier-interpreter`, `tier-interpreter-network`는 [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) 프로파일에서 생성되는 **tier 조합 findings**입니다. `cross-skill-*` findings는 [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection)에서 생성됩니다. 이들은 모두 아래 표에 나타나지만 `rules.yaml`에는 정의되어 있지 않습니다. ::: @@ -384,6 +384,8 @@ skillshare audit --json | jq '.skills[].findings' # findings를 프로그래밍 | `insecure-http-0` | insecure-http | LOW | | `external-link-0` | external-link | LOW | | `dangling-link` | dangling-link | LOW | +| `reference-escapes-root` | reference-escapes-root | HIGH | +| `reference-check-incomplete` | reference-check-incomplete | LOW | | `content-tampered` | content-tampered | MEDIUM | | `content-oversize` | content-oversize | MEDIUM | | `content-missing` | content-missing | LOW | diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit.md index d357a4da8..27f462369 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/audit.md @@ -137,7 +137,7 @@ skillshare audit --analyzer static --analyzer dataflow # 여러 분석기 | `tier` | skill별 | 기능 등급(capability tier) 조합 위험 분석 | | `integrity` | skill별 | 콘텐츠 해시 검증 (SKILL.md의 `file_hashes`) | | `metadata` | skill별 | 공급망 신뢰 검증 (publisher 불일치, authority 주장) | -| `structure` | skill별 | markdown 댕글링 링크 탐지 | +| `structure` | skill별 | 로컬 Markdown 링크/이미지 및 명시된 번들 경로의 누락과 루트 외부 참조 감지 | | `cross-skill` | 번들 | Cross-skill 유출 및 권한 상승 분석 | config에서도 설정할 수 있습니다: diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/doctor.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/doctor.md index 19e766450..16abd939c 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/doctor.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/reference/commands/doctor.md @@ -59,6 +59,8 @@ Next 에이전트 변형이 있는 추적 저장소의 Source 줄에는 `N skills, M variants`가 표시됩니다. 이는 논리적 스킬 수와 물리적 복사본 수입니다. `variant_routing` 검사는 symlink 모드가 에이전트별 선택 없이 모든 변형을 노출할 때 경고합니다. 선택적 라우팅에는 merge 또는 copy 모드를 사용하세요. +번들 참조는 두 모드에서 audit 구조 검사를 사용합니다. 누락·미완료는 경고, 루트 이탈은 오류입니다. 전역/프로젝트 `audit-rules.yaml`의 비활성화 설정을 적용합니다. JSON의 `bundled_references`에는 규칙 ID, 파일, 줄 번호와 스니펫이 포함됩니다. [참조 검사](../../understand/audit-engine.md)를 참고하세요. + ## 사용 시점 - 뭔가 작동하지 않는데 원인을 모를 때 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/current/understand/audit-engine.md b/website/i18n/ko/docusaurus-plugin-content-docs/current/understand/audit-engine.md index 1e66ef26c..822c79b88 100644 --- a/website/i18n/ko/docusaurus-plugin-content-docs/current/understand/audit-engine.md +++ b/website/i18n/ko/docusaurus-plugin-content-docs/current/understand/audit-engine.md @@ -86,6 +86,7 @@ audit engine은 skill 디렉터리의 모든 텍스트 기반 파일을 100개 | `data-exfiltration` | 서브도메인에 명령 치환을 사용한 `dig`/`nslookup`/`host`를 통한 DNS 데이터 유출 | | `self-propagation` | 다른 파일이나 프로젝트로 페이로드를 전파하는 자기 복제 지침 | | `hardcoded-secret` | 인라인 API 키, 토큰, 비밀번호: Google API 키(`AIza...`), AWS 액세스 키(`AKIA...`), GitHub PAT(`ghp_`/`ghs_`/`github_pat_`), Slack 토큰(`xox[bporas]-`), OpenAI 키, Anthropic 키, Stripe 키, PEM 개인 키 블록, 그리고 높은 엔트로피 값을 가진 일반적인 `api_key`/`secret_key`/`password` 할당 | +| `reference-escapes-root` | 명시적 참조가 skill 디렉터리 밖으로 나가는 경우 | > **왜 high인가?** 숨겨진 유니코드 문자는 코드 리뷰 중 악성 지침을 보이지 않게 만들 수 있습니다. 양방향 텍스트 제어 문자는 보이는 텍스트의 순서를 바꿔 악성 코드를 위장할 수 있습니다(Trojan Source). Base64 난독화는 사람의 검사를 우회하는 일반적인 기법입니다. `rm -rf /` 같은 파괴적인 명령은 되돌릴 수 없는 손상을 일으킬 수 있습니다. `curl | bash`는 고전적인 원격 코드 실행 벡터입니다 — 가져온 콘텐츠가 셸에서 바로 실행됩니다. Config/메모리 파일 오염은 AI 세션 전반에 걸쳐 지속됩니다. DNS 유출은 훔친 데이터를 서브도메인 쿼리에 인코딩합니다. 자기 전파 지침은 저장소 웜을 만듭니다. skill 파일에 하드코딩된 비밀 정보(API 키, 토큰, 개인 키)는 유출된 자격 증명이거나 의도적인 자격 증명 노출을 나타내며 — 둘 다 검토가 필요한 공급망 위험입니다. @@ -146,19 +147,24 @@ Markdown(`.md`) 파일에서는 펜스 및 들여쓰기 코드 블록과 파싱 이는 위험 점수와 보고에 기여하는 낮은 심각도의 지표입니다: - `LOW`: 약한 의심 패턴 (예: 명령 내 비-HTTPS URL — 중간자 공격 가능성) +- `LOW`: 검사할 수 없는 참조도 LOW `reference-check-incomplete`로 보고합니다. - `LOW`: **외부 링크** — 외부 URL(`https://...`)을 가리키는 markdown 링크. 프롬프트 인젝션 벡터나 불필요한 토큰 소비를 나타낼 수 있음. localhost 링크는 제외 -- `LOW`: **끊어진 로컬 링크** — 대상 파일이나 디렉터리가 디스크에 존재하지 않는 깨진 상대 markdown 링크 +- `LOW`: **없는 번들 참조** — Markdown 링크, 이미지, 명시적 또는 인라인 경로의 대상이 없는 경우 - `LOW`: **content-missing** / **content-unexpected** — 콘텐츠 무결성 문제 (위 참고) - `INFO`: 셸 체이닝 패턴 같은 문맥적 힌트 (분류/가시성 목적) - `INFO`: **낮은 분석 가능성** — skill 콘텐츠의 70% 미만이 감사 가능한 텍스트임 ([Analyzability Score](#analyzability-score) 참고) > 이 발견 사항들은 설치를 막지 않지만 전체 위험 점수를 높입니다. LOW/INFO 발견 사항이 많은 skill은 더 면밀한 검사가 필요할 수 있습니다. -#### 끊어진 링크 탐지 +#### 번들 참조 검사 -audit engine은 `.md` 파일에 대해 **구조적 검사**도 수행합니다: 모든 인라인 markdown 링크(`[label](target)`)를 추출하여 로컬 상대 대상이 디스크에 존재하는지 확인합니다. 외부 링크(`http://`, `https://`, `mailto:` 등)와 순수 앵커(`#section`)는 건너뜁니다. +구조 분석기는 참조 형식을 포함한 로컬 Markdown 링크와 이미지를 검사합니다. 인라인 코드에서는 공백·glob·템플릿 구문 없이 파일 확장자가 있고 `./`, `../`, `scripts/`, `references/`, `assets/`로 시작하는 경로와 명시적인 `path:` 선언을 검사합니다. `skillshare-paths`로 표시한 펜스에서는 한 줄에 경로 하나를 검사합니다. 명시적 선언이 없는 확장자 없는 예제, 일반 식별자, 다른 코드 펜스, 명시적 표시가 없는 절대 경로 코드 예제, URL(`file:` URI 포함), 앵커만 있는 참조는 의도적으로 제외합니다. 필수 절대 경로는 Markdown 링크나 `path:` 선언으로 지정합니다. Markdown 링크와 이미지는 해당 문서의 디렉터리를 기준으로 해석합니다. 인라인 코드 경로, `path:` 선언, `skillshare-paths` 항목도 `./` 또는 `../`로 시작하면 해당 문서를 기준으로 해석합니다. 그 밖의 상대 코드 경로는 중첩된 Markdown 파일에서도 skill 루트를 기준으로 해석합니다. -이는 누락된 참조 파일, 이름이 변경된 경로, 불완전한 skill 패키징 같은 흔한 품질 문제를 잡아냅니다. 각 깨진 링크는 `dangling-link` 패턴으로 `LOW` 심각도 발견 사항을 생성합니다. +없는 대상은 기존 LOW `dangling-link`를 유지합니다. 상위 경로, 홈 경로, Windows 드라이브 경로 또는 심볼릭 링크 구성 요소가 skill 디렉터리 밖으로 나가면 HIGH `reference-escapes-root`를 생성합니다. 번들 내부의 절대 경로는 허용하며, 선언된 루트와 심볼릭 링크가 포함된 상위 디렉터리에서 도출한 동등한 표기(macOS의 `/var`와 `/private/var` 등)도 인식합니다. 선언된 루트 안에서 횟수가 제한된 `lstat`/`readlink`를 사용하며 참조 파일 내용은 읽지 않습니다. 미지원 경로, 읽을 수 없는 메타데이터, 링크 순환, 해석 한도 초과는 LOW `reference-check-incomplete`로 보고하며, 대상이 없거나 안전하다고 판단하지 않습니다. 한도는 경로당 4,096바이트, 구성 요소 256단계, 심볼릭 링크 40홉입니다. Windows의 기본 구분자는 정규화합니다. 다른 호스트에서는 인식 가능한 Windows 드라이브 이탈을 제외한 역슬래시 경로를 지원하지 않습니다. 원본 줄 번호와 스니펫을 보존합니다. 암시적 인라인 코드 예시가 번들 밖으로 나가면 무시하고 끝의 `:line`은 제거합니다. + +`/docs/foo` 같은 사이트 루트 링크가 스킬 밖을 가리키면 기존 LOW `dangling-link` 대신 HIGH `reference-escapes-root`가 발생합니다. `--threshold high`에서는 차단될 수 있습니다. + +세 규칙 ID 모두 `audit-rules.yaml`의 `enabled: false`를 지원하며 다른 구조 검사와 같은 전역/프로젝트 설정을 사용합니다. `doctor`도 같은 분석기를 사용합니다. 누락 또는 미완료는 경고, 루트 이탈은 오류이며, `doctor --json`은 `bundled_references`로 기록합니다. 두 모드에서 발견된 skill에 적용됩니다. ## 위협 카테고리 심층 분석 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/learn/with-playground.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/learn/with-playground.md index 175d62780..a10444880 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/learn/with-playground.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/learn/with-playground.md @@ -38,7 +38,7 @@ make playground | `audit-demo-ci-release` | `security/` | HIGH + MEDIUM(sudo、外部 URL) | | `audit-demo-debug-exfil` | `security/` | CRITICAL(凭证外泄) | | `audit-demo-external-link` | `security/` | LOW(外部 URL) | -| `audit-demo-dangling-link` | `security/` | LOW(失效的本地链接) | +| `audit-demo-dangling-link` | `security/` | LOW(缺失链接)+ HIGH(超出根目录) | ### 示例项目(`~/demo-project`) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md index ee29772fa..f808a9be6 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md @@ -284,7 +284,7 @@ skillshare audit --json | jq '.skills[].findings' # Inspect findings programmat :::note 结构性、分级和跨 skill 检查 -`dangling-link`、`content-tampered`、`content-oversize`、`content-missing` 和 `content-unexpected` 属于**结构性检查**(文件系统查找和哈希比较,而非正则表达式)。`low-analyzability` 是由 [Analyzability Score](/docs/understand/audit-engine#analyzability-score) 生成的**可分析性发现结果**。`tier-stealth`、`tier-destructive-network`、`tier-network-heavy`、`tier-interpreter` 和 `tier-interpreter-network` 是由 [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) profile 生成的**分级组合发现结果**。`cross-skill-*` 发现结果由 [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection) 生成。以上这些都出现在下面的表格中,但并未定义在 `rules.yaml` 里。 +`dangling-link`、`reference-escapes-root`、`reference-check-incomplete`、`content-tampered`、`content-oversize`、`content-missing` 和 `content-unexpected` 属于**结构性检查**(文件系统查找和哈希比较,而非正则表达式)。`low-analyzability` 是由 [Analyzability Score](/docs/understand/audit-engine#analyzability-score) 生成的**可分析性发现结果**。`tier-stealth`、`tier-destructive-network`、`tier-network-heavy`、`tier-interpreter` 和 `tier-interpreter-network` 是由 [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) profile 生成的**分级组合发现结果**。`cross-skill-*` 发现结果由 [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection) 生成。以上这些都出现在下面的表格中,但并未定义在 `rules.yaml` 里。 ::: @@ -384,6 +384,8 @@ skillshare audit --json | jq '.skills[].findings' # Inspect findings programmat | `insecure-http-0` | insecure-http | LOW | | `external-link-0` | external-link | LOW | | `dangling-link` | dangling-link | LOW | +| `reference-escapes-root` | reference-escapes-root | HIGH | +| `reference-check-incomplete` | reference-check-incomplete | LOW | | `content-tampered` | content-tampered | MEDIUM | | `content-oversize` | content-oversize | MEDIUM | | `content-missing` | content-missing | LOW | diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit.md index 8b5144984..9cbdcc6dd 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/audit.md @@ -137,7 +137,7 @@ skillshare audit --analyzer static --analyzer dataflow # 使用多个分析器 | `tier` | 逐 skill | 能力分级组合风险分析 | | `integrity` | 逐 skill | 内容哈希校验(SKILL.md 中的 `file_hashes`) | | `metadata` | 逐 skill | 供应链信任校验(发布者不匹配、权威性声明) | -| `structure` | 逐 skill | 悬空 markdown 链接检测 | +| `structure` | 逐 skill | 检查本地 Markdown 链接/图片和显式声明的捆绑路径是否缺失,并检测指向根目录外的引用 | | `cross-skill` | 整批 | 跨 skill 的外泄与权限提升分析 | 你也可以在配置中设置: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/doctor.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/doctor.md index 33755a0cb..550d3f134 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/doctor.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/commands/doctor.md @@ -59,6 +59,8 @@ Next 对于包含代理变体的跟踪仓库,Source 行显示 `N skills, M variants`,分别表示逻辑技能数和物理副本数。`variant_routing` 检查会在 symlink 模式公开所有变体而不按代理选择时发出警告;选择性路由请使用 merge 或 copy 模式。 +捆绑引用在两种模式下使用 audit 结构检查:缺失或未完成为警告,逃逸根目录为错误。沿用全局/项目 `audit-rules.yaml` 的禁用设置。JSON 的 `bundled_references` 包含规则 ID、源文件、行号与片段。参见[引用检查](../../understand/audit-engine.md)。 + ## 何时使用 - 某些功能无法工作,但你不知道原因 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/understand/audit-engine.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/understand/audit-engine.md index fa6ad9263..60260e473 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/understand/audit-engine.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/understand/audit-engine.md @@ -86,6 +86,7 @@ audit engine 会用 100 多条内置规则(正则表达式模式、表驱动 | `data-exfiltration` | 通过 `dig`/`nslookup`/`host` 结合子域名中的命令替换进行的 DNS 数据渗出 | | `self-propagation` | 将 payload 传播到其他文件或项目的自我复制指令 | | `hardcoded-secret` | 内联的 API 密钥、令牌和密码:Google API 密钥(`AIza...`)、AWS 访问密钥(`AKIA...`)、GitHub PAT(`ghp_`/`ghs_`/`github_pat_`)、Slack 令牌(`xox[bporas]-`)、OpenAI 密钥、Anthropic 密钥、Stripe 密钥、PEM 私钥块,以及带有高熵值的通用 `api_key`/`secret_key`/`password` 赋值 | +| `reference-escapes-root` | 显式引用解析到 skill 目录之外 | > **为什么是 high?** 隐藏的 Unicode 字符可以让恶意指令在代码审查中不可见。双向文本控制字符可以重新排列可见文本以伪装恶意代码(Trojan Source)。Base64 混淆是绕过人工检查的常见手段。像 `rm -rf /` 这样的破坏性命令可能造成不可逆的损害。`curl | bash` 是经典的远程代码执行向量——获取的内容会直接在你的 shell 中运行。配置/记忆文件污染会跨 AI 会话持续存在。DNS 渗出将窃取的数据编码在子域名查询中。自我传播指令会制造仓库蠕虫。skill 文件中的硬编码机密(API 密钥、令牌、私钥)表明凭证已泄露或存在故意的凭证暴露——两者都是应该审查的供应链风险。 @@ -146,19 +147,24 @@ audit engine 会用 100 多条内置规则(正则表达式模式、表驱动 这些是严重程度较低的指标,会计入风险评分和报告: - `LOW`:较弱的可疑模式(例如命令中的非 HTTPS URL——存在中间人攻击的可能) +- `LOW`: 无法检查的引用也会报告为 LOW `reference-check-incomplete`。 - `LOW`:**外部链接**——指向外部 URL(`https://...`)的 markdown 链接,可能表明存在 prompt injection 向量或不必要的 token 消耗;本地链接(localhost)除外 -- `LOW`:**悬空的本地链接**——目标文件或目录在磁盘上不存在的失效相对 markdown 链接 +- `LOW`:**缺失的捆绑引用**——Markdown 链接、图片、显式或行内路径的目标不存在 - `LOW`:**content-missing** / **content-unexpected**——内容完整性问题(见上文) - `INFO`:诸如 shell 链式命令模式等上下文提示(用于分诊/可见性) - `INFO`:**低可分析性**——skill 内容中可审计文本的占比低于 70%(见 [Analyzability Score](#analyzability-score)) > 这些发现结果不会阻止安装,但会提高整体风险评分。有大量 LOW/INFO 发现结果的 skill 可能值得更仔细的检查。 -#### 悬空链接检测 +#### 捆绑引用检查 -audit engine 还会对 `.md` 文件执行**结构性检查**:提取所有内联 markdown 链接(`[label](target)`),并验证本地相对目标在磁盘上是否存在。外部链接(`http://`、`https://`、`mailto:` 等)和纯锚点(`#section`)会被跳过。 +结构分析器检查本地 Markdown 链接和图片,包括引用式链接。内联代码中,检查具有文件扩展名、不含空白或 glob/模板语法且以 `./`、`../`、`scripts/`、`references/` 或 `assets/` 开头的路径,以及显式 `path:` 声明。标记为 `skillshare-paths` 的代码围栏中每行检查一个路径。未显式声明的无扩展名示例、普通标识符、其他代码围栏、未显式声明的绝对路径代码示例、URL(包括 `file:` URI)和纯锚点是有意排除的例外。必需的绝对路径应使用 Markdown 链接或显式 `path:` 声明。 Markdown 链接和图片相对于所在文档的目录解析。内联代码路径、`path:` 声明和 `skillshare-paths` 条目以 `./` 或 `../` 开头时也相对于所在文档解析;其他相对代码路径相对于 skill 根目录解析,嵌套 Markdown 文件中也一样。 -这能捕获常见的质量问题,如缺失的引用文件、重命名的路径或不完整的 skill 打包。每个失效链接会产生一条 `LOW` 严重级别、模式为 `dangling-link` 的发现结果。 +缺失目标保留 LOW `dangling-link` 标识。父目录遍历、主目录路径、Windows 驱动器路径或符号链接组件离开 skill 目录时,产生 HIGH `reference-escapes-root`。允许捆绑目录内的绝对路径,也识别从声明的根目录及其符号链接父目录导出的等价写法(例如 macOS 的 `/var` 与 `/private/var`)。检查在声明的根目录内使用有界的 `lstat`/`readlink`,不会读取引用文件的内容。不支持的路径、不可读元数据、符号链接循环或解析超限会产生 LOW `reference-check-incomplete`,而不会声称目标缺失或安全。限制为每个路径 4,096 字节、256 个组件步骤和 40 次符号链接跳转。Windows 原生分隔符会被规范化;在其他主机上,除可识别的 Windows 驱动器逃逸外,不支持反斜杠路径。保留原始行号与代码片段。 离开捆绑目录的隐式行内代码示例会被忽略,末尾的 `:line` 会被移除。 + +`/docs/foo` 等站点根链接指向技能目录之外时,现在产生 HIGH `reference-escapes-root`,而非原来的 LOW `dangling-link`。使用 `--threshold high` 时可能被阻止。 + +三个规则 ID 都支持在 `audit-rules.yaml` 中设置 `enabled: false`,沿用其他结构检查的全局/项目规则层。`doctor` 复用此分析器:缺失或未完成的引用为警告,逃逸为错误,`doctor --json` 将其记入 `bundled_references`。两种模式中发现的 skill 都适用。 ## 威胁类别深入分析 diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/learn/with-playground.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/learn/with-playground.md index 98625cd7e..8969eadea 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/learn/with-playground.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/learn/with-playground.md @@ -38,7 +38,7 @@ make playground | `audit-demo-ci-release` | `security/` | HIGH + MEDIUM(sudo、外部 URL) | | `audit-demo-debug-exfil` | `security/` | CRITICAL(憑證外洩) | | `audit-demo-external-link` | `security/` | LOW(外部 URL) | -| `audit-demo-dangling-link` | `security/` | LOW(失效的本機連結) | +| `audit-demo-dangling-link` | `security/` | LOW(缺少連結)+ HIGH(超出根目錄) | ### Demo Project (`~/demo-project`) diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md index 833ee1060..cebd9fca3 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit-rules.md @@ -284,7 +284,7 @@ skillshare audit --json | jq '.skills[].findings' # Inspect findings programmat :::note 結構性、分層與跨 skill 檢查 -`dangling-link`、`content-tampered`、`content-oversize`、`content-missing` 與 `content-unexpected` 是**結構性檢查**(檔案系統查找與雜湊比對,並非正規表示式)。`low-analyzability` 是由 [Analyzability Score](/docs/understand/audit-engine#analyzability-score) 產生的**可分析性發現項目**。`tier-stealth`、`tier-destructive-network`、`tier-network-heavy`、`tier-interpreter` 與 `tier-interpreter-network` 是由 [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) 設定檔產生的**分層組合發現項目**。`cross-skill-*` 發現項目是由 [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection) 產生。以上這些都會出現在下方表格中,但並未定義於 `rules.yaml` 中。 +`dangling-link`、`reference-escapes-root`、`reference-check-incomplete`、`content-tampered`、`content-oversize`、`content-missing` 與 `content-unexpected` 是**結構性檢查**(檔案系統查找與雜湊比對,並非正規表示式)。`low-analyzability` 是由 [Analyzability Score](/docs/understand/audit-engine#analyzability-score) 產生的**可分析性發現項目**。`tier-stealth`、`tier-destructive-network`、`tier-network-heavy`、`tier-interpreter` 與 `tier-interpreter-network` 是由 [Command Safety Tiering](/docs/understand/audit-engine#command-safety-tiering) 設定檔產生的**分層組合發現項目**。`cross-skill-*` 發現項目是由 [Cross-Skill Interaction Detection](/docs/understand/audit-engine#cross-skill-interaction-detection) 產生。以上這些都會出現在下方表格中,但並未定義於 `rules.yaml` 中。 ::: @@ -384,6 +384,8 @@ skillshare audit --json | jq '.skills[].findings' # Inspect findings programmat | `insecure-http-0` | insecure-http | LOW | | `external-link-0` | external-link | LOW | | `dangling-link` | dangling-link | LOW | +| `reference-escapes-root` | reference-escapes-root | HIGH | +| `reference-check-incomplete` | reference-check-incomplete | LOW | | `content-tampered` | content-tampered | MEDIUM | | `content-oversize` | content-oversize | MEDIUM | | `content-missing` | content-missing | LOW | diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit.md index 558c98b15..d35da0f13 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/audit.md @@ -137,7 +137,7 @@ skillshare audit --analyzer static --analyzer dataflow # Multiple analyzers | `tier` | Per-skill | 能力層級組合的風險分析 | | `integrity` | Per-skill | 內容雜湊驗證(SKILL.md 中的 `file_hashes`) | | `metadata` | Per-skill | 供應鏈信任驗證(發布者不符、權威性宣稱) | -| `structure` | Per-skill | 偵測失效的 markdown 連結 | +| `structure` | Per-skill | 檢查本機 Markdown 連結/圖片與明確宣告的套件路徑是否缺失,並偵測指向根目錄外的參照 | | `cross-skill` | Bundle | 跨 skill 的資料外洩與權限提升分析 | 你也可以在 config 中設定: diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/doctor.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/doctor.md index 478876ee3..5787efc3c 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/doctor.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/reference/commands/doctor.md @@ -59,6 +59,8 @@ Next 對於包含代理變體的追蹤儲存庫,Source 行顯示 `N skills, M variants`,分別代表邏輯技能數與實體副本數。`variant_routing` 檢查會在 symlink 模式公開所有變體而未依代理選擇時發出警告;選擇性路由請使用 merge 或 copy 模式。 +套件參照在兩種模式下使用 audit 結構檢查:遺失或未完成列為警告,逸出根目錄列為錯誤。沿用全域/專案 `audit-rules.yaml` 的停用設定。JSON 的 `bundled_references` 包含規則 ID、來源檔案、行號與片段。請參閱[參照檢查](../../understand/audit-engine.md)。 + ## 何時使用 - 有東西無法運作但你不知道原因 diff --git a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/understand/audit-engine.md b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/understand/audit-engine.md index 701f442f2..04669fca3 100644 --- a/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/understand/audit-engine.md +++ b/website/i18n/zh-Hant/docusaurus-plugin-content-docs/current/understand/audit-engine.md @@ -86,6 +86,7 @@ Audit engine 會把 skill 目錄中每個以文字為主的檔案,拿去比對 | `data-exfiltration` | 透過 `dig`/`nslookup`/`host`,在子網域中使用命令替換進行 DNS 資料外洩 | | `self-propagation` | 把 payload 散播到其他檔案或專案的自我複製指令 | | `hardcoded-secret` | 內嵌的 API 金鑰、token 與密碼:Google API 金鑰(`AIza...`)、AWS access key(`AKIA...`)、GitHub PAT(`ghp_`/`ghs_`/`github_pat_`)、Slack token(`xox[bporas]-`)、OpenAI 金鑰、Anthropic 金鑰、Stripe 金鑰、PEM 私鑰區塊,以及高熵值的一般 `api_key`/`secret_key`/`password` 賦值 | +| `reference-escapes-root` | 明確參照解析到 skill 目錄之外 | > **為什麼是 high?** 隱藏的 Unicode 字元可以讓惡意指令在程式碼審查時看不見。雙向文字控制字元可以重新排列可見文字以偽裝惡意程式碼(Trojan Source)。Base64 混淆是常見的規避人工檢查手法。像 `rm -rf /` 這樣的破壞性命令可能造成無法復原的損害。`curl | bash` 是經典的遠端程式碼執行向量 — 抓取的內容會直接在你的 shell 中執行。Config/記憶檔案下毒會跨 AI session 持續存在。DNS 外洩把竊取的資料編碼在子網域查詢中。自我複製指令會建立 repository worm。Skill 檔案中的硬編碼機密資料(API 金鑰、token、私鑰)代表憑證已外洩或是刻意暴露憑證 — 兩者都是應該被審查的供應鏈風險。 @@ -146,19 +147,24 @@ Audit engine 會把 skill 目錄中每個以文字為主的檔案,拿去比對 這些是嚴重程度較低的指標,會計入風險評分與報告: - `LOW`:較弱的可疑模式(例如命令中的非 HTTPS URL — 可能有中間人攻擊風險) +- `LOW`: 無法檢查的參照也會報告為 LOW `reference-check-incomplete`。 - `LOW`:**外部連結** — 指向外部 URL(`https://...`)的 markdown 連結,可能代表 prompt injection 向量或不必要的 token 消耗;localhost 連結不列入 -- `LOW`:**失效的本機連結** — 目標檔案或目錄在磁碟上不存在的損毀相對 markdown 連結 +- `LOW`:**遺失的套件參照** — Markdown 連結、圖片、明確或行內路徑的目標不存在 - `LOW`:**content-missing** / **content-unexpected** — 內容完整性問題(見上方) - `INFO`:情境提示,例如 shell 串接模式(供分流/可見度使用) - `INFO`:**低可分析性** — skill 內容中可稽核的文字不到 70%(見 [Analyzability Score](#analyzability-score)) > 這些發現不會封鎖安裝,但會提高整體風險評分。有大量 LOW/INFO 發現的 skill 可能值得更仔細的檢查。 -#### 失效連結偵測 +#### 套件參照檢查 -Audit engine 也會對 `.md` 檔案執行**結構檢查**:擷取所有內嵌的 markdown 連結(`[label](target)`),並驗證本機相對目標是否存在於磁碟上。外部連結(`http://`、`https://`、`mailto:` 等)與純錨點(`#section`)會被略過。 +結構分析器會檢查本機 Markdown 連結與圖片,包括參照式連結。行內程式碼會檢查具有副檔名、不含空白或 glob/範本語法且以 `./`、`../`、`scripts/`、`references/` 或 `assets/` 開頭的路徑,以及明確的 `path:` 宣告。標記為 `skillshare-paths` 的程式碼圍欄每行檢查一個路徑。未明確宣告的無副檔名範例、一般識別字、其他程式碼圍欄、未明確宣告的絕對路徑程式碼範例、URL(包括 `file:` URI)與純錨點均為刻意排除的例外。必要的絕對路徑應使用 Markdown 連結或明確的 `path:` 宣告。 Markdown 連結與圖片相對於所在文件的目錄解析。行內程式碼路徑、`path:` 宣告與 `skillshare-paths` 項目以 `./` 或 `../` 開頭時也相對於所在文件解析;其他相對程式碼路徑相對於 skill 根目錄解析,巢狀 Markdown 檔案中也一樣。 -這能抓出常見的品質問題,例如遺失的參照檔案、改名的路徑,或不完整的 skill 打包。每個損毀連結都會產生一筆模式為 `dangling-link` 的 `LOW` 嚴重程度發現。 +遺失的目標保留 LOW `dangling-link` 識別。父目錄遍歷、家目錄路徑、Windows 磁碟機路徑或符號連結元件離開 skill 目錄時,會產生 HIGH `reference-escapes-root`。允許套件目錄內的絕對路徑,也辨識從宣告的根目錄及其符號連結父目錄導出的等價寫法(例如 macOS 的 `/var` 與 `/private/var`)。檢查在宣告的根目錄內使用有上限的 `lstat`/`readlink`,不會讀取參照檔案的內容。不支援的路徑、無法讀取的中繼資料、符號連結循環或解析超過上限會產生 LOW `reference-check-incomplete`,不會宣稱目標遺失或安全。上限為每個路徑 4,096 位元組、256 個元件步驟與 40 次符號連結跳躍。Windows 原生分隔符會正規化;在其他主機上,除了可辨識的 Windows 磁碟機逸出,不支援反斜線路徑。保留原始行號與片段。 離開套件目錄的隱含行內程式碼範例會被忽略,末尾的 `:line` 會被移除。 + +`/docs/foo` 等網站根連結指向技能目錄之外時,現在會產生 HIGH `reference-escapes-root`,而非原本的 LOW `dangling-link`。使用 `--threshold high` 時可能被封鎖。 + +三個規則 ID 都支援在 `audit-rules.yaml` 設定 `enabled: false`,沿用其他結構檢查的全域/專案規則層。`doctor` 共用此分析器:遺失或未完成的參照列為警告,逸出列為錯誤,`doctor --json` 將其記錄在 `bundled_references`。兩種模式中探索到的 skill 都適用。 ## 威脅類別深入解析