* fix(deps): update golang.org/x modules to latest on the Go 1.25 line
Clears the x/crypto, x/net, x/sys and x/text vulnerability findings
reported against the pmg binary by image scanners.
Deliberately kept back: the go directive stays 1.25.1 because the Go
1.26 move is blocked on goproxy URL parsing (see #390), and grpc stays
pinned at v1.81.0 due to the trailers regression with v1.82.x.
* fix(container): move runtime base to debian 13 and refresh builder pin
The bullseye runtime base and the stale golang:1.25-bookworm digest
(go1.25.5) accounted for most of the vulnerability findings in the
published image. debian:13-slim is current stable and the refreshed
golang digest carries go1.25.12, covering every flagged stdlib CVE.
* feat(sandbox): report landlock seccomp denials via pmg sandbox violations
The landlock driver's seccomp supervisor already emitted structured deny
events over the audit socket, but the driver drained them to io.Discard, so
the violation cache was never populated on Linux and violations list /
explain always came up empty.
Capture the events at the driver, enrich them with access mode and process
name, and implement BestEffortViolation mirroring the seatbelt reporter:
failure-only collection, seccomp_deny events only, (kind, target) dedupe.
The platform-neutral cache/list/explain pipeline picks it up unchanged.
Only the seccomp deny-list layer is observable; denials made by the
Landlock LSM itself (allow-list boundary, delete/rename, network) fail
in-kernel with no userspace signal and are documented as out of scope.
Also make the explain renderer driver-neutral: the raw-log label was
hardcoded as "Seatbelt log" and an empty correlation ID printed a blank
value.
* fix: address review findings on landlock violation reporting
Report the deny rule that fired, not the requested access: an O_RDWR open
denied by a read-only rule now surfaces as a read denial with an effective
override suggestion (allow write= prunes only deny_write). The matched rule
path is emitted as rule_path and mapped to RuleTarget, bringing the
"Matched rule:" line to parity with seatbelt.
Dedupe deny events by (kind, path) at capture time so a retry loop on one
denied path cannot fill the buffer and evict a later distinct denial; the
cap now bounds distinct denials.
Stamp deny events with a timestamp (they rendered "ts":0 in the raw log)
and default unknown syscalls to generic_deny instead of fs_write.
* refactor: single source for the deny dedupe key
Capture-time and extract-time dedupe must agree on what identifies a
denial; building the key in two places risks them drifting apart.
* fix: bound the capture dedupe map by marking keys only on append
seen grew for every distinct deny key even after the buffer was full,
and keys carry attacker-chosen path bytes — a hostile process looping
over crafted unique denied paths could grow the pmg parent's memory for
the run's duration, defeating the cap. Marking keys only when the event
is appended bounds the map at the cap and keeps the one-time drop
warning reachable for distinct denials past it.
* docs(sandbox): AppArmor userns fix for the Landlock driver on Ubuntu 23.10+
The shim fails with "install seccomp: ... permission denied" when
kernel.apparmor_restrict_unprivileged_userns=1. Document the per-binary
AppArmor profile as the recommended fix and the sysctl as the blunt
alternative.
* docs(sandbox): drop em dashes from the landlock sections
* fix(doctor): cover landlock in the AppArmor userns probe
The warn detail only named the bwrap failure and the only suggested fix
was the system-wide sysctl. Name the landlock shim error too and suggest
the per-binary AppArmor profile first, pointing at the new docs section.
* refactor: remove guard mode execution paths and guard-only packages
Guard (non-proxy) mode is removed; all package-manager commands now
always run the proxy flow. Removes the guard engine, the common flow,
the extractor package, the npm/pypi dependency resolvers and the
PackageResolver plumbing that only guard mode consumed.
The guard package retains only PackageManagerGuardInteraction, which
the proxy flow and confirmation interceptors reuse for user prompts.
Proxy behavior is unchanged.
* refactor: remove proxy opt-out surfaces, guard references in config, action and docs
Removes Config.ProxyMode, ProxyConfig.Enabled, IsProxyModeEnabled, the
proxy_mode legacy fallback, PMG_PROXY_ENABLED handling and the
--proxy-mode / --include-dev-dependencies flags. Proxy interception can
no longer be disabled.
Also removes the proxy-mode input from the GitHub Action, the
proxy-mode doctor check and setup info row, updates the E2E workflow to
stop passing --proxy-mode=false, and sweeps guard-mode wording from
docs and the config template.
The legacy proxy_install_only flat key and PMG_PROXY_INSTALL_ONLY env
var remain supported. audit.FlowTypeGuard is kept so previously
recorded audit events still translate for cloud sync.
* feat: fail loudly when a removed proxy opt-out is still configured
A leftover proxy.enabled: false / proxy_mode: false config key or
PMG_PROXY_ENABLED=false / PMG_PROXY_MODE=false env var previously meant
guard mode; silently ignoring it would switch those users to proxy
interception without notice. PMG now exits with an actionable error
naming the exact source. Precedence mirrors the old resolution order:
env (ignored under lockdown) > proxy.enabled > legacy proxy_mode.
The pmg config subtree is exempt so the config file can still be fixed
with pmg config edit/set. The GitHub Action's proxy-mode input is kept
as a tombstone that fails the action when set to false and warns
otherwise.
* refactor: extract flows.RunProxy and address review findings
Collapses the identical parse-then-run body duplicated across the 12
package manager commands into flows.RunProxy. Documents the cache-hit /
offline analysis trade-off versus the removed guard manifest path,
fixes a stale non-proxy label in the E2E workflow and a stale guard
reference in the uvx parser comment.
* fix(config): mirror old proxy opt-out precedence exactly
PMG_PROXY_MODE only ever took effect through the legacy fallback, which
was gated on the presence of a proxy: key in the config file (even a
null one). Promoting it to the top env tier caused two inversions: a
stale PMG_PROXY_MODE=false hard-failed configs that resolved to proxy
mode, and PMG_PROXY_MODE=true silently overrode an explicit
proxy.enabled: false file opt-out. The check now resolves in the old
order: PMG_PROXY_ENABLED > proxy: section (presence gates the legacy
tier) > PMG_PROXY_MODE > flat proxy_mode.
parseOptOutBool also accepts numeric values (0 = false) to match
viper's WeaklyTypedInput/cast.ToBool coercion, so proxy.enabled: 0 and
proxy_mode: 0 are detected as opt-outs.
* refactor: move package manager interaction out of guard
* refactor: trim package manager interaction
* fix(config): normalize config keys viper-style in proxy opt-out check
Viper resolved config file keys case-insensitively and expanded dotted
keys, so spellings like Proxy:, Enabled:, a literal proxy.enabled key or
Proxy_Mode selected guard mode before the removal. The opt-out check now
lowercases keys recursively and nests dotted keys before matching, so
those existing opt-outs fail loudly instead of being silently ignored.
* refactor: remove inert transitive controls, dead parser state and guard audit variant
transitive / transitive_depth lost their only consumers with the
dependency resolvers; remove the config fields, flags, template and doc
entries, and the report/audit plumbing that misreported transitive
analysis as enabled.
Remove write-only parser state (PackageInstallTarget.Extras,
ParsedCommand.ManifestFiles, ShouldExtractFromManifest); IsManifestInstall
stays as it feeds sandbox gating via IsInstallationCommand.
Remove audit.FlowTypeGuard and its cloud mapping; guard events recorded
by pre-removal versions in an unsynced WAL translate to UNSPECIFIED.
* fix: address review findings on the opt-out wiring and cleanups
Move the removed-opt-out rejection from the CLI PersistentPreRun into
proxyFlow.Run: the check now fires exactly for package-manager runs, so
non-install commands (pmg setup remove, doctor, config, version) stay
usable to fix or remove an opted-out installation, and future commands
inherit or avoid the check by construction instead of by exemption list.
Also: make the e2e malicious-package assertion actually fail the job
when an install is not blocked, route pmg go through flows.RunProxy,
and drop the dead extras return from pypiParsePackageInfo (extras are
still stripped from package names).
* fix(config): make the removed opt-out check faithful to the old resolution
The gate that silenced the legacy proxy_mode surfaces matched the raw
proxy key case-sensitively in the old code, while values resolved
viper-style (case-insensitive, dotted keys); applying each semantic
where the old code did fixes both divergences: a case-variant Proxy:
section no longer hides a flat proxy_mode: false opt-out, and a dotted
proxy.enabled: false overridden by proxy_mode: true no longer errors.
Replace the generic key-tree normalization with two targeted lookups
(the check only ever resolves proxy.enabled and proxy_mode), which also
makes colliding spellings resolve deterministically. Coerce legacy-tier
values cast.ToBool-style so PMG_PROXY_MODE=off style opt-outs are
detected, log the config read error instead of swallowing it, and
shorten the error to a one-line statement with the specific remedy in
the help text.
Add lockdown coverage (env inert both directions) and a repeated-run
determinism test.
* fix(config): fall back to defaults for unrecognized proxy opt-out values
The old loader swallowed viper errors and ran on defaults, so values
like proxy.enabled: yes or PMG_PROXY_ENABLED=banana silently discarded
the whole config and defaulted to proxy. Treat them the same way now:
unrecognized values mean the default (proxy on) instead of a hard
error, and the doc comment no longer claims the old loader failed
loudly. Only values that actually meant guard mode fail.
Also check the removed opt-out before the CA trust check in pmg go,
restoring the old error precedence: a config problem must not steer
the user into an unnecessary OS trust store change.
* fix(e2e): PMG_PROXY_MODE assertion must match the legacy gate semantics
The runner's setup step writes the template config, which has a proxy:
section — and with one present the legacy PMG_PROXY_MODE was always
inert, so expecting a loud failure there asserts pre-fidelity-fix
behavior. Assert both sides instead: inert (command succeeds) with the
standard config, loud failure against an empty config dir where the
legacy fallback actually applied.
* refactor(config): collapse parseOptOutBool to ParseBool over the string form
YAML hands us typed values (bool, int), so route them through
fmt.Sprintf %v and strconv.ParseBool instead of a per-type switch.
Identical behavior for every recognized value; numbers other than 0/1
now read as no opinion instead of cast.ToBool's nonzero-true, which no
real config relies on.
`pmg cloud sync` without usable credentials surfaced misleading errors:
missing credentials fell into the generic network fallback ("check your
network connectivity") and server-rejected credentials (gateway 403)
showed a bare "Permission denied" with no remediation.
Map dry's cloud.ErrMissingCredentials to a new CloudCredentialsNotFound
code pointing at 'pmg cloud login' and the SAFEDEP_API_KEY /
SAFEDEP_TENANT_ID environment variables, and rebrand authentication and
authorization failures with the same credential guidance. Entitlement,
quota and server errors still pass through unchanged.
The build stage ran natively on $BUILDPLATFORM and make never received a
target arch, so both manifest variants shipped the same amd64 binary
(#379). Pass TARGETOS/TARGETARCH into the build with CGO_ENABLED=0 and
verify each platform variant runs 'pmg version' after push.
Fixes#379
Claude-Session: https://claude.ai/code/session_01E8yrxjqVw7454zByb8kxvD
Co-authored-by: Claude <noreply@anthropic.com>
Switch the audit cloudSink from the authenticated SyncClientBundle to
dry's new emit-only endpointsync.EventEmitterClient. Normal command
invocations now persist events to the local cloud-sync WAL without
resolving credentials or opening a data-plane connection; delivery
still happens only through the authenticated sync paths (pmg cloud
sync, sync-background auto-sync, and the proxy daemon drain), which
are unchanged.
Previously, running with cloud.enabled but no credentials skipped the
cloud sink entirely, so no events were recorded. Those events are now
staged in the WAL and sync once the user authenticates.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
`pmg setup doctor` reported npm protection as OK on a machine with no npm
installed. Two compounding defects:
1. The availability gate used a plain `exec.LookPath`, which resolves the PMG
shim on PATH rather than the real binary, so the "skip" branch never fired.
It now uses `shim.ResolveRealBinary` (PATH with shim dirs stripped), matching
the runner, so a missing real binary correctly yields WARN "not available".
2. The result was inferred purely from a non-zero exit, so PackageManagerNotFound
(exit 127) and other failures were misread as a successful block. The check
now requires PMG's block headline in the captured output before reporting
PASS; other non-zero exits report WARN with the error surfaced.
The block headline is extracted into `ui.MalwareBlockedHeadline` so the doctor's
marker stays in sync with what PMG prints across its block-output sites.
* docs(specs): add custom block messages and package blocklist spec
* docs(specs): add custom block messages and package blocklist implementation plan
* feat(config): add blocked_packages list and custom block messages
* feat(audit): add package_blocklist_blocked event and blocklist model
* feat(proxy): block blocklisted packages in the policy gate before analysis
* feat(guard): block blocklisted packages before trust skip and analysis
* feat(ui): render blocklist blocks and custom messages, fix silent-mode block output
* feat(proxy): append custom messages to malware and go-cooldown block bodies
* test(proxye2e): cover blocklist enforcement and custom block messages
* docs(specs): remove spec and plan documents
* refactor: drop guard-flow blocklist enforcement and trim docs
Guard mode is being deprecated; the blocklist is enforced in proxy mode
only. Remove the trusted_packages mirroring references outside the docs.
* refactor(config): consolidate blocklist and block message under top-level block section
Replace dependency_cooldown.message, malware.message and blocked_packages
with a single block section: block.message is appended to every block
output regardless of which control blocked, and block.packages is the
package blocklist.
* fix(ui): render block.message as info note with clean spacing
* fix(ui): indent wrapped continuation lines in block reasons and messages
* update config template
* refactor(config): replace block section with top-level advisory_message
Remove the package blocklist (will be implemented as part of policies in
the future) and replace block.message with an optional top-level
advisory_message appended to every block output.
* chore(config): move advisory_message near top-level scalar configs in template
* fix: fail fast with clear error when package manager is not installed
When PMG shims intercept a package manager that isn't installed (e.g. a
clean JAMF-provisioned laptop where PMG is set up before dev tooling),
real-binary resolution failed with a generic "unknown" error and a
bug-report link, making it look like PMG itself had crashed.
Introduce a typed BinaryNotFoundError that exits with code 127 (standard
"command not found") and maps to a new PackageManagerNotFound error code
with an actionable message instead of the Unknown classification.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: improve missing package manager help message
Use a concise, dynamic install hint instead of explaining PMG's
PATH forwarding internals.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: mention PATH in missing package manager help text
Covers the common case where a package manager is installed but its bin
directory is not on PATH yet (e.g. after curl | bash install).
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* ci: add E2E for pmg action server-mode
Exercises the safedep/pmg action with server-mode enabled: the action
starts the proxy daemon and injects HTTP_PROXY + CA env vars, then bare
npm/pip installs are intercepted. Asserts benign installs pass, malicious
npm/pip installs are blocked, and 'pmg proxy stop --fail-on-violation'
fails the job on the blocks.
Scoped via paths to action.yml and the proxy server sources so it only
runs when relevant. Complements persistent-proxy-e2e.yml, which covers
the branch's proxy internals via raw pmg proxy commands.
* ci: extract shared proxy E2E assertions into composite action
Both the action server-mode E2E and the persistent-proxy E2E run the same
benign/malicious install assertions. Factor them into a local composite
action (.github/actions/proxy-e2e-assertions) so the assertions live in one
place and both workflows exercise the composite itself.
Proxy teardown (pmg proxy stop --fail-on-violation) stays inline in each
workflow since the setup/teardown differs per binary-under-test (released
binary via the action vs. branch build via make).
* feat(proxy): emit session summary on persistent proxy shutdown
The persistent proxy daemon never ran the per-invocation flow that calls
LogSessionComplete, so no session summary reached the cloud for server-mode
runs. Emit one from the daemon's aggregate stats collector on shutdown,
before the final cloud flush, so it is delivered with the run's events and
carries the CI/invocation context.
Extract the event emission into a shared LogSessionSummary(SessionData); both
the per-invocation flow and the daemon now use it. The daemon serves every
package manager, so the summary carries no single package manager.
* chore(action): shorten default cloud endpoint id prefix to gha/
* refactor(flows): extract SetupCACertificate for reuse
Move the CA load/generate/merge logic out of proxyFlow into an exported
flows.SetupCACertificate so the persistent proxy server can reuse it.
* feat(proxy): add persistent proxy server with start/stop/env/status
Introduces 'pmg proxy' commands backed by internal/proxyserver: a long-lived
MITM proxy that intercepts package managers via env vars (no shims). Supports
--daemon (Unix), --state, --port; generic 'env' output that skips cert vars
when the CA is OS-trusted; opt-in 'stop --fail-on-violation' (fail-closed on
crash) with a synchronous cloud event flush; and the malysis analysis cache.
* feat(action): add server-mode for persistent proxy
When server-mode=true the action starts the proxy daemon and injects proxy
env vars into the job instead of installing shims.
* test(proxy): add persistent proxy server E2E workflow
* docs(readme): document persistent proxy server mode
* fix(proxy): create cache dir before writing state file and daemon log
On a fresh CI runner the cache directory does not exist yet; os.OpenFile and
os.WriteFile do not create parent dirs, so 'pmg proxy start --daemon' failed
with 'no such file or directory'. MkdirAll the parent before writing.
* docs: add persistent proxy server architecture doc
* refactor proxyserver
* fix(proxy): always emit cert env vars instead of skipping on OS-trust status
npm/pip/yarn/requests trust the MITM CA inconsistently across tools, versions,
and configs; many still use bundled CA stores. Always emitting the cert-path
env vars is the conservative choice that works regardless, and is harmless for
tools that read the OS store (they ignore the vars). Skipping them when a
system CA exists would silently break any tool still on a bundled store.
* refactor(proxy): drop redundant audit init in daemon; rely on main.go
main.go's PersistentPreRun already initializes the audit pipeline for every
command (including the daemon's re-exec'd child) and closes it at process exit.
Re-initializing in proxyserver.Run created a second auditor and a second
cloud-sync WAL connection, orphaning the first. Removing it makes the daemon
consistent with the normal proxy flow, which never self-initializes audit.
* fix(proxy): bypass proxy env when flushing events to cloud on stop
pmg proxy stop inherits HTTP(S)_PROXY (injected by 'pmg proxy env') pointing at
the PMG proxy it just shut down. The cloud sync gRPC client honored those vars
and routed api.safedep.io through the dead proxy, failing with 'connection
refused' so no events were delivered. Clear the proxy env vars before the sync
so PMG's own cloud traffic goes direct.
* chore(proxy): address review feedback
- configurable bind host via proxy.server.listen_host (default loopback)
- proxy commands use ui.ErrorExit instead of returning errors to cobra
- rename errcode to ProxyPolicyViolation (covers malware + cooldown)
- share cloud sync via audit.DrainToCloud (de-dup with cmd/cloud/sync)
- centralize proxy CA bundle path in certmanager
- docs: persistent proxy cert trust + bind address
* fix(proxy): show real message on fail-on-violation error
stopExitError set only WithMsg, but ui.ErrorExit renders HumanError, so the
framed error showed 'no human-readable message available'. Set both from one
string, and emit the framed error before the stdout summary so the blocked
count is stated once.
* fix(proxy): flush cloud events from the daemon, not stop
The stop process inherits HTTP_PROXY (from 'pmg proxy env'), so its cloud
client routed api.safedep.io through the already-stopped proxy and failed with
connection refused. Move the flush into the daemon's shutdown, which has no
proxy env (it started before env injection) and dials SafeDep directly.
- daemon flushes on shutdown via audit.DrainToCloud and records the result in
the state file; stop surfaces it (on both success and fail-on-violation
paths) since the daemon's own logs aren't visible to stop
- coordinate stop's wait with the daemon shutdown budget; on timeout, error
out without reading stale state or deleting the file (fail-closed)
- persist blocked count before the flush so the gate stays correct if the
flush hangs or the daemon is killed mid-flush
- remove now-redundant cloud_flush.go
* disable auto-sync for proxy cmds
* feat(proxy): periodic cloud sync + move proxy env vars to packagemanager
- daemon runs a periodic cloud-sync ticker so the shutdown flush stays small;
the run total is reported by stop, and shutdown timeouts are coordinated
- move EnvVarForProxy from config to packagemanager (it is package-manager
knowledge); the shared function now builds the proxy URL and NO_PROXY itself,
removing the duplicated construction in the per-command and persistent paths
- relocate the #319 yarn and #339 IPv6 regression tests alongside the function
- enable cloud sync in the persistent-proxy E2E workflow and fix the stale
internal/proxystate path filter
* refactor(proxy): rename cloudFlushLockTimeout to cloudFlushLockWait
Consistent timeout naming: *LockWait is the lock-acquire bound, *Timeout is
the sync-RPC bound. Previously the final-flush pair was cloudFlushLockTimeout
vs cloudFlushTimeout — two lookalike names for different operations.
* refactor(proxy): extract cloudFlush and trim duplicate shutdown comments
The shutdown's final-flush block is now a cloudFlush helper, symmetric with
startCloudSyncLoop (one-shot vs loop). Removed the triplicated ticker/lock
contention comments, keeping the contract on the function doc and one-line
pointers at the call sites.
* docs: update persistent proxy cloud sync to daemon-owned model
The daemon now owns cloud delivery (periodic sync while serving + final flush
on shutdown); stop signals it, waits, and reports the result. Rewrite the Cloud
event sync section, fix stop attributions, add the cloud_sync state field, and
update the sequence diagram.
* docs: move Usage section up below How it works
Put the copy-paste recipes near the top so users find them before the internals.
* refactor(proxy): address PR review feedback
- configurable bind host/port via --host/--port flags + config (listen_host,
listen_port), bound directly to config fields per PMG's flag pattern
- daemon log path via --log-file and readiness timeout in ProxyDaemonConfig;
Daemonize no longer owns path policy (caller validates, fails fast)
- gate periodic cloud sync on auto_sync; suppress detached background sync for
proxy commands instead of flipping the flag
- pmg proxy env --export emits shell-quoted lines for eval (spaces survive)
- extract shared flows.BuildCachedMalysisAnalyzer, dropping the analyzer+cache
duplication between proxy flow and proxy server
- add internal/proxyserver/doc.go documenting the package + boundary vs flows
- E2E: assert malicious installs are blocked (drop continue-on-error)
- docs: trim Commands/State-file to user contracts; refresh bind address
* refactor(proxy): proactive alignment fixes from whole-PR review
- gate the shutdown cloud flush on auto_sync too, matching the periodic ticker
(auto_sync consistently controls all daemon-driven cloud delivery)
- ResolveStatePath takes cacheDir instead of *RuntimeConfig, keeping state.go
free of config dependency
- drop the empty-host comment in listenAddr; keep the loopback guard so a blank
host never silently binds all interfaces
* fix: Decouple localdb with malysis analyser construction
* fix: Persist global args before proxy server daemon exec
* fix: GitHub Action for cloud auto-sync in server mode
---------
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
* feat(cooldown): respect trusted_packages in dependency cooldown
Trusted packages are now treated as a superset waiver that bypasses every
PMG control (malware analysis, cooldown, and any future controls). A
globally trusted package is automatically exempt from the cooldown window
and no longer needs a duplicate entry in dependency_cooldown.skip.
The skip list remains the narrower, cooldown-only waiver for packages
that must bypass the cooldown wait but still be malware-scanned.
* refactor(cooldown): tag skip reason and audit-log skipped packages
Address review feedback on #342:
- Restore cooldownSkip to a pure single-list function (SRP); the merge
into trusted_packages now happens in a separate mergeCooldownSkip step,
driven by the exported CooldownSkip wrapper.
- Extend CooldownSkipInfo with a CooldownSkipReason (TrustedPackage /
CooldownSkipList) on both SkipAll and per-version entries, so callers
can tell apart the broad waiver from the cooldown-only one. When both
lists match the same package, trusted_packages wins.
- Add audit.LogCooldownSkipped and emit it from the npm and PyPI
interceptors on the SkipAll path, alongside the existing info log,
carrying the source list as the reason.
* refactor(cooldown): inline list merge, audit per-version exemptions
Address further review feedback:
- Drop the separate mergeCooldownSkip helper; cooldownSkip now writes
into a shared *CooldownSkipInfo and is called twice from CooldownSkip
(cooldown skip list first, trusted_packages on top so trusted entries
override the reason on overlap).
- Audit log every exemption, not just SkipAll: a new auditCooldownSkip
helper in proxy/interceptors/cooldown.go emits one event per match
(package-wide or per-version), each tagged with its source list.
LogCooldownSkipped gains a version argument for the per-version case.
- Cover the trusted_packages reason path in TestCooldownSkip.
* fix(cooldown): avoid double-auditing trusted package exemptions
auditCooldownSkip now only emits EventTypeCooldownSkipped for entries
that came from dependency_cooldown.skip. Trusted-package exemptions
already get an EventTypeInstallTrustedAllowed event at tarball-download
time (proxy/interceptors/base_registry.go), so emitting a cooldown event
for them too would double-count the same waiver.
* emit trusted and cooldown skip events to cloud
* fix tests
* refactor(cooldown): return value from collectCooldownSkip, short-circuit on trusted SkipAll
Address PR review feedback:
- Rename cooldownSkip to collectCooldownSkip and return CooldownSkipInfo
instead of mutating an input pointer.
- Add mergeCooldownSkip to combine per-list results with trusted_packages
taking precedence on overlap.
- CooldownSkip now consults trusted_packages first and returns immediately
on a package-wide trusted exemption (DC skip list cannot add anything).
- Extend tests to cover disjoint pinned entries across both lists and the
case where DC version-less subsumes a trusted pinned entry.
* fix(audit): address cooldown review feedback
* fix(cooldown): audit cooldown skips at download time with concrete version
Backend rejects PackageVersion messages without a version, and audit logs
should reflect the runtime fact (a specific version was skipped) rather
than the config rule. Move the audit emission from metadata-request
handling to download-request handling, where the concrete version is
known, and require version in LogCooldownSkipped.
* chore(audit): drop dead scope assignment in LogCooldownSkipped
* refactor(cooldown): move skip-list logic into cooldown handlers
Registry interceptors no longer compute CooldownSkip or branch on SkipAll;
they just call HandleMetadataRequest. The npm and pypi cooldown handlers
own the skip lookup, the package-wide exemption short-circuit, and (for
pypi) the canonical-name denormalization. Also align LogCooldownSkipped
with other LogXxx signatures by taking *packagev1.PackageVersion.
* fix: Simplify audit logging for dependency cooldown skip
* refactor: Simplify cooldown handling and maintain separation of concepts for trusted and DC skip packages
* fix: Code review fixes
* fix: Emit cooldown skipped audit event ONLY when an in-window version is skipped
---------
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
* 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
* fix(sandbox): bind parent dir for globstar allow_write on bwrap
Fine-grained per-path mounts under read-only project binds broke pip
install into in-project .venv directories. Always mount the parent tree
for ** write rules instead.
Fixes#315
* test(sandbox): tighten globstar bind assertions and ensure ~/.npm exists for e2e
Strengthen TestBubblewrapAllowWriteGlobstarBindsParentOnly to verify the
parent dir is writably bound and the child path is read-only bound, not
just substring presence. Pre-create ~/.npm in the e2e harness so
bubblewrap --bind-try does not skip the npm cache dir on fresh runners.
* switch pnpm to /tmp in sandbox e2e
* test(sandbox): update glob ** test for parent-bind semantics
Globstar allow_write now binds the parent dir only (e2e740d), so the
test should assert the parent is writably bound and child subdirs are
not individually bound, instead of substring-matching subdir names.
* fix(sandbox): bind correct base dir for in-pattern globstar allow_write
Globstar allow_write previously used extractGlobParentDir, which walks past
the first ** and yields the wrong root for patterns like /a/b/**/d/**/e.
Introduce extractGlobstarWriteBaseDir, which takes the prefix before the
first /**, and use it in processWriteRule. Also dedup the coarse-fallback
parent-bind loop to mirror the read-rule fallback.
* feat: add CloudSinkEnvResolver interface with default implementation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add GitHub Actions environment resolver for cloud sink
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: populate invocation context with CI environment on cloud events
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address lint errors in cloud sink tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: use getter-based CloudSinkCIResolver with nil-when-no-CI
Rename to CloudSinkCIResolver with focused CI concern. Factory returns
nil when no CI is detected, removing the need for IsCI() and a default
resolver. Leaves room for a separate agent resolver in the future.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add CI metadata support using updated API SDK
Update SDK to include SetMetadata on EndpointCIContext. Add Metadata()
to CloudSinkCIResolver interface and GitHub Actions implementation
(workflow, job, run_attempt, server_url). Wire metadata into
buildInvocationContext.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: address review comments on CI resolver
- Inject CloudSinkCIResolver as dependency into newCloudSink for testability
- Check both GITHUB_ACTIONS and GITHUB_RUN_ID for GHA environment detection
- Make factory and constructor package-private (newCloudSinkCIResolver,
newGithubActionsCIResolver)
- Attach invocation context only to session complete events, not every event
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: fail fast on os.Getwd error instead of swallowing it
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: avoid resolving symlinks in shim PMG binary path
Shims hardcoded the resolved Cellar path (e.g.
/opt/homebrew/Cellar/pmg/0.16.0/bin/pmg) instead of the stable
Homebrew symlink. This broke all shims after `brew upgrade` since
the old Cellar directory is removed.
Fixes#302
* fix pip test pkg version
PMG was forcing Accept: application/vnd.pypi.simple.v1+json on all
Simple API requests regardless of client capability. Older pip versions
(< 22.3) that only understand text/html would reject the JSON response,
breaking installs entirely.
Now checks the client's original Accept header before applying cooldown.
If PEP 691 is not supported, the request passes through unchanged with
a warning log recommending pip upgrade.
* feat: add doctor check runner core types and logic
* feat: add doctor checks for config, binary, directory, and aliases
* feat: add doctor checks for sandbox and security features
* feat: add protection verification check using test malicious packages
* feat: add summarized package manager availability check
* feat: add pmg setup doctor command with compact output
* feat: add PATH shim verification to doctor command
* fix: improve doctor command UX and alias detection
- Capitalize all check messages for consistent output
- Dim passing checks, color warn/fail for visual clarity
- Silence empty Cobra error output on doctor failure
- Remove redundant pmg binary check (self-evident)
- Fix alias IsInstalled to skip commented-out source lines
- Improve protection failure message
* refactor: remove package manager availability check from doctor
* fix: handle os.RemoveAll error in doctor protection check
* refactor: use table layout for setup doctor, extract shared table renderer
Move renderTable, truncate, and visibleWidth helpers from cmd/sandbox
to internal/ui so both sandbox and setup doctor share them. Rewrite
setup doctor output to use the same table structure as sandbox doctor.
Fix VisibleWidth to count runes instead of bytes for correct alignment
with multi-byte UTF-8 characters.
* docs: add pmg setup doctor to README, remove manual verification step
* refactor: use constants for check names, rename and inline doctor helpers
Address PR review comments: extract check name constants, rename
CheckConfigFile to CheckFileExists and CheckDirectoryWritable to
CheckDirectoryExists for reusability, inline trivial wrappers
(CheckSandbox, CheckSecurityFeature, CheckProxyMode), and add
fix hints for all checks with correct config keys.
* refactor: inline simple doctor checks into command layer
* fix: skip protection check when aliases and shims are inactive
Protection checks now fail immediately when shell aliases and shims
are both inactive, instead of falsely passing by running through the
pmg binary directly. Also clean up summary messages to remove
redundant fix hints and truncated paths.
* feat: add macOS setup script for Jamf deployment
Adds scripts/pmg_setup_install.sh that installs/updates pmg (via
Homebrew or GitHub releases), runs pmg setup install, and optionally
enables cloud sync with credentials stored in macOS Keychain.
* feat: add --from-env flag to pmg cloud login
Allows non-interactive credential import from SAFEDEP_API_KEY and
SAFEDEP_TENANT_ID environment variables. Fails explicitly if either
is missing. Used by the setup script for Jamf deployments.
* refactor: use cloud.NewEnvCredentialResolver for --from-env
Use the dry library's env credential resolver instead of reading
env vars directly, keeping env var ownership in the shared library.
* update DRY
* update go to 1.25 back
runner.Execute was not filtering ~/.pmg/bin from the environment
passed to child processes. This caused two bugs:
1. Sandboxed commands (bubblewrap) inherited the unfiltered PATH,
so child processes resolved package manager binaries to the shim
instead of the real binary, causing "file not found" errors.
2. Direct pmg invocations (pmg npm install) would spawn subprocess
that find the shim in PATH, causing infinite recursion (shim →
pmg → shim → pmg) until the system runs out of OS threads.
The proxy flow already filtered the environment via setupEnvForProxy
and FilterPMGFromEnv. This applies the same filtering to the
non-proxy execute path.
* feat: add FilterPMGFromPath utility for PATH shim recursion prevention
* feat: add FilterPMGFromEnv to filter PATH from env slices
* feat: filter ~/.pmg/bin from PATH in proxy subprocess env
* feat: add PathExport method to Shell interface for shim PATH integration
* feat: add ShimManager for PATH shim install/remove lifecycle
* feat: wire ShimManager into setup commands with --use-aliases fallback
* refactor: add DefaultShimConfig helper to reduce setup boilerplate
* fix: resolve real binary path to prevent shim double-invocation
exec.CommandContext resolves the binary using the current process PATH,
which still contains ~/.pmg/bin. This caused pmg to launch the shim
instead of the real package manager, resulting in a second pmg instance
with its own proxy — producing duplicate error messages and wasted work.
ResolveRealBinary searches a filtered PATH (without ~/.pmg/bin) to find
the real package manager binary before execution.
* fix: resolve real binary in runner.Execute and expand path resolution tests
Ensure guard mode and proxy skip paths also resolve through
ResolveRealBinary to prevent infinite shim recursion. Add table-driven
tests covering error cases, multi-binary PATH, and PATH restoration.
* fix: handle error return values from os.Setenv and file Close calls
Address errcheck lint failures: check os.Setenv returns in
ResolveRealBinary, and check f.Close/tempFile.Close in ShimManager.
* feat: auto-migrate shell aliases to PATH shims on setup install
When running `pmg setup install`, detect existing shell aliases and
automatically remove them before installing shims. Existing users
get a seamless migration with no extra flags or commands needed.
* fix: update E2E test to verify shim installation instead of alias RC file
Replace the .pmg.rc file check with assertions that ~/.pmg/bin/ exists
and contains executable shim scripts for npm and pip.
* feat: add FilterPMGFromPath utility for PATH shim recursion prevention
* feat: add FilterPMGFromEnv to filter PATH from env slices
* feat: filter ~/.pmg/bin from PATH in proxy subprocess env
* feat: add PathExport method to Shell interface for shim PATH integration
* feat: add ShimManager for PATH shim install/remove lifecycle
* feat: wire ShimManager into setup commands with --use-aliases fallback
* refactor: add DefaultShimConfig helper to reduce setup boilerplate
* fix: resolve real binary path to prevent shim double-invocation
exec.CommandContext resolves the binary using the current process PATH,
which still contains ~/.pmg/bin. This caused pmg to launch the shim
instead of the real package manager, resulting in a second pmg instance
with its own proxy — producing duplicate error messages and wasted work.
ResolveRealBinary searches a filtered PATH (without ~/.pmg/bin) to find
the real package manager binary before execution.
* fix: resolve real binary in runner.Execute and expand path resolution tests
Ensure guard mode and proxy skip paths also resolve through
ResolveRealBinary to prevent infinite shim recursion. Add table-driven
tests covering error cases, multi-binary PATH, and PATH restoration.
* fix: handle error return values from os.Setenv and file Close calls
Address errcheck lint failures: check os.Setenv returns in
ResolveRealBinary, and check f.Close/tempFile.Close in ShimManager.
* feat: auto-migrate shell aliases to PATH shims on setup install
When running `pmg setup install`, detect existing shell aliases and
automatically remove them before installing shims. Existing users
get a seamless migration with no extra flags or commands needed.
* fix: update E2E test to verify shim installation instead of alias RC file
Replace the .pmg.rc file check with assertions that ~/.pmg/bin/ exists
and contains executable shim scripts for npm and pip.
* feat: install both aliases and shims for full coverage
Aliases win in interactive shells (including venvs), shims catch
non-interactive contexts (IDEs, CI, subprocesses). Remove --use-aliases
flag and migration logic since both are always installed together.
Update E2E to verify all shim scripts and alias RC file.
* feat: address review feedback for shim implementation
- Install both aliases and shims together for full coverage
- Move homeDir resolution into NewDefaultShimManager (internal concern)
- Add mutex to ResolveRealBinary to guard against concurrent PATH mutation
- Use filepath.SplitList for platform-correct PATH splitting
- Add ResolveRealBinary to runner.Execute and proxy flow to prevent
shim recursion in all execution paths
- Remove print side-effects from ShimManager.Remove
- Update E2E to verify all shim scripts and alias RC file
- Expand ResolveRealBinary tests with table-driven cases
* fix: restore errcheck handling and add concurrency test for ResolveRealBinary
- Restore proper defer with log.Warnf for PATH restoration in ResolveRealBinary
- Restore errcheck handling for f.Close() and tempFile.Close() in ShimManager
- Add explanatory comment for ResolveRealBinary call in proxy_flow
- Add TestResolveRealBinaryConcurrent to verify mutex guards concurrent access
* feat: skip shell integration on Windows with informative warning
On Windows, pmg setup install now writes only the config file and
prints a warning that shell aliases and PATH shims require WSL.
* fix: PMG use pre-resolved binary path (#253)
---------
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
2026-05-12 22:27:05 +05:30
Sahil BansalGitHubClaude Opus 4.6devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>Abhisek Dattadevin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat: emit cloud events for dependency cooldown and host observations (#237)
Wire cooldown blocks and proxy host observations through the cloud sync
pipeline so they appear as telemetry in Control Tower.
- Cooldown blocks emit PACKAGE_DECISION with COOLDOWN_BLOCKED action and
PmgDependencyCooldown context (publish date, cooldown days, days since
publish, days remaining)
- Proxy host observations emit HOST_OBSERVATION with PmgHostObservation
(hostname, method)
- Session summary now includes cooldown_blocked_count
- Updated buf API dependency for new proto schema
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* format file
* fix: add explicit eventlog mapping for EventTypeDependencyCooldown
Follow the existing pattern where every audit event type has an explicit
case in mapEventType and a corresponding constant in the eventlog package.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Apply suggestion from @devin-ai-integration[bot]
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Signed-off-by: Abhisek Datta <abhisek.datta@gmail.com>
---------
Signed-off-by: Abhisek Datta <abhisek.datta@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Script runners (run, start, stop, restart, test, etc.) are not
package management commands — remove them so they go through the
proxy instead of being skipped.
- Replace nested policies map with flat skip_commands map in ProxyConfig
- Make skip_commands dependent on install_only being enabled
- Move proxy configuration docs from proxy.md to proxy-mode.md
- Update config template and tests for new schema
* 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
ConfigureSandbox was only triggered by IsInstallationCommand(), missing
update commands (npm update, pnpm update, etc.) that pull new versions
and run postinstall scripts. Use MayDownloadPackages() as the sandbox
signal so all package-downloading commands are sandboxed.
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
* 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: Show cooldown report for pinned version installs
When a user installs a package with an explicit version (e.g.
npm install foo@1.2.3) and that version falls within the dependency
cooldown window, the cooldown block is now recorded and shown in the
report. Previously, the report only appeared when ALL versions of a
package were in cooldown (remaining == 0), causing pinned version
installs to fail with a confusing "version not found" error from the
package manager instead of a clear cooldown explanation.
Introduces InterceptorContext to carry per-execution data (pinned
versions) from the CLI command through the interceptor layer, keeping
it separate from long-lived dependencies like the analyzer and cache.
* fix: Normalize PyPI pinned version keys for cooldown lookup
CLI-provided package names (e.g. Flask_Cors) don't match the
URL-parsed form (flask-cors). Normalize keys once at construction
time so cooldown lookups match correctly.
* fix: Handle dots in PyPI package name normalization per PEP 503
denormalizePyPIPackageName already documented [-_.] replacement but
only handled underscores. Now also replaces dots with hyphens so
names like zope.interface match the URL-parsed form zope-interface.
* refactor: Extract shared cooldown stats recording into helper
Deduplicate identical stats-recording blocks from npm_cooldown.go
and pypi_cooldown.go into recordCooldownStats in cooldown.go.
* fix: Distinguish explicit version pins from auto-resolved versions
PyPI parsers resolve all packages to concrete versions (even without
a user-specified constraint), so HasVersion() was always true. Add
IsExplicitVersion to PackageInstallTarget, set it only when the user
provided an explicit constraint. Use it in proxy_flow.go to avoid
false pinned-version cooldown reports.
* refactor: Extract shared cooldown helpers to package-level functions
* feat: Add PyPI cooldown handler with PEP 691 file parsing
* feat: Add PyPI cooldown file stripping logic
* feat: Implement PyPI cooldown HandleMetadataRequest with PEP 691 filtering
* feat: Wire PyPI cooldown into pypi_registry interceptor
* update headers for no cache
* fix: Strip conditional GET headers to prevent 304 bypass in cooldown handlers
pip and npm clients cache Simple API / registry responses with ETags. On
subsequent requests they send If-None-Match, which causes the server to
return 304 Not Modified with no body. The cooldown response modifier
received an empty body, failed to parse it, and failed-open — letting
the client use its stale cached (unfiltered) response.
Fix: delete If-None-Match and If-Modified-Since from the request before
forwarding, forcing a full 200 response so the modifier always has a
body to filter.
Also removes the Content-Type guard from the PyPI modifier (the empty
Content-Type on 304 responses was a symptom of the same root cause) and
replaces Cache-Control: no-cache with the more targeted header deletion.
* docs: Add PyPI cooldown limitation for pip < 22.3 to dependency-cooldown docs
* feat: Add proxy_install_only config to restrict proxy to download commands
Introduces proxy_install_only (default: false) which, when enabled,
skips the proxy for package manager commands that do not download
packages (e.g. npm ls, pip list), avoiding unnecessary MITM overhead.
- Add ProxyInstallOnly to Config and config template
- Add IsKnownDownloadCommand / MayDownloadPackages to ParsedCommand
- Add DownloadCommands to npm and pypi PM configs covering update,
ci, audit, dlx, exec, x, download, run and equivalents per PM
- Extract shared runner.Execute used by both proxy flow and guard
- Proxy flow short-circuits to runner.Execute for non-download commands
when proxy_install_only=true
* refactor: Inject CommandExecutor into guard to fix dependency direction
guard depended on internal/runner, which inverted the intended layer
hierarchy. Now guard defines a CommandExecutor function type and accepts
it as a constructor argument. internal/flows (the composition root)
creates the executor closure wrapping runner.Execute and injects it,
keeping guard free of internal/ dependencies.
* refactor: Invert proxy_install_only logic to use known non-download commands
Replace the DownloadCommands allowlist (opt-in, fail-open) with a
NonDownloadCommands denylist (opt-out, fail-safe). The proxy now runs
for all commands except those explicitly known to not download packages.
Unknown or future package manager subcommands default to running with
the proxy.
Includes script runners (run, start, test, stop, restart) that can spin
up local servers — setting proxy env vars on these breaks them without
providing any security benefit. Also covers removal commands and local
operations that never contact the registry.
* fix: Support PMG_* env vars regardless of config file state
AutomaticEnv only resolves env vars for keys Viper already knows about
via AllKeys(). When a key is absent from the config file (commented out,
new key added after last setup, or no config file at all), Viper had no
knowledge of it and silently skipped the env var.
Fix by registering all Config struct fields as Viper defaults via
reflection (using mapstructure tags) before reading the config file.
This ensures PMG_* env vars work in all cases.
Precedence: cobra flags > env vars > config file > defaults.
SetDefault is used (not Set) so env vars and config file can still
override the Go defaults freely.
Tests added covering all precedence levels including the key-absent-
from-config-file case that was the original bug report.
* fix: Only check first non-flag arg against NonDownloadCommands
Scanning all args caused false proxy bypasses when package names or
script arguments matched a NonDownloadCommands entry. For example:
- npm exec test → "test" matched, proxy incorrectly skipped
- npm update config → "config" matched, proxy skipped
- npm publish --tag version → "version" matched, proxy skipped
Fix by checking only the first non-flag argument (the subcommand).
If it is not in NonDownloadCommands we break immediately, so trailing
args never influence the classification. Applied to all four parsers:
npm, pip/pip3, uv, and poetry.
Regression tests added for the false positive cases.
* refactor: Replace reflection-based Viper defaults with embedded template
Load the embedded config template as the Viper base so all keys are
registered upfront, enabling PMG_* env vars to work regardless of
whether a key exists in the user's config file.
* fix: Restore trusted_packages template entry and revert DefaultConfig change
* docs: Document environment variable overrides for config keys
* update npm test cmd
* refactor: extract shared non-download command detection helper
Replaces duplicated first-non-flag-arg detection loops in npm.go and
pypi.go (pip + poetry parsers) with a shared isFirstNonFlagArgInList
helper in packagemanager.go.
https://claude.ai/code/session_01AHaKF3vc2Haj9tK3jgUBAs
---------
Co-authored-by: Claude <noreply@anthropic.com>
* fix: only strip own package manager name in ParseCommand args
ParseCommand was stripping the first arg if it matched any package
manager name (npm, pnpm, bun, yarn). This caused yarn's parser to
incorrectly strip "npm" from "yarn npm login", since "npm" is a
valid yarn subcommand, not a package manager prefix.
Fixes#204
* use require in test
* 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>
When users have HTTP_PROXY/HTTPS_PROXY set in their shell (e.g. corporate
proxy), PMG's upstream transport routes all traffic through that external
proxy — including requests to localhost/127.0.0.1. The external proxy
cannot reach the user's loopback, causing EFAULT/ConnectionRefused errors.
This adds loopback bypass in two places:
- Proxy upstream transport skips external proxy for localhost/127.0.0.1/::1
- Child process env gets NO_PROXY so proxy-aware libs (axios) skip PMG's
proxy for loopback addresses
Fixes#193
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* update README.md
* ci: Remove paths-ignore filters from all workflows
Removes docs/ and *.md path exclusions so required checks always run,
preventing PRs from being blocked when only documentation files change.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* docs: Add config merging design spec for #114
Defines the merge-during-setup-install approach for keeping user
configs up to date with new template keys while preserving all
existing values, comments, and formatting.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: Add implementation plan for config merging
TDD-based plan with 6 tasks: dependency setup, failing tests,
core merge implementation, integration test, WriteTemplateConfig
integration, and full verification.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: Merge template config into existing user config during setup install
Instead of skipping when a config file exists, WriteTemplateConfig() now
merges missing keys from the embedded template into the user's config
using YAML AST manipulation. Preserves all user values, comments, and
formatting. Only adds keys present in the template but absent in the
user's config.
Closes#114
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: Graceful error handling for config loading and setup commands
Replace panics in loadViperConfig with error returns so the app falls
back to defaults instead of crashing on malformed config files. Add
SilenceUsage to setup install/remove commands so runtime errors don't
dump the full usage text.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* add test cmd in readme
* update copy text
* refactor: Address review feedback on config merging
- Rename existing/template to dest/source for generic util naming
- Remove unnecessary code comments (Rule N references, obvious comments)
- Add AGENTS.md with dev guide and code style rules, symlink CLAUDE.md
- Add BenchmarkMergeYAML (~46μs/op on M4 Pro)
- Remove stale design spec
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update `MergeYAML` to use from dry/utils
* update AGENTS.md
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
The npm postinstall script used `unzip` to extract .zip archives, but
`unzip` is not available by default on Windows, causing installation to
fail with a `spawn UNKNOWN` error. Use PowerShell's `Expand-Archive`
on Windows instead, which is available since PowerShell 5.0 (Windows 10+).
Fixes#187
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
The spinner goroutine was writing carriage-return + status text to
os.Stdout every 100ms. In the non-interactive TTY path, the child
process also writes directly to os.Stdout, causing both writers to
race on the same file descriptor. The \r emitted by the spinner
resets the cursor to column 0 mid-line, corrupting and truncating
the child process output.
Fix by writing all spinner/status output to os.Stderr, which is the
standard Unix convention for diagnostic and status messages. This is
also consistent with how progress.go and ShowWarning already behave.
https://claude.ai/code/session_012jMiRSS4Jx9Bs7a2F4S6KN
Co-authored-by: Claude <noreply@anthropic.com>
* add support to merge system CA with PMG CA
* Keep CA cert immutable; merge system bundle only when writing proxy CA file
* Update proxy/certmanager/generator.go
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
* Update internal/flows/proxy_flow.go
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
* update config field name
* Use integer-only guard when sizing merged CA bundle
* Use int64-only guard when sizing merged CA bundle
* add tests for firstReadablePath
* Update proxy/certmanager/generator.go
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
* fix linter
* refactor system CA merge API
* add max limit to 2MB for certificates
* update max limit to 2MB for certificate merging
* remove python specific env var for CAs
---------
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
* provide package blocked feedback in proxy mode
* update test case & clear status on block
* refactor reporting
* clearStatus on `continueExecution`
* set spinnerChan to nil
* add sync for spinner
* fix proxy mode failing for GH private packages
* skip analysis for private packages for proxy mode
* introduce npmRegistryConfig and support for handling multiple parsers in future
* refactor name and unexport npm config functions
* rm unused function
* rename & unexport npmRegistryURLParser
* add e2e for malicious pkg blocked using proxy mode
* introduce enforce_always sandbox config & hooks for flows
* fix sandbox failing for unsupported commands
* add hooks for pypi package managers
* add tests for sandbox hook
* introduce enforce_always flag for ease use & CI
* make comments descriptive
* remove hooks & update config to add API to configure sandbox
* add comments
* rm unused function
* 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>
* 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
* fix: resolve dependencies for manifest file scans
* fix: resolve dependencies for manifest file scans
* fix: resolve dependencies for manifest file scans - 2
* revert back to traditional for loop
* fix(manifest-scan): resolve deps only for requirements.txt