Adds pmg proxy command group for running a long-lived MITM proxy that
intercepts all package manager traffic without requiring PMG shims or
wrappers. Targets CI/CD pipelines where env vars can be set globally.
- pmg proxy start: starts proxy with npm+pypi interceptors, writes
state file (pid/addr/ca-cert-path), auto-blocks suspicious packages
- pmg proxy stop: sends SIGTERM to the running proxy
- pmg proxy env: emits HTTP_PROXY/HTTPS_PROXY/SSL_CERT_FILE etc. as
shell exports, or writes directly to $GITHUB_ENV with --gha
- pmg proxy status: shows running/stopped status
GHA usage:
pmg proxy start &
pmg proxy env --gha # populates env for all subsequent steps
npm install # intercepted automatically, no wrapper needed
Also adds .github/workflows/persistent-proxy-e2e.yml to validate the
persistent proxy mode end-to-end in CI.
* fix(shim): recognize shims at arbitrary paths via PMG_SHIM_PATH
The recursion guard in FilterPMGFromPath hardcoded the `/.pmg/bin`
suffix, so shims placed anywhere else (e.g. `/usr/local/lib/pmg/bin`,
`/shims`, or any future system-wide location) would not be stripped
from PATH when PMG resolved the real package manager. The shim would
resolve back to itself and PMG would re-exec it in an infinite loop.
This blocks moving shims out of `~/.pmg/bin` — needed for a future
`pmg setup install --system` (#317) — and also any user attempt to
relocate shims manually.
Have the shim export its own path before exec'ing pmg, and let the
filter use that to strip the exact dir at runtime. Keep the legacy
suffix check as a fallback so already-installed shims keep working
until they are regenerated.
Also drop `PMG_SHIM_PATH` from the env passed to the real package
manager so child processes don't inherit a stale marker.
* docs(shim): clarify PMG_SHIM_PATH is internal and unsupported to set manually
* remove comment
* update comment
* feat: Add support for background sync
* refactor: Maintain single source of truth for command defn
* fix: Code review fixes
* fix: Code review fixes
* docs: Add corner case inline doc
* feat: add ProxyConfig struct with per-PM skip_commands and legacy fallback
* feat: consolidate proxy config into structured section with backward compat
Replaces flat proxy_mode/proxy_install_only keys with a structured proxy
section supporting per-package-manager skip_commands. Legacy keys are
respected via fallback when user's config lacks the new proxy section.
Removes deprecated experimental_proxy_mode config and flag.
* fix: env var resolution for nested config keys and deduplicate skip command matching
- Add "." to "_" in Viper env key replacer so nested keys like
sandbox.enabled resolve from PMG_SANDBOX_ENABLED (was silently broken)
- Export IsFirstNonFlagArgInList and remove duplicate from proxy_flow.go
- Add table-driven tests for skip command matching with real-world cases
- Remove redundant env var test
* docs: update proxy configuration and env var documentation
Update config.md env var table to reflect new proxy.enabled and
proxy.install_only keys. Add proxy configuration section to proxy.md
covering config structure, per-PM skip commands, CLI flags, and env vars.
* fix: legacy fallback precedence
* feat: Log PMG version and config details in debug mode
Logs the full execution context on startup when --debug is enabled,
including the command invocation, version/build info, OS/arch, and
all key config values so that bug reports with debug logs are
self-contained.
* collect debug context at end
* feat: Add dependency cooldown for npm packages
Strip recently-published package versions from npm registry metadata
responses so npm's resolver naturally falls back to older versions.
Overrides the Accept header to force full packument responses (which
include the "time" field needed for publish-date checks).
Reports cooldown blocks only when all versions are stripped (remaining == 0),
matching npm's --min-release-age behavior for silent fallback.
* fix: Report oldest version in cooldown block (shortest wait)
When all versions are blocked by cooldown, report the oldest version
since it exits the cooldown window first — giving the user the
shortest wait time instead of the longest.
* fix: Handle resp.Body.Close error return for errcheck linter
* test: Add dependency cooldown assertions to template config tests
* fix: config template for dependency cooldown
* fix: Prevent npm from caching cooldown-stripped metadata responses
* fix: Restore body on ReadAll failure and log Close errors in response modifier
* fix: Close response body before replacing to prevent connection leak
* fix: Correct daysLeft ceiling math and update ContentLength on error recovery
* fix: Clear Status on status code change and update ContentLength in modifier error path
* refactor: address review comments on dependency cooldown PR
- Make NpmCooldownHandler and constructor package-private
- Pass cooldown days as parameter instead of reading config internally
- Convert standalone functions to methods on npmCooldownHandler
- Set Accept-Encoding: identity to prevent gzip responses breaking JSON parsing
- Return 503 with descriptive message when upstream body read fails
* fix: log errors in stripCooldownVersions instead of swallowing them
* fix: Config preserve fallback defaults
* fix: Code review fixes
* fix: correct cooldown tip to show wait time instead of incorrect trusted_packages advice
* fix: prevent integer overflow in cooldown duration calculation with large days values
* refactor: deduplicate CooldownBlock into internal/models, fix misleading variable names
- Move CooldownBlock struct to internal/models to eliminate duplication
between proxy/interceptors and internal/ui packages
- Simplify proxy_flow.go by using direct assignment instead of field copy
- Rename latestStripped/latestDate to oldestVer/oldestDate for clarity
* fix: Dependency Cooldown Check Encapsulation (#207)
* fix: Encapsulate cooldown check
* feat: Add --skip-dependency-cooldown override
* fix: Code review fixes
---------
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
* define contract for package executors
* introduce npx executor
* add npx and pnpx cmd support
* fix typo
* rm PackageExecutor and depend on PackageManager interface
* add support for PTY to handle parent-child process interaction
* refactor PTY handling in proxy flow
* enforce interactiveSession interface check
* close reader explicitly and clean npm version for pkg executors
* rm interaction from interceptors
* add docs and wait for outputRouter before exit
* add support for non interactive TTY for proxy mode
* add support for CI env var check for non interactive tty proxy mode
* update readme to include npx, pnpx support
* Update internal/flows/proxy_flow.go
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
* update ptyx lib
* fix docs typo
---------
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* introduce a persistent config
* add tests and refactor config creation
* update config handling and add support for removing config
* add support to skip suspicious pkgs marked as trusted
* add support for config dir Env & unexport functions
* small fixes
* add assert for dir
* fix tests
* fix shell source line & trusted pkgs parsing
* fix flag inconsistency
* update config to read on each invocation and create if does not exist
* fix flags value being overridden
* remove redundant func call
* modify trusted pkg check to be config bound
* modify RemoveConfig to rm files & not dir. add tests for paths.go
* add versions for package for e2e
* modify tests to reset config
* fix: Simplify config persistence
* fix: Misc comments
* fix: Misc fix
* fix: Do not overwrite config file if exists
* fix: Do not overwrite config file if exists
* fix: Config cobra command should override and not replace
* fix: Create dir before writing config template
* fix: Create dir before writing config template
* fix: Misc refactoring
* test: Add test for is trusted package version
* Update cmd/setup/setup.go
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Abhisek Datta <abhisek.datta@gmail.com>
* Update config/config.go
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Abhisek Datta <abhisek.datta@gmail.com>
* Apply suggestion from @Copilot
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Abhisek Datta <abhisek.datta@gmail.com>
* fix: Remove unused constant in config
* fix: Resolve conflict with event logger
* docs: Add doc for eventlogger.Logger interface
* test: Add E2E for config file creation
* fix: Code review fixes
---------
Signed-off-by: Abhisek Datta <abhisek.datta@gmail.com>
Co-authored-by: Sahilb315 <bansalsahil315@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Add comprehensive event logging system with OS-specific location and rotation
Features:
- Event logging for security-relevant events (malware detection, installations)
- OS-specific default log locations (~/.pmg/logs/ on macOS/Linux, %LOCALAPPDATA%\pmg\logs\ on Windows)
- Automatic 7-day log rotation with daily log files (YYYYMMDD-pmg.log format)
- Support for custom log files via --log flag
- Thread-safe JSON logging with zero external dependencies
Implementation:
- New internal/eventlog package with comprehensive logging functionality
- Integration with guard.go to log malware detections and blocks
- Integration with main.go for initialization and cleanup
- Log file naming: YYYYMMDD-pmg.log (e.g., 20251216-pmg.log)
- Fail-safe design - PMG continues if logging fails
Event Types:
- malware_blocked: Malicious package blocked from installation
- malware_confirmed: User proceeded with flagged package
- install_allowed: Clean package installation allowed
- install_started: Package manager command initiated
- error: Error events
Testing:
- Comprehensive test suite with 6 passing tests
- Verified with real malware detection (e.g., @postman/tunnel-agent)
- Works with all package managers (npm, pip, etc.)
Technical Details:
- Thread-safe with mutex protection
- JSON format for easy parsing
- Automatic cleanup of logs >7 days old
- Background cleanup goroutine
- Uses only Go standard library (encoding/json, os, path/filepath, sync, time)
* Add update command support and improve event logging robustness
Features:
- Add support for npm/pnpm/bun/yarn update/upgrade/ci commands
- These commands now scan packages for malware before updating
- Closes security gap where update commands bypassed PMG protection
Improvements:
- Make event logging more defensive (graceful failure when not initialized)
- Add nil check for packageManager in guard to prevent test failures
- Add comprehensive tests for update commands
Testing:
- All 33+ unit tests passing
- Integration tests verified with real malware detection
- Tested with npm update, npm ci, npm upgrade, pnpm update, yarn upgrade
Files changed:
- packagemanager/npm.go: Added update/upgrade/ci to InstallCommands
- packagemanager/npm_test.go: Added 4 new test cases for update commands
- guard/guard.go: Added nil check for packageManager
- internal/eventlog/eventlog.go: Made logging more defensive
* Address review feedback: use log.Warnf instead of silently failing
Replace silent error handling in cleanupOldLogs with log.Warnf
to avoid completely swallowing errors when reading log directory.
Fixes reviewer feedback from abhisek.
* Remove update/upgrade command support, keep logging improvements
- Remove update/upgrade/ci commands from InstallCommands for npm, pnpm, bun, yarn
- Remove special handling for update/upgrade/ci commands in ParseCommand
- Remove update command test cases and restore original test
- Preserve logging improvements (nil check in guard.go, defensive check in eventlog.go)
All tests passing.
* Add support for yarn package manager
- Added yarn command handler in cmd/npm/yarn.go
- Added DefaultYarnPackageManagerConfig() in packagemanager/npm.go
- Added yarn dev flag support (--dev/-D) in ParseCommand()
- Added yarn analytics tracking in internal/analytics/event.go
- Registered yarn command in main.go
- Added yarn to alias setup in internal/alias/alias.go
- Added comprehensive test suite in packagemanager/yarn_test.go
- All tests passing (12 yarn tests + existing tests)
Resolves#30
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
* docs: update README with yarn package manager support
Updated documentation to reflect yarn support addition:
- Changed yarn status from '🚧 Planned' to '✅ Active' in package managers table
- Added 'pmg yarn add <package>' command example
- Added 'yarn add <package-name>' to command list
- Added 'yarn install # Uses yarn.lock' to lockfile examples
This documentation update corresponds to the yarn implementation in the previous commit.
Related to #30
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
* fix: address review feedback for yarn support
- Add support for bare 'yarn' command as manifest install
- Validate yarn install does not accept package names
- Add YarnExtractor for yarn.lock file support
Changes:
- packagemanager/npm.go: Added bare yarn command handling and validation
- packagemanager/yarn_test.go: Added test for bare yarn command
- extractor/ecosystems.go: Added Yarn PackageManagerName and extractor
- extractor/npm.go: Added YarnExtractor implementation
- go.mod, go.sum: Updated dependencies
Addresses review feedback from @Sahilb315
- Bare yarn command now triggers manifest install per docs
- yarn install <package> is now properly rejected
- yarn.lock extraction support added
Related to #30
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
* chore: tidy go.mod and go.sum to remove unused dependencies
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
* fix: add yarn.lock extractor mapping
- Add yarn.lock case in getExtractorForFile switch
- Import yarnlock extractor from osv-scalibr
- Enables lockfile parsing for manifest-based installations
Tested both package-based and manifest-based installations successfully.
Addresses review feedback from @Sahilb315
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
* test: add validation test for yarn install with package name
- Add test case to verify 'yarn install <package>' is rejected
- Ensures invalid syntax returns no install targets
- Confirms IsManifestInstall is false for invalid commands
Addresses review feedback from @Sahilb315
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
---------
Signed-off-by: shrvansudhakara <shrvansudhakara@gmail.com>
* follow proper consistent naming in pypi packagemanager
* follow proper consistent naming in pypi packagemanager - 2
* feat: add specialized command parsers to handle pip and uv command formats
* add uv support & modify extractor to be more robust
* add uv alias
* refactor var name & add error handling
* update readme & add support for `uv pip sync` cmd