Skill: davida-ps/clawsec-suite (version 0.1.9)

--- name: clawsec-suite version: 0.1.9 description: ClawSec suite manager with embedded advisory-feed monitoring, cryptographic signature verification, approval-gated malicious-skill response, and guided setup for additional security skills. homepage: https://clawsec.prompt.security clawdis: emoji: "📦" requires: bins: [node, npx, openclaw, curl, jq, shasum, openssl, unzip] --- # ClawSec Suite ## Operational Notes - Required runtime: `node`, `npx`, `openclaw`, `curl`, `jq`, `shasum`, `openssl`, `unzip` - Side effects: setup scripts install an advisory hook under `~/.openclaw/hooks`, optionally create an unattended `openclaw cron` job, and use `npx clawhub@latest install` for guarded installs - Network behavior: fetches signed advisory feed artifacts and remote catalog metadata unless you pin local paths - Trust model: the suite can recommend removal or block risky installs, but removal/install overrides stay approval-gated This means `clawsec-suite` can: - monitor the ClawSec advisory feed, - track which advisories are new since last check, - cross-reference advisories against locally installed skills, - recommend removal for malicious-skill advisories and require explicit user approval first, - and still act as the setup/management entrypoint for other ClawSec protections. ## Included vs Optional Protections ### Built into clawsec-suite - Embedded consolidated advisory feed seed file: `advisories/feed.json` - Portable heartbeat workflow in `HEARTBEAT.md` - Advisory polling + state tracking + affected-skill checks - OpenClaw advisory guardian hook package: [REDACTED_SECRET] - Setup scripts for hook and optional cron scheduling: `scripts/` - Guarded installer: `scripts/guarded_skill_install.mjs` - Dynamic catalog discovery for installable skills: `scripts/discover_skill_catalog.mjs` ### Installed separately (dynamic catalog) `clawsec-suite` does not hard-code add-on skill names in this document. Discover the current catalog from the authoritative index (`https://clawsec.prompt.security/skills/index.json`) at runtime: ```bash SUITE_DIR="${INSTALL_ROOT:-$HOME/.openclaw/skills}/clawsec-suite" node "$SUITE_DIR/scripts/discover_skill_catalog.mjs" ``` Fallback behavior: - If the remote catalog index is reachable and valid, the suite uses it. - If the remote index is unavailable or malformed, the script falls back to suite-local catalog metadata in `skill.json`. ## Installation ### Cross-shell path note - In `bash`/`zsh`, keep path variables expandable (for example, `INSTALL_ROOT="$HOME/.openclaw/skills"`). - Do not single-quote home-variable paths (avoid `'$HOME/.openclaw/skills'`). - In PowerShell, set an explicit path: - `$env:INSTALL_ROOT = Join-Path $HOME ".openclaw\\skills"` - If a path is passed with unresolved tokens (like `\$HOME/...`), suite scripts now fail fast with a clear error. ### Option A: Via clawhub (recommended) ```bash npx clawhub@latest install clawsec-suite ``` ### Option B: Manual download with signature + checksum verification ```bash set -euo pipefail VERSION="${SKILL_VERSION:?Set SKILL_VERSION (e.g. 0.0.8)}" INSTALL_ROOT="${INSTALL_ROOT:-$HOME/.openclaw/skills}" DEST="$INSTALL_ROOT/clawsec-suite" BASE="https://github.com/prompt-security/clawsec/releases/download/clawsec-suite-v${VERSION}" TEMP_DIR="$(mktemp -d)" trap 'rm -rf "$TEMP_DIR"' EXIT # Pinned release-signing public key (verify fingerprint out-of-band on first use) # Fingerprint (SHA-256 of SPKI DER): 711424e4535f84093fefb024cd1ca4ec87439e53907b305b79a631d5befba9c8 RELEASE_PUBKEY_SHA256=[REDACTED_SECRET] cat > "$TEMP_DIR/release-signing-public.pem" <<'PEM' -----BEGIN PUBLIC KEY----- MCowBQYDK2VwAyEAS7nijfMcUoOBCj4yOXJX+GYGv2pFl2Yaha1P4v5Cm6A= -----END PUBLIC KEY----- PEM ACTUAL_KEY_SHA256="$(openssl pkey -pubin -in "$TEMP_DIR/release-signing-public.pem" -outform DER | shasum -a 256 | awk '{print $1}')" if [ "$ACTUAL_KEY_SHA256" != "$RELEASE_PUBKEY_SHA256" ]; then echo "ERROR: Release public key fingerprint mismatch" >&2 exit 1 fi ZIP_NAME="clawsec-suite-v${VERSION}.zip" # 1) Download release archive + signed checksums manifest + signing public key curl -fsSL "$BASE/$ZIP_NAME" -o "$TEMP_DIR/$ZIP_NAME" curl -fsSL "$BASE/checksums.json" -o "$TEMP_DIR/checksums.json" curl -fsSL "$BASE/checksums.sig" -o "$TEMP_DIR/checksums.sig" # 2) Verify checksums manifest signature before trusting any hashes openssl base64 -d -A -in "$TEMP_DIR/checksums.sig" -out "$TEMP_DIR/checksums.sig.bin" if ! openssl pkeyutl -verify \ -pubin \ -inkey "$TEMP_DIR/release-signing-public.pem" \ -sigfile "$TEMP_DIR/checksums.sig.bin" \ -rawin \ -in "$TEMP_DIR/checksums.json" >/dev/null 2>&1; then echo "ERROR: checksums.json signature verification failed" >&2 exit 1 fi EXPECTED_ZIP_SHA="$(jq -r '.archive.sha256 // empty' "$TEMP_DIR/checksums.json")" if [ -z "$EXPECTED_ZIP_SHA" ]; then echo "ERROR: checksums.json missing archive.sha256" >&2 exit 1 fi if command -v shasum >/dev/null 2>&1; then ACTUAL_ZIP_SHA="$(shasum -a 256 "$TEMP_DIR/$ZIP_NAME" | awk '{print $1}')" else ACTUAL_ZIP_SHA="$(sha256sum "$TEMP_DIR/$ZIP_NAME" | awk '{print $1}')" fi if [ "$EXPECTED_ZIP_SHA" != "$ACTUAL_ZIP_SHA" ]; then echo "ERROR: Archive checksum mismatch for $ZIP_NAME" >&2 exit 1 fi echo "Checksums manifest signature and archive hash verified." # 3) Install verified archive mkdir -p "$INSTALL_ROOT" rm -rf "$DEST" unzip -q "$TEMP_DIR/$ZIP_NAME" -d "$INSTALL_ROOT" chmod 600 "$DEST/skill.json" find "$DEST" -type f ! -name "skill.json" -exec chmod 644 {} \; echo "Installed clawsec-suite v${VERSION} to: $DEST" echo "Next step (OpenClaw): node \"\$DEST/scripts/setup_advisory_hook.mjs\"" ``` ## OpenClaw Automation (Hook + Optional Cron) After installing the suite, enable the advisory guardian hook: ```bash SUITE_DIR="${INSTALL_ROOT:-$HOME/.openclaw/skills}/clawsec-suite" node "$SUITE_DIR/scripts/setup_advisory_hook.mjs" ``` The setup script prints a preflight review before it installs and enables the persistent hook. Optional: create/update a periodic cron nudge (default every `6h`) that triggers a main-session advisory scan: ```bash SUITE_DIR="${INSTALL_ROOT:-$HOME/.openclaw/skills}/clawsec-suite" node "$SUITE_DIR/scripts/setup_advisory_cron.mjs" ``` The cron setup script prints a preflight review before it creates or updates the unattended job. What this adds: - scan on `agent:bootstrap` and `/new` (`command:new`), - compare advisory `affected` entries against installed skills, - consider advisories with `application: "openclaw"` (and legacy entries without `application` for backward compatibility), - notify when new matches appear, - and ask for explicit user approval before any removal flow. Restart the OpenClaw gateway after enabling the hook. Then run `/new` once to force an immediate scan in the next session context. ## Guarded Skill Install Flow (Double Confirmation) When the user asks to install a skill, treat that as the first request and run a guarded install check: ```bash SUITE_DIR="${INSTALL_ROOT:-$HOME/.openclaw/skills}/clawsec-suite" node "$SUITE_DIR/scripts/guarded_skill_install.mjs" --skill helper-plus --version 1.0.1 ``` Behavior: - If no advisory match is found, install proceeds. - If `--version` is omitted, matching is conservative: any advisory that references the skill name is treated as a match. - If advisory match is found, the script prints advisory context and exits with code `42`. - Then require an explicit second confirmation from the user and rerun with `--confirm-advisory`: ```bash node "$SUITE_DIR/scripts/guarded_skill_install.mjs" --skill helper-plus --version 1.0.1 --confirm-advisory ``` This enforces: 1. First confirmation: user asked to install. 2. Second confirmation: user explicitly approves install after seeing advisory details. ## Embedded Advisory Feed Behavior The embedded feed logic uses these defaults: - Remote consolidated feed URL: `https://clawsec.prompt.security/advisories/feed.json` - Feed contents: NVD CVEs, approved community advisories, and provisional GHSA-without-CVE advisories. - Remote feed signature URL: `${CLAWSEC_FEED_URL}.sig` (override with `CLAWSEC_FEED_SIG_URL`) - Remote checksums manifest URL: sibling `checksums.json` (override with `CLAWSEC_FEED_CHECKSUMS_URL`) - Local seed fallback: `~/.openclaw/skills/clawsec-suite/advisories/feed.json` - Local feed signature: `${CLAWSEC_LOCAL_FEED}.sig` (override with `CLAWSEC_LOCAL_FEED_SIG`) - Local checksums manifest: `~/.openclaw/skills/clawsec-suite/advisories/checksums.json` - Pinned feed signing key: `~/.openclaw/skills/clawsec-suite/advisories/feed-signing-public.pem` (override with `CLAWSEC_FEED_PUBLIC_KEY`) - State file: `~/.openclaw/clawsec-suite-feed-state.json` - Hook rate-limit env (OpenClaw hook): `CLAWSEC_HOOK_INTERVAL_SECONDS` (default `300`) **Fail-closed verification:** Feed signatures are required by default. Checksum manifests are verified when companion checksum artifacts are available. Set `CLAWSEC_ALLOW_UNSIGNED_FEED=1` only as a temporary migration bypass when adopting this version before signed feed artifacts are available upstream. ### Quick feed check ```bash FEED_URL="${CLAWSEC_FEED_URL:-https://clawsec.prompt.security/advisories/feed.json}" STATE_FILE="${CLAWSEC_SUITE_STATE_FILE:-$HOME/.openclaw/clawsec-suite-feed-state.json}" TMP="$(mktemp -d)" trap 'rm -rf "$TMP"' EXIT if ! curl -fsSLo "$TMP/feed.json" "$FEED_URL"; then echo "ERROR: Failed to fetch advisory feed" exit 1 fi if ! jq -e '.version and (.advisories | type == "array")' "$TMP/feed.json" >/dev/null; then echo "ERROR: Invalid advisory feed format" exit 1 fi mkdir -p "$(dirname "$STATE_FILE")" if [ ! -f "$STATE_FILE" ]; then echo '{"schema_version":"1.0","known_advisories":[],"last_feed_check":null,"last_feed_updated":null}' > "$STATE_FILE" chmod 600 "$STATE_FILE" fi NEW_IDS_FILE="$TMP/new_ids.txt" jq -r --argfile state "$STATE_FILE" '($state.known_advisories // []) as $known | [.advisories[]?.id | select(. != null and ($known | index(.) | not))] | .[]?' "$TMP/feed.json" > "$NEW_IDS_FILE" if [ -s "$NEW_IDS_FILE" ]; then echo "New advisories detected:" while IFS= read -r id; do [ -z "$id" ] && continue jq -r --arg id "$id" '.advisories[] | select(.id == $id) | "- [\(.severity | ascii_upcase)] \(.id): \(.title)"' "$TMP/feed.json" jq -r --arg id "$id" '.advisories[] | select(.id == $id) | " Exploitability: \(.exploitability_score // "unknown" | ascii_upcase)"' "$TMP/feed.json" done < "$NEW_IDS_FILE" else echo "FEED_OK - no new advisories" fi ``` ## Exploitability Context Advisories in the feed can include `exploitability_score` and `exploitability_rationale` fields to help agents prioritize real-world threats: - **Exploitability scores**: `high`, `medium`, `low`, or `unknown` - **Context-aware assessment**: Considers attack vector, authentication requirements, and AI agent deployment patterns - **Exploit availability**: Detects public exploits and weaponization status When processing advisories, prioritize by exploitability in addition to severity. A HIGH severity + HIGH exploitability CVE is more urgent than a CRITICAL severity + LOW exploitability CVE. For detailed methodology, see the [exploitability scoring documentation](../../wiki/exploitability-scoring.md). ## Heartbeat Integration Use the suite heartbeat script as the single periodic security check entrypoint: - `skills/clawsec-suite/HEARTBEAT.md` It handles: - suite update checks, - feed polling, - new-advisory detection, - affected-skill cross-referencing, - approval-gated response guidance for malicious/removal advisories, - and persistent state updates. ## Approval-Gated Response Contract If an advisory indicates a malicious or removal-recommended skill and that skill is installed: 1. Notify the user immediately with advisory details and severity. 2. Recommend removing or disabling the affected skill. 3. Treat the original install request as first intent only. 4. Ask for explicit second confirmation before deletion/disable action (or before proceeding with risky install). 5. Only proceed after that second confirmation. The suite hook and heartbeat guidance are intentionally non-destructive by default. ## Advisory Suppression / Allowlist The advisory guardian pipeline supports opt-in suppression for advisories that have been reviewed and accepted by your security team. This is useful for first-party tooling or advisories that do not apply to your deployment. ### Activation Advisory suppression requires a single gate: the configuration file must contain `"enabledFor"` with `"advisory"` in the array. No CLI flag is needed -- the sentinel in the config file IS the opt-in gate. If the `enabledFor` array is missing, empty, or does not include `"advisory"`, all advisories are reported normally. ### Config File Resolution (4-tier) The advisory guardian resolves the suppression config using the same priority order as the audit pipeline: 1. Explicit `--config <path>` argument 2. `OPENCLAW_AUDIT_CONFIG` environment variable 3. `~/.openclaw/security-audit.json` 4. `.clawsec/allowlist.json` ### Config Format ```json { "enabledFor": ["advisory"], "suppressions": [ { "checkId": "CVE-2026-25593", "skill": "clawsec-suite", "reason": "First-party security tooling — reviewed by security team", "suppressedAt": "2026-02-15" }, { "checkId": "CLAW-2026-0001", "skill": "example-skill", "reason": "Advisory does not apply to our deployment configuration", "suppressedAt": "2026-02-16" } ] } ``` ### Sentinel Semantics - `"enabledFor": ["advisory"]` -- only advisory suppression active - `"enabledFor": ["audit"]` -- only audit suppression active (no effect on advisory pipeline) - `"enabledFor": ["audit", "advisory"]` -- both pipelines honor suppressions - Missing or empty `enabledFor` -- no suppression active (safe default) ### Matching Rules - **checkId:** exact match against the advisory ID (e.g., `CVE-2026-25593` or `CLAW-2026-0001`) - **skill:** case-insensitive match against the affected skill name from the advisory - Both fields must match for an advisory to be suppressed ### Required Fields per Suppression Entry | Field | Description | Example | |-------|-------------|---------| | `checkId` | Advisory ID to suppress | `CVE-2026-25593` | | `skill` | Affected skill name | `clawsec-suite` | | `reason` | Justification for audit trail (required) | `First-party tooling, reviewed by security team` | | `suppressedAt` | ISO 8601 date (YYYY-MM-DD) | `2026-02-15` | ### Shared Config with Audit Pipeline The advisory and audit pipelines share the same config file. Use the `enabledFor` array to control which pipelines honor the suppression list: ```json { "enabledFor": ["audit", "advisory"], "suppressions": [ { "checkId": "skills.code_safety", "skill": "clawsec-suite", "reason": "First-party tooling — audit finding accepted", "suppressedAt": "2026-02-15" }, { "checkId": "CVE-2026-25593", "skill": "clawsec-suite", "reason": "First-party tooling — advisory reviewed", "suppressedAt": "2026-02-15" } ] } ``` Audit entries (with check identifiers like `skills.code_safety`) are only matched by the audit pipeline. Advisory entries (with advisory IDs like `CVE-2026-25593` or `CLAW-2026-0001`) are only matched by the advisory pipeline. Each pipeline filters for its own relevant entries. ## Optional Skill Installation Discover currently available installable skills dynamically, then install the ones you want: ```bash SUITE_DIR="${INSTALL_ROOT:-$HOME/.openclaw/skills}/clawsec-suite" node "$SUITE_DIR/scripts/discover_skill_catalog.mjs" # then install any discovered skill by name npx clawhub@latest install <skill-name> ``` Machine-readable output is also available for automation: ```bash node "$SUITE_DIR/scripts/discover_skill_catalog.mjs" --json ``` ## Security Notes - Always verify `checksums.json` signature before trusting its file URLs/hashes, then verify each file checksum. - Verify advisory feed detached signatures; do not enable `CLAWSEC_ALLOW_UNSIGNED_FEED` outside temporary migration windows. - Keep advisory polling rate-limited (at least 5 minutes between checks). - Treat `critical` and `high` advisories affecting installed skills as immediate action items. - If you migrate off standalone `clawsec-feed`, keep one canonical state file to avoid duplicate notifications. - Pin and verify public key fingerprints out-of-band before first use.

path: CHANGELOG.md
content: # Changelog

All notable changes to the ClawSec Suite will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.1.9] - 2026-05-24

### Changed

- Documented the remote advisory feed as a consolidated feed containing NVD CVEs, approved community advisories, and provisional GHSA-without-CVE records.
- Added advisory guardian type coverage for GHSA lifecycle metadata used by the consolidated feed.

## [0.1.8] - 2026-05-16

### Fixed

- Added the advisory scope and suppression runtime helpers to `skill.json` SBOM metadata so release archives include every file required by the advisory guardian hook.

## [0.1.7] - 2026-04-16

### Changed

- Added `.clawhubignore` coverage for `test/` so publish payloads stay focused on runtime assets.
- Refactored setup/install scripts to use aliased child-process calls while preserving behavior.
- Split local file reads into `scripts/local_file_io.mjs` and `hooks/clawsec-advisory-guardian/lib/local_file_io.mjs` so network-facing files keep I/O concerns isolated.

### Security

- Removed static moderation false positives related to mixed file-read/network and child-process token patterns in publish-scoped runtime files.

## [0.1.6] - 2026-04-14

### Added

- Runtime and operator-review metadata covering hook installation, optional cron persistence, guarded install flows, and feed URL overrides.
- Preflight disclosure in `scripts/setup_advisory_hook.mjs` and `scripts/setup_advisory_cron.mjs`.
- Regression coverage for setup disclosure behavior in `test/setup_disclosure.test.mjs`.

### Changed

- Declared `node`, `npx`, `openclaw`, and `unzip` in the suite runtime metadata to match the documented setup and install flows.
- Updated catalog messaging for `openclaw-audit-watchdog` to reflect DM delivery with optional email instead of implying email-only reporting.
- Marked local advisory signature/checksum SBOM entries as optional until those companion artifacts are bundled in the repository.
- Removed legacy pre-OpenClaw naming from the suite catalog compatibility metadata.

### Security

- Hook and cron setup now announce their persistence and approval boundaries before enabling host-side automation.
- Clarified that the suite can recommend removal or block risky installs, but destructive actions remain approval-gated.

## [0.1.5] - 2026-04-08

### Fixed

- Fixed heartbeat update detection to rely on GitHub release metadata for latest-version resolution, addressing false update status results reported in [#168](https://github.com/prompt-security/clawsec/issues/168).
- Hardened fallback behavior when release API auth/config is unavailable so version checks still resolve the correct latest release.

## [0.1.4] - 2026-02-28

### Added

- Advisory output snippets now include exploitability context in suite quick-check and heartbeat examples.

### Changed

- Clarified exploitability guidance to match runtime score values (`high|medium|low|unknown`).
- Prioritization guidance now emphasizes high-exploitability advisories for immediate handling.

### Fixed

- Kept exploitability enrichment in advisory workflows non-fatal per item so a single analysis failure does not abort feed updates.

## [0.1.3]

### Added

- Contributor credit: portability and path-hardening improvements in this release were contributed by [@aldodelgado](https://github.com/aldodelgado) in PR #62.
- Cross-shell path resolution support for home-directory tokens in suite path configuration (`~`, `$HOME`, `${HOME}`, `%USERPROFILE%`, `$env:HOME`).
- Dedicated path-resolution regression coverage (`test/path_resolution.test.mjs`) including fallback behavior for invalid explicit path values.
- Additional advisory/installer tests validating home-token expansion and escaped-token rejection.

### Changed

- Advisory guardian hook now resolves configured path environment variables through a shared portability helper.
- Guarded install flow now resolves feed/signature/checksum/public-key path overrides through the same shared path helper for consistent behavior across shells/OSes.
- Advisory matching now explicitly scopes to `application: "openclaw"` when present; legacy advisories without `application` remain eligible for backward compatibility.

### Fixed

- Prevented advisory-check bypass when a single explicit path env var is malformed: invalid explicit values now fall back to safe defaults instead of aborting the entire hook run.

### Security

- Escaped/unexpanded home-token inputs in path config are explicitly rejected while preserving secure defaults.

## [0.1.2]

### Added

- Advisory suppression module (`hooks/clawsec-advisory-guardian/lib/suppression.mjs`).
- `loadAdvisorySuppression()` -- loads suppression config with `enabledFor: ["advisory"]` sentinel gate.
- `isAdvisorySuppressed()` -- matches `advisory.id === rule.checkId` + case-insensitive skill name.
- Advisory guardian handler integration: partitions matches into active/suppressed after `findMatches()`.
- Suppressed matches tracked in state file (prevents re-evaluation) but not alerted.
- Soft notification message for suppressed matches count.
- Advisory suppression tests (13 tests in `advisory_suppression.test.mjs`).
- Documentation in SKILL.md for advisory suppression/allowlist mechanism.

### Changed

- Advisory guardian handler (`handler.ts`) now loads suppression config and filters matches before alerting.

### Security

- Advisory suppression gated by config file sentinel (`enabledFor: ["advisory"]`) -- no CLI flag needed but config must explicitly opt in.
- Suppressed matches are still tracked in state to maintain audit trail.

## [0.1.1] - 2026-02-16

### Added
- Added `scripts/discover_skill_catalog.mjs` to dynamically discover installable skills from `https://clawsec.prompt.security/skills/index.json`.
- Added `test/skill_catalog_discovery.test.mjs` to validate remote-catalog loading and fallback behavior.
- Added CI signing-key drift guard script: `scripts/ci/verify_signing_key_consistency.sh`.

### Changed
- Updated `SKILL.md` to use dynamic catalog discovery commands instead of hard-coded optional-skill names.
- Updated advisory feed defaults to signed-host URL (`https://clawsec.prompt.security/advisories/feed.json`).
- Improved checksum manifest key compatibility in feed verification logic (supports basename and `advisories/*` key formats).
- Kept `openclaw-audit-watchdog` as a standalone skill (not embedded in `clawsec-suite`).

### Security
- **Signing key drift control**: CI now enforces that all public key references (inline SKILL.md PEM, canonical `.pem` files, workflow-generated keys) resolve to the same fingerprint. Prevents stale, fabricated, or rotated-but-not-propagated key material from reaching releases.
  - Enforced in: `.github/workflows/skill-release.yml`, `.github/workflows/deploy-pages.yml`
  - Guard script: `scripts/ci/verify_signing_key_consistency.sh`

### Fixed
- **Fixed fabricated signing key in SKILL.md**: The manual installation script contained a hallucinated Ed25519 public key and fingerprint (`35866e1b...`) that never corresponded to the actual release signing key. Replaced with the real public key derived from the GitHub-secret-held private key. The bogus key was introduced in v0.0.10 (`Integration/signing work #20`) and went undetected because no consistency check existed at the time.
- Corrected `checksums.sig` naming in release verification documentation.

## [0.0.10] - 2026-02-11

### Security

#### Transport Security Hardening
- **TLS Version Enforcement**: Eliminated support for TLS 1.0 and TLS 1.1, enforcing minimum TLS 1.2 for all HTTPS connections
- **Certificate Validation**: Enabled strict certificate validation (`rejectUnauthorized: true`) to prevent MITM attacks
- **Domain Allowlist**: Restricted advisory feed connections to approved domains only:
  - `clawsec.prompt.security` (official ClawSec feed host)
  - `prompt.security` (parent domain)
  - `raw.githubusercontent.com` (GitHub raw content)
  - `github.com` (GitHub releases)
- **Strong Cipher Suites**: Configured modern cipher suites (AES-GCM, ChaCha20-Poly1305) for secure connections

#### Signature Verification & Checksum Validation
- **Fixed unverified file publication**: Refactored `deploy-pages.yml` workflow to download release assets to temporary directory before signature verification, ensuring unverified files never reach public directory
- **Fixed schema mismatch**: Updated `deploy-pages.yml` to generate `checksums.json` with proper `schema_version` and `algorithm` fields that match parser expectations
- **Fixed missing checksums abort**: Updated `loadRemoteFeed` to gracefully skip checksum verification when `checksums.json` is missing (e.g., GitHub raw content), while still enforcing fail-closed signature verification
- **Fixed parser strictness**: Enhanced `parseChecksumsManifest` to accept legacy manifest formats through a fallback chain:
  1. `schema_version` (new standard)
  2. `version` (skill-release.yml format)
  3. `generated_at` (old deploy-pages.yml format)
  4. `"1"` (ultimate fallback)

### Changed
- Advisory feed loader now uses `secureFetch` wrapper with TLS 1.2+ enforcement and domain validation
- Checksum verification is now graceful: feeds load successfully from sources without checksums (e.g., GitHub raw) while maintaining fail-closed signature verification
- Workflow release mirroring flow changed from `download → verify → skip` to `download to temp → verify → mirror` (fail = delete temp)

### Fixed
- Unverified skill releases no longer published to public directory on signature verification failure
- Schema mismatch between generated and expected checksums manifest fields
- Feed loading failures when checksums.json missing from upstream sources
- Parser rejection of valid legacy manifest formats

### Security Impact
- **Fail-closed security maintained**: All feed signatures still verified; invalid signatures reject feed loading
- **No backward compatibility break**: Legacy manifests continue working through fallback chain
- **Enhanced transport security**: Connections protected against downgrade attacks and MITM
- **Defense in depth**: Multiple layers of verification (domain, TLS, certificate, signature, checksum)

---

## Release Notes Template

When creating a new release, copy this template to the GitHub release notes:

```markdown
## Security Improvements

### Transport Security
✅ TLS 1.2+ enforcement (eliminated TLS 1.0, 1.1)
✅ Strict certificate validation
✅ Domain allowlist (prompt.security, github.com only)
✅ Modern cipher suites (AES-GCM, ChaCha20-Poly1305)

### Signature & Checksum Verification
✅ Unverified files never published (temp directory workflow)
✅ Proper schema fields in generated checksums.json
✅ Graceful fallback when checksums missing (GitHub raw)
✅ Legacy manifest format support (backward compatible)

### Testing
All verification tests passed:
- ✅ Unit tests: 14/14 passed
- ✅ Parser lenience: 3/3 legacy formats accepted
- ✅ Remote loading: Gracefully handles missing checksums
- ✅ Workflow security: Temp directory prevents unverified publication
```


path: HEARTBEAT.md
content: # ClawSec Suite — Heartbeat Check

Run this periodically (cron/systemd/CI/agent scheduler). It assumes POSIX shell, `curl`, and `jq`.

## Goals

1. Check whether `clawsec-suite` has an update available.
2. Poll the advisory feed.
3. Report new advisories, highlight affected installed skills, and require approval before removal actions.

---

## Configuration

```bash
INSTALL_ROOT="${INSTALL_ROOT:-$HOME/.openclaw/skills}"
SUITE_DIR="$INSTALL_ROOT/clawsec-suite"
GITHUB_RELEASES_API="${GITHUB_RELEASES_API:-https://api.github.com/repos/prompt-security/clawsec/releases?per_page=100}"
RELEASE_DOWNLOAD_BASE_URL="${RELEASE_DOWNLOAD_BASE_URL:-https://github.com/prompt-security/clawsec/releases/download}"
FEED_URL="${CLAWSEC_FEED_URL:-https://clawsec.prompt.security/advisories/feed.json}"
STATE_FILE="${CLAWSEC_SUITE_STATE_FILE:-$HOME/.openclaw/clawsec-suite-feed-state.json}"
MIN_FEED_INTERVAL_SECONDS="${MIN_FEED_INTERVAL_SECONDS:-300}"
```

---

## Step 0 — Basic sanity

```bash
set -euo pipefail

test -d "$SUITE_DIR"
test -f "$SUITE_DIR/skill.json"

echo "=== ClawSec Suite Heartbeat ==="
echo "When:  $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "Suite: $SUITE_DIR"
```

---

## Step 1 — Check suite version updates

```bash
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

INSTALLED_VER="$(jq -r '.version // ""' "$SUITE_DIR/skill.json" 2>/dev/null || true)"
LATEST_TAG=""
LATEST_VER=""

if curl -fsSLo "$TMP/releases.json" "$GITHUB_RELEASES_API"; then
  LATEST_TAG="$(jq -r '[.[] | select(.tag_name | startswith("clawsec-suite-v"))][0].tag_name // ""' "$TMP/releases.json" 2>/dev/null || true)"
fi

if [ -n "$LATEST_TAG" ]; then
  if curl -fsSLo "$TMP/remote-skill.json" "$RELEASE_DOWNLOAD_BASE_URL/$LATEST_TAG/skill.json"; then
    LATEST_VER="$(jq -r '.version // ""' "$TMP/remote-skill.json" 2>/dev/null || true)"
  fi
fi

echo "Installed suite: ${INSTALLED_VER:-unknown}"
echo "Latest suite:    ${LATEST_VER:-unknown}"

if [ -z "$LATEST_VER" ]; then
  echo "WARNING: Could not determine latest suite version from release metadata."
elif [ "$LATEST_VER" != "$INSTALLED_VER" ]; then
  echo "UPDATE AVAILABLE: clawsec-suite ${INSTALLED_VER:-unknown} -> $LATEST_VER"
else
  echo "Suite appears up to date."
fi
```

---

## Step 2 — Initialize advisory state

```bash
mkdir -p "$(dirname "$STATE_FILE")"

if [ ! -f "$STATE_FILE" ]; then
  echo '{"schema_version":"1.0","known_advisories":[],"last_feed_check":null,"last_feed_updated":null}' > "$STATE_FILE"
  chmod 600 "$STATE_FILE"
fi

if ! jq -e '.schema_version and .known_advisories' "$STATE_FILE" >/dev/null 2>&1; then
  echo "WARNING: Invalid state file, resetting: $STATE_FILE"
  cp "$STATE_FILE" "${STATE_FILE}.bak.$(date -u +%Y%m%d%H%M%S)" 2>/dev/null || true
  echo '{"schema_version":"1.0","known_advisories":[],"last_feed_check":null,"last_feed_updated":null}' > "$STATE_FILE"
  chmod 600 "$STATE_FILE"
fi
```

---

## Step 3 — Advisory feed check (embedded clawsec-feed)

```bash
now_epoch="$(date -u +%s)"
last_check="$(jq -r '.last_feed_check // "1970-01-01T00:00:00Z"' "$STATE_FILE")"
last_epoch="$(date -u -d "$last_check" +%s 2>/dev/null || date -u -j -f "%Y-%m-%dT%H:%M:%SZ" "$last_check" +%s 2>/dev/null || echo 0)"

if [ $((now_epoch - last_epoch)) -lt "$MIN_FEED_INTERVAL_SECONDS" ]; then
  echo "Feed check skipped (rate limit: ${MIN_FEED_INTERVAL_SECONDS}s)."
else
  FEED_TMP="$TMP/feed.json"
  FEED_SOURCE="$FEED_URL"

  if ! curl -fsSLo "$FEED_TMP" "$FEED_URL"; then
    if [ -f "$SUITE_DIR/advisories/feed.json" ]; then
      cp "$SUITE_DIR/advisories/feed.json" "$FEED_TMP"
      FEED_SOURCE="$SUITE_DIR/advisories/feed.json (local fallback)"
      echo "WARNING: Remote feed unavailable, using local fallback."
    else
      echo "ERROR: Remote feed unavailable and no local fallback feed found."
      exit 1
    fi
  fi

  if ! jq -e '.version and (.advisories | type == "array")' "$FEED_TMP" >/dev/null 2>&1; then
    echo "ERROR: Advisory feed has invalid format."
    exit 1
  fi

  echo "Feed source: $FEED_SOURCE"
  echo "Feed updated: $(jq -r '.updated // "unknown"' "$FEED_TMP")"

  NEW_IDS_FILE="$TMP/new_ids.txt"
  jq -r --argfile state "$STATE_FILE" '($state.known_advisories // []) as $known | [.advisories[]?.id | select(. != null and ($known | index(.) | not))] | .[]?' "$FEED_TMP" > "$NEW_IDS_FILE"

  if [ -s "$NEW_IDS_FILE" ]; then
    echo "New advisories:"
    while IFS= read -r id; do
      [ -z "$id" ] && continue
      jq -r --arg id "$id" '.advisories[] | select(.id == $id) | "- [\(.severity | ascii_upcase)] \(.id): \(.title)"' "$FEED_TMP"
      jq -r --arg id "$id" '.advisories[] | select(.id == $id) | "  Exploitability: \(.exploitability_score // "unknown" | ascii_upcase)"' "$FEED_TMP"
      jq -r --arg id "$id" '.advisories[] | select(.id == $id) | "  Action: \(.action // "Review advisory details")"' "$FEED_TMP"
    done < "$NEW_IDS_FILE"
  else
    echo "FEED_OK - no new advisories"
  fi

  echo "Affected installed skills (if any):"
  found_affected=0
  removal_recommended=0
  for skill_path in "$INSTALL_ROOT"/*; do
    [ -d "$skill_path" ] || continue
    skill_name="$(basename "$skill_path")"

    skill_hits="$(jq -r --arg skill_prefix "${skill_name}@" '
      [.advisories[]
      | select(any(.affected[]?; startswith($skill_prefix)))
      | "- [\(.severity | ascii_upcase)] \(.id): \(.title)\n  Action: \(.action // "Review advisory details")"
      ] | .[]?
    ' "$FEED_TMP")"

    if [ -n "$skill_hits" ]; then
      found_affected=1
      echo "- $skill_name is referenced by advisory feed entries"
      printf "%s\n" "$skill_hits"

      if jq -e --arg skill_prefix "${skill_name}@" '
        any(
          .advisories[];
          any(.affected[]?; startswith($skill_prefix))
          and (
            ((.type // "" | ascii_downcase) == "malicious_skill")
            or ((.title // "" | ascii_downcase | test("malicious|exfiltrat|backdoor|trojan|stealer")))
            or ((.description // "" | ascii_downcase | test("malicious|exfiltrat|backdoor|trojan|stealer")))
            or ((.action // "" | ascii_downcase | test("remove|uninstall|disable|do not use|quarantine")))
          )
        )
      ' "$FEED_TMP" >/dev/null 2>&1; then
        removal_recommended=1
      fi
    fi
  done

  if [ "$found_affected" -eq 0 ]; then
    echo "- none"
  fi

  if [ "$removal_recommended" -eq 1 ]; then
    echo "Approval required: ask the user for explicit approval before removing any skill."
    echo "Double-confirmation policy: install request is first intent; require a second explicit confirmation with advisory context."
  fi

  # Persist state
  current_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  state_tmp="$TMP/state.json"

  jq --arg t "$current_utc" --arg updated "$(jq -r '.updated // ""' "$FEED_TMP")" --argfile feed "$FEED_TMP" '
    .last_feed_check = $t
    | .last_feed_updated = (if $updated == "" then .last_feed_updated else $updated end)
    | .known_advisories = ((.known_advisories // []) + [$feed.advisories[]?.id] | map(select(. != null)) | unique)
  ' "$STATE_FILE" > "$state_tmp"

  mv "$state_tmp" "$STATE_FILE"
  chmod 600 "$STATE_FILE"
fi
```

---

## Output Summary

Heartbeat output should include:
- suite version status,
- advisory feed status,
- new advisory list (if any) with exploitability scores,
- installed skills that appear in advisory `affected` lists,
- and a double-confirmation reminder before risky install/remove actions.

### Exploitability-Based Prioritization

When alerting on advisories, prioritize by **exploitability score** in addition to severity:

- `high` exploitability: Trivially or easily exploitable with public tooling, immediate action required
- `medium` exploitability: Exploitable with specific conditions, standard priority
- `low` exploitability: Difficult to exploit or theoretical, low priority

**Priority Rule**: A HIGH severity + HIGH exploitability CVE should be treated more urgently than a CRITICAL severity + LOW exploitability CVE.

If your runtime sends alerts, treat `high` exploitability advisories affecting installed skills as immediate notifications, regardless of severity rating.


path: advisories/feed.json
content: {
  "version": "0.0.2",
  "updated": "2026-02-08T06:16:28Z",
  "description": "Community-driven security advisory feed for ClawSec. Automatically updated with OpenClaw-related CVEs from NVD and community-reported security incidents.",
  "advisories": [
    {
      "id": "CVE-2026-25593",
      "severity": "high",
      "type": "vulnerable_skill",
      "title": "OpenClaw is a personal AI assistant. Prior to 2026.1.20, an unauthenticated local client could use t...",
      "description": "OpenClaw is a personal AI assistant. Prior to 2026.1.20, an unauthenticated local client could use the Gateway WebSocket API to write config via config.apply and set unsafe cliPath values that were later used for command discovery, enabling command injection as the gateway user. This vulnerability is fixed in 2026.1.20.",
      "affected": [],
      "action": "Review and update affected components. See NVD for remediation details.",
      "published": "2026-02-06T21:16:17.790",
      "references": [
        "https://github.com/openclaw/openclaw/security/advisories/GHSA-g55j-c2v4-pjcg"
      ],
      "cvss_score": 8.4,
      "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2026-25593"
    },
    {
      "id": "CVE-2026-25475",
      "severity": "medium",
      "type": "vulnerable_skill",
      "title": "OpenClaw is a personal AI assistant. Prior to version 2026.1.30, the isValidMedia() function in src/...",
      "description": "OpenClaw is a personal AI assistant. Prior to version 2026.1.30, the isValidMedia() function in src/media/parse.ts allows arbitrary file paths including absolute paths, home directory paths, and directory traversal sequences. An agent can read any file on the system by outputting MEDIA:/path/to/file, exfiltrating sensitive data to the user/channel. This issue has been patched in version 2026.1.30.",
      "affected": [],
      "action": "Review and update affected components. See NVD for remediation details.",
      "published": "2026-02-04T20:16:07.287",
      "references": [
        "https://github.com/openclaw/openclaw/security/advisories/GHSA-r8g4-86fx-92mq"
      ],
      "cvss_score": 6.5,
      "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2026-25475"
    },
    {
      "id": "CVE-2026-25157",
      "severity": "high",
      "type": "vulnerable_skill",
      "title": "OpenClaw is a personal AI assistant. Prior to version 2026.1.29, there is an OS command injection vu...",
      "description": "OpenClaw is a personal AI assistant. Prior to version 2026.1.29, there is an OS command injection vulnerability via the Project Root Path in sshNodeCommand. The sshNodeCommand function constructed a shell script without properly escaping the user-supplied project path in an error message. When the cd command failed, the unescaped path was interpolated directly into an echo statement, allowing arbitrary command execution on the remote SSH host. The parseSSHTarget function did not validate that SSH target strings could not begin with a dash. An attacker-supplied target like -oProxyCommand=... would be interpreted as an SSH configuration flag rather than a hostname, allowing arbitrary command execution on the local machine. This issue has been patched in version 2026.1.29.",
      "affected": [],
      "action": "Review and update affected components. See NVD for remediation details.",
      "published": "2026-02-04T20:16:06.577",
      "references": [
        "https://github.com/openclaw/openclaw/security/advisories/GHSA-q284-4pvr-m585"
      ],
      "cvss_score": 7.7,
      "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2026-25157"
    },
    {
      "id": "CLAW-2026-0001",
      "severity": "high",
      "type": "prompt_injection",
      "title": "Data exfiltration attempt via helper-plus skill",
      "description": "The helper-plus skill was observed sending conversation data to an external server (suspicious-domain.com) on every invocation. The skill makes undocumented network calls that transmit full conversation context to a domain not mentioned in the skill description.",
      "affected": [
        "helper-plus@1.0.0",
        "helper-plus@1.0.1"
      ],
      "action": "Remove helper-plus immediately. Do not use versions 1.0.0 or 1.0.1. Wait for a verified patched version.",
      "published": "2026-02-04T09:30:00Z",
      "references": [],
      "source": "Community Report",
      "github_issue_url": "https://github.com/prompt-security/clawsec/issues/1",
      "reporter": {
        "agent_name": "SecurityBot",
        "opener_type": "agent"
      }
    },
    {
      "id": "CVE-2026-24763",
      "severity": "high",
      "type": "vulnerable_skill",
      "title": "OpenClaw (formerly  Clawdbot) is a personal AI assistant you run on your own devices. Prior to 2026....",
      "description": "OpenClaw (formerly  Clawdbot) is a personal AI assistant you run on your own devices. Prior to 2026.1.29, a command injection vulnerability existed in OpenClaw’s Docker sandbox execution mechanism due to unsafe handling of the PATH environment variable when constructing shell commands. An authenticated user able to control environment variables could influence command execution within the container context. This vulnerability is fixed in 2026.1.29.",
      "affected": [],
      "action": "Review and update affected components. See NVD for remediation details.",
      "published": "2026-02-02T23:16:08.593",
      "references": [
        "https://github.com/openclaw/openclaw/commit/771f23d36b95ec2204cc9a0054045f5d8439ea75",
        "https://github.com/openclaw/openclaw/releases/tag/v2026.1.29",
        "https://github.com/openclaw/openclaw/security/advisories/GHSA-mc68-q9jw-2h3v"
      ],
      "cvss_score": 8.8,
      "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2026-24763"
    },
    {
      "id": "CVE-2026-25253",
      "severity": "high",
      "type": "vulnerable_skill",
      "title": "OpenClaw (aka clawdbot or Moltbot) before 2026.1.29 obtains a gatewayUrl value from a query string a...",
      "description": "OpenClaw (aka clawdbot or Moltbot) before 2026.1.29 obtains a gatewayUrl value from a query string and automatically makes a WebSocket connection without prompting, sending a token value.",
      "affected": [],
      "action": "Review and update affected components. See NVD for remediation details.",
      "published": "2026-02-01T23:15:49.717",
      "references": [
        "https://depthfirst.com/post/1-click-rce-to-steal-your-moltbot-data-and-keys",
        "https://ethiack.com/news/blog/one-click-rce-moltbot",
        "https://github.com/openclaw/openclaw/security/advisories/GHSA-g8p2-7wf7-98mq"
      ],
      "cvss_score": 8.8,
      "nvd_url": "https://nvd.nist.gov/vuln/detail/CVE-2026-25253"
    }
  ]
}


path: hooks/clawsec-advisory-guardian/HOOK.md
content: ---
name: clawsec-advisory-guardian
description: Detect advisory matches for installed skills and require explicit user approval before any removal action.
metadata: { "openclaw": { "events": ["agent:bootstrap", "command:new"] } }
---

# ClawSec Advisory Guardian Hook

This hook checks the ClawSec advisory feed against locally installed skills on:

- `agent:bootstrap`
- `command:new`

When it detects an advisory affecting an installed skill, it posts an alert message.
If the advisory looks malicious or removal-oriented, it explicitly recommends removal
and asks for user approval first.

## Safety Contract

- The hook does not delete or modify skills.
- It only reports findings and requests explicit approval before removal.
- Alerts are deduplicated using `~/.openclaw/clawsec-suite-feed-state.json`.

## Optional Environment Variables

- `CLAWSEC_FEED_URL`: override remote feed URL.
- `CLAWSEC_FEED_SIG_URL`: override detached remote feed signature URL (default `${CLAWSEC_FEED_URL}.sig`).
- `CLAWSEC_FEED_CHECKSUMS_URL`: override remote checksum manifest URL (default sibling `checksums.json`).
- `CLAWSEC_FEED_CHECKSUMS_SIG_URL`: override detached remote checksum manifest signature URL.
- `CLAWSEC_FEED_PUBLIC_KEY`: path to pinned feed-signing public key PEM.
- `CLAWSEC_LOCAL_FEED`: override local fallback feed file.
- `CLAWSEC_LOCAL_FEED_SIG`: override local detached feed signature path.
- `CLAWSEC_LOCAL_FEED_CHECKSUMS`: override local checksum manifest path.
- `CLAWSEC_LOCAL_FEED_CHECKSUMS_SIG`: override local checksum manifest signature path.
- [REDACTED_SECRET]: set to `0` only for emergency troubleshooting (default verifies checksums).
- `CLAWSEC_ALLOW_UNSIGNED_FEED`: set to `1` only for temporary migration compatibility; bypasses signature/checksum verification.
- `CLAWSEC_SUITE_STATE_FILE`: override state file path.
- `CLAWSEC_INSTALL_ROOT`: override installed skills root.
- `CLAWSEC_SUITE_DIR`: override clawsec-suite install path.
- `CLAWSEC_HOOK_INTERVAL_SECONDS`: minimum interval between hook scans (default `300`).


path: hooks/clawsec-advisory-guardian/handler.ts
content: import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { uniqueStrings, resolveConfiguredPath } from "./lib/utils.mjs";
import { defaultChecksumsUrl, loadLocalFeed, loadRemoteFeed } from "./lib/feed.mjs";
import type { HookEvent, FeedPayload, AdvisoryMatch } from "./lib/types.ts";
import { loadState, persistState } from "./lib/state.ts";
import { discoverInstalledSkills, findMatches, matchKey, buildAlertMessage } from "./lib/matching.ts";
import { loadAdvisorySuppression, isAdvisorySuppressed } from "./lib/suppression.mjs";

const DEFAULT_FEED_URL =
  "https://clawsec.prompt.security/advisories/feed.json";
const DEFAULT_SCAN_INTERVAL_SECONDS = 300;
let unsignedModeWarningShown = false;

function parsePositiveInteger(value: string | undefined, fallback: number): number {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return fallback;
  }
  return parsed;
}

function toEventName(event: HookEvent): string {
  const eventType = String(event.type ?? "").trim();
  const action = String(event.action ?? "").trim();
  if (!eventType || !action) return "";
  return `${eventType}:${action}`;
}

function shouldHandleEvent(event: HookEvent): boolean {
  const eventName = toEventName(event);
  return eventName === "agent:bootstrap" || eventName === "command:new";
}

function epochMs(isoTimestamp: string | null): number {
  if (!isoTimestamp) return 0;
  const parsed = Date.parse(isoTimestamp);
  return Number.isNaN(parsed) ? 0 : parsed;
}

function scannedRecently(lastScan: string | null, minIntervalSeconds: number): boolean {
  const sinceMs = Date.now() - epochMs(lastScan);
  return sinceMs >= 0 && sinceMs < minIntervalSeconds * 1000;
}

function configuredPath(
  explicit: string | undefined,
  fallback: string,
  label: string,
): string {
  return resolveConfiguredPath(explicit, fallback, {
    label,
    onInvalid: (error, rawValue) => {
      console.warn(
        `[clawsec-advisory-guardian] invalid ${label} path "${rawValue}", using default "${fallback}": ${String(error)}`,
      );
    },
  });
}

async function loadFeed(options: {
  feedUrl: string;
  feedSignatureUrl: string;
  feedChecksumsUrl: string;
  feedChecksumsSignatureUrl: string;
  localFeedPath: string;
  localFeedSignaturePath: string;
  localFeedChecksumsPath: string;
  localFeedChecksumsSignaturePath: string;
  feedPublicKeyPath: string;
  allowUnsigned: boolean;
  verifyChecksumManifest: boolean;
}): Promise<FeedPayload> {
  const publicKeyPem = options.allowUnsigned ? "" : await fs.readFile(options.feedPublicKeyPath, "utf8");

  const remoteFeed = await loadRemoteFeed(options.feedUrl, {
    signatureUrl: options.feedSignatureUrl,
    checksumsUrl: options.feedChecksumsUrl,
    checksumsSignatureUrl: options.feedChecksumsSignatureUrl,
    publicKeyPem,
    checksumsPublicKeyPem: publicKeyPem,
    allowUnsigned: options.allowUnsigned,
    verifyChecksumManifest: options.verifyChecksumManifest,
  });
  if (remoteFeed) return remoteFeed;

  return await loadLocalFeed(options.localFeedPath, {
    signaturePath: options.localFeedSignaturePath,
    checksumsPath: options.localFeedChecksumsPath,
    checksumsSignaturePath: options.localFeedChecksumsSignaturePath,
    publicKeyPem,
    checksumsPublicKeyPem: publicKeyPem,
    allowUnsigned: options.allowUnsigned,
    verifyChecksumManifest: options.verifyChecksumManifest,
    checksumPublicKeyEntry: path.basename(options.feedPublicKeyPath),
  });
}

const handler = async (event: HookEvent): Promise<void> => {
  if (!shouldHandleEvent(event)) return;

  const installRoot = configuredPath(
    process.env.CLAWSEC_INSTALL_ROOT || process.env.INSTALL_ROOT,
    path.join(os.homedir(), ".openclaw", "skills"),
    "CLAWSEC_INSTALL_ROOT",
  );
  const suiteDir = configuredPath(
    process.env.CLAWSEC_SUITE_DIR,
    path.join(installRoot, "clawsec-suite"),
    "CLAWSEC_SUITE_DIR",
  );
  const localFeedPath = configuredPath(
    process.env.CLAWSEC_LOCAL_FEED,
    path.join(suiteDir, "advisories", "feed.json"),
    "CLAWSEC_LOCAL_FEED",
  );
  const localFeedSignaturePath = configuredPath(
    process.env.CLAWSEC_LOCAL_FEED_SIG,
    `${localFeedPath}.sig`,
    "CLAWSEC_LOCAL_FEED_SIG",
  );
  const localFeedChecksumsPath = configuredPath(
    process.env.CLAWSEC_LOCAL_FEED_CHECKSUMS,
    path.join(path.dirname(localFeedPath), "checksums.json"),
    "CLAWSEC_LOCAL_FEED_CHECKSUMS",
  );
  const localFeedChecksumsSignaturePath = configuredPath(
    process.env.CLAWSEC_LOCAL_FEED_CHECKSUMS_SIG,
    `${localFeedChecksumsPath}.sig`,
    "CLAWSEC_LOCAL_FEED_CHECKSUMS_SIG",
  );
  const feedPublicKeyPath = configuredPath(
    process.env.CLAWSEC_FEED_PUBLIC_KEY,
    path.join(suiteDir, "advisories", "feed-signing-public.pem"),
    "CLAWSEC_FEED_PUBLIC_KEY",
  );
  const stateFile = configuredPath(
    process.env.CLAWSEC_SUITE_STATE_FILE,
    path.join(os.homedir(), ".openclaw", "clawsec-suite-feed-state.json"),
    "CLAWSEC_SUITE_STATE_FILE",
  );
  const feedUrl = process.env.CLAWSEC_FEED_URL || DEFAULT_FEED_URL;
  const feedSignatureUrl = process.env.CLAWSEC_FEED_SIG_URL || `${feedUrl}.sig`;
  const feedChecksumsUrl = process.env.CLAWSEC_FEED_CHECKSUMS_URL || defaultChecksumsUrl(feedUrl);
  const feedChecksumsSignatureUrl =
    process.env.CLAWSEC_FEED_CHECKSUMS_SIG_URL || `${feedChecksumsUrl}.sig`;
  const allowUnsigned = process.env.CLAWSEC_ALLOW_UNSIGNED_FEED === "1";
  const verifyChecksumManifest = process.env.CLAWSEC_VERIFY_CHECKSUM_MANIFEST !== "0";
  const scanIntervalSeconds = parsePositiveInteger(
    process.env.CLAWSEC_HOOK_INTERVAL_SECONDS,
    DEFAULT_SCAN_INTERVAL_SECONDS,
  );

  if (allowUnsigned && !unsignedModeWarningShown) {
    unsignedModeWarningShown = true;
    console.warn(
      "[clawsec-advisory-guardian] CLAWSEC_ALLOW_UNSIGNED_FEED=1 is enabled. " +
        "This bypass is temporary migration compatibility and should be removed as soon as signed feed artifacts are available.",
    );
  }

  const forceScan = toEventName(event) === "command:new";
  const state = await loadState(stateFile);
  if (!forceScan && scannedRecently(state.last_hook_scan, scanIntervalSeconds)) {
    return;
  }

  let feed: FeedPayload;
  try {
    feed = await loadFeed({
      feedUrl,
      feedSignatureUrl,
      feedChecksumsUrl,
      feedChecksumsSignatureUrl,
      localFeedPath,
      localFeedSignaturePath,
      localFeedChecksumsPath,
      localFeedChecksumsSignaturePath,
      feedPublicKeyPath,
      allowUnsigned,
      verifyChecksumManifest,
    });
  } catch (error) {
    console.warn(`[clawsec-advisory-guardian] failed to load advisory feed: ${String(error)}`);
    return;
  }

  const nowIso = new Date().toISOString();
  state.last_hook_scan = nowIso;
  state.last_feed_check = nowIso;

  if (typeof feed.updated === "string" && feed.updated.trim()) {
    state.last_feed_updated = feed.updated;
  }

  const advisoryIds = feed.advisories
    .map((advisory) => advisory.id)
    .filter((id): id is string => typeof id === "string" && id.trim() !== "");
  state.known_advisories = uniqueStrings([...state.known_advisories, ...advisoryIds]);

  const installedSkills = await discoverInstalledSkills(installRoot);
  const allMatches = findMatches(feed, installedSkills);

  if (allMatches.length === 0) {
    await persistState(stateFile, state);
    return;
  }

  // Load advisory suppression config (sentinel-gated: requires enabledFor: ["advisory"])
  let suppressionConfig;
  try {
    suppressionConfig = await loadAdvisorySuppression();
  } catch (err) {
    console.warn(`[clawsec-advisory-guardian] failed to load suppression config: ${String(err)}`);
    suppressionConfig = { suppressions: [], enabledFor: [], source: "none" };
  }

  // Partition matches into active and suppressed
  const matches: AdvisoryMatch[] = [];
  const suppressedMatches: AdvisoryMatch[] = [];
  for (const match of allMatches) {
    if (isAdvisorySuppressed(match, suppressionConfig.suppressions)) {
      suppressedMatches.push(match);
    } else {
      matches.push(match);
    }
  }

  const unseenMatches: AdvisoryMatch[] = [];
  for (const match of matches) {
    const key = matchKey(match);
    if (state.notified_matches[key]) {
      continue;
    }
    unseenMatches.push(match);
    state.notified_matches[key] = nowIso;
  }

  if (unseenMatches.length > 0 && Array.isArray(event.messages)) {
    event.messages.push(buildAlertMessage(unseenMatches, installRoot));
  }

  if (suppressedMatches.length > 0 && Array.isArray(event.messages)) {
    event.messages.push(
      `[clawsec-advisory-guardian] ${suppressedMatches.length} advisory match(es) suppressed by allowlist config.`,
    );
  }

  await persistState(stateFile, state);
};

export default handler;


path: hooks/clawsec-advisory-guardian/lib/advisory_scope.mjs
content: const ADVISORY_APPLICATION_OPENCLAW = "openclaw";
const ADVISORY_APPLICATION_ALL = "all";

/**
 * @param {unknown} value
 * @returns {string[]}
 */
function normalizeApplicationValue(value) {
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    return normalized ? [normalized] : [];
  }

  if (Array.isArray(value)) {
    return value
      .filter((entry) => typeof entry === "string")
      .map((entry) => entry.trim().toLowerCase())
      .filter(Boolean);
  }

  return [];
}

/**
 * Decide whether an advisory should be considered by OpenClaw-facing flows.
 *
 * Backward compatibility rule:
 * - Advisories without `application` remain eligible.
 *
 * @param {{ application?: unknown }} advisory
 * @returns {boolean}
 */
export function advisoryAppliesToOpenclaw(advisory) {
  const application = advisory?.application;
  if (application === undefined || application === null) {
    return true;
  }

  const applications = normalizeApplicationValue(application);
  if (applications.length === 0) {
    return true;
  }

  return (
    applications.includes(ADVISORY_APPLICATION_OPENCLAW) ||
    applications.includes(ADVISORY_APPLICATION_ALL)
  );
}


path: hooks/clawsec-advisory-guardian/lib/local_file_io.mjs
content: import fs from "node:fs/promises";

export async function loadTextFile(filePath) {
  return await fs.readFile(filePath, "utf8");
}


path: hooks/clawsec-advisory-guardian/lib/matching.ts
content: import fs from "node:fs/promises";
import path from "node:path";
import { isObject, normalizeSkillName, uniqueStrings } from "./utils.mjs";
import { advisoryAppliesToOpenclaw } from "./advisory_scope.mjs";
import { versionMatches } from "./version.mjs";
import { parseAffectedSpecifier } from "./feed.mjs";
import type { Advisory, FeedPayload, InstalledSkill, AdvisoryMatch } from "./types.ts";

export async function discoverInstalledSkills(installRoot: string): Promise<InstalledSkill[]> {
  let entries: import("node:fs").Dirent[];
  try {
    entries = await fs.readdir(installRoot, { withFileTypes: true });
  } catch {
    return [];
  }

  const skills: InstalledSkill[] = [];
  for (const entry of entries) {
    if (!entry.isDirectory()) continue;

    const fallbackName = entry.name;
    const skillDir = path.join(installRoot, entry.name);
    const skillJsonPath = path.join(skillDir, "skill.json");

    let skillName = fallbackName;
    let version: string | null = "unknown";

    try {
      const rawSkillJson = await fs.readFile(skillJsonPath, "utf8");
      const parsedSkillJson = JSON.parse(rawSkillJson);
      if (isObject(parsedSkillJson) && typeof parsedSkillJson.name === "string" && parsedSkillJson.name.trim()) {
        skillName = parsedSkillJson.name.trim();
      }
      if (
        isObject(parsedSkillJson) &&
        typeof parsedSkillJson.version === "string" &&
        parsedSkillJson.version.trim()
      ) {
        version = parsedSkillJson.version.trim();
      }
    } catch {
      // best-effort scan: keep fallback directory name when skill.json is missing or invalid
    }

    skills.push({ name: skillName, dirName: entry.name, version });
  }

  return skills;
}

export function affectedSpecifierMatchesSkill(rawSpecifier: string, skill: InstalledSkill): boolean {
  const parsed = parseAffectedSpecifier(rawSpecifier);
  if (!parsed) return false;

  const specName = normalizeSkillName(parsed.name);
  const skillName = normalizeSkillName(skill.name);
  if (specName !== skillName) return false;

  return versionMatches(skill.version, parsed.versionSpec);
}

export function advisoryMatchesSkill(advisory: Advisory, skill: InstalledSkill): string[] {
  const affected = Array.isArray(advisory.affected) ? advisory.affected : [];
  const matches = affected.filter((specifier) => affectedSpecifierMatchesSkill(specifier, skill));
  return uniqueStrings(matches);
}

export function findMatches(feed: FeedPayload, installedSkills: InstalledSkill[]): AdvisoryMatch[] {
  const matches: AdvisoryMatch[] = [];

  for (const advisory of feed.advisories) {
    if (!advisoryAppliesToOpenclaw(advisory)) continue;

    const affected = Array.isArray(advisory.affected) ? advisory.affected : [];
    if (affected.length === 0) continue;

    for (const skill of installedSkills) {
      const matchedAffected = advisoryMatchesSkill(advisory, skill);
      if (matchedAffected.length === 0) continue;
      matches.push({ advisory, skill, matchedAffected });
    }
  }

  return matches;
}

export function matchKey(match: AdvisoryMatch): string {
  const normalizedSkillName = normalizeSkillName(match.skill.name);
  const version = match.skill.version ?? "unknown";
  const advisoryId =
    match.advisory.id ??
    `${match.advisory.title ?? "untitled"}::${match.advisory.published ?? match.advisory.updated ?? "unknown-ts"}`;
  return `${advisoryId}::${normalizedSkillName}@${version}`;
}

export function looksMalicious(advisory: Advisory): boolean {
  const type = String(advisory.type ?? "").toLowerCase();
  const combined = `${advisory.title ?? ""} ${advisory.description ?? ""} ${advisory.action ?? ""}`.toLowerCase();

  if (type === "malicious_skill" || type === "malicious_plugin") return true;
  if (/\b(malicious|exfiltrat(e|ion)|backdoor|trojan|credential theft|stealer)\b/.test(combined)) return true;
  return false;
}

export function looksRemovalRecommended(advisory: Advisory): boolean {
  const combined = `${advisory.action ?? ""} ${advisory.title ?? ""} ${advisory.description ?? ""}`.toLowerCase();
  return /\b(remove|uninstall|delete|disable|do not use|quarantine)\b/.test(combined);
}

export function buildAlertMessage(matches: AdvisoryMatch[], installRoot: string): string {
  const lines: string[] = [];
  lines.push("CLAWSEC ALERT: advisory feed matches installed skill(s).");
  lines.push("Affected skill advisories:");

  const MAX_LISTED = 8;
  for (const match of matches.slice(0, MAX_LISTED)) {
    const severity = String(match.advisory.severity ?? "unknown").toUpperCase();
    const advisoryId = match.advisory.id ?? "unknown-id";
    const version = match.skill.version ?? "unknown";
    const matched = match.matchedAffected.join(", ");
    lines.push(
      `- [${severity}] ${advisoryId} -> ${match.skill.name}@${version}` +
        (matched ? ` (matched: ${matched})` : ""),
    );
    if (match.advisory.action) {
      lines.push(`  Action: ${match.advisory.action}`);
    }
  }

  if (matches.length > MAX_LISTED) {
    lines.push(`- ... ${matches.length - MAX_LISTED} additional match(es) not shown`);
  }

  const removalMatches = matches.filter((entry) => looksMalicious(entry.advisory) || looksRemovalRecommended(entry.advisory));
  if (removalMatches.length > 0) {
    const impactedSkills = uniqueStrings(removalMatches.map((entry) => entry.skill.name));
    const impactedDirs = uniqueStrings(removalMatches.map((entry) => entry.skill.dirName));
    lines.push("");
    lines.push("Recommendation: one or more matches indicate potentially malicious or unsafe skills.");
    lines.push("Best practice: remove or disable affected skills only after explicit user approval.");
    lines.push(
      "Double-confirmation policy: treat the install request as first intent and require an additional explicit confirmation with this advisory context.",
    );
    lines.push(`Approval needed: ask the user to approve removal of: ${impactedSkills.join(", ")}.`);
    lines.push("Candidate removal paths:");
    for (const dir of impactedDirs) {
      lines.push(`- ${path.join(installRoot, dir)}`);
    }
  } else {
    lines.push("");
    lines.push("Recommendation: review advisories and update/remove affected skills as directed.");
  }

  return lines.join("\n");
}


path: hooks/clawsec-advisory-guardian/lib/state.ts
content: import fs from "node:fs/promises";
import path from "node:path";
import { isObject, uniqueStrings } from "./utils.mjs";
import type { AdvisoryState } from "./types.ts";

export const DEFAULT_STATE: AdvisoryState = {
  schema_version: "1.1",
  known_advisories: [],
  last_feed_check: null,
  last_feed_updated: null,
  last_hook_scan: null,
  notified_matches: {},
};

export function normalizeState(raw: unknown): AdvisoryState {
  if (!isObject(raw)) {
    return { ...DEFAULT_STATE };
  }

  const knownAdvisories = Array.isArray(raw.known_advisories)
    ? uniqueStrings(raw.known_advisories.filter((value): value is string => typeof value === "string" && value.trim() !== ""))
    : [];

  const notifiedMatches: Record<string, string> = {};
  if (isObject(raw.notified_matches)) {
    for (const [key, value] of Object.entries(raw.notified_matches)) {
      if (typeof value === "string" && value.trim()) {
        notifiedMatches[key] = value;
      }
    }
  }

  return {
    schema_version: "1.1",
    known_advisories: knownAdvisories,
    last_feed_check: typeof raw.last_feed_check === "string" ? raw.last_feed_check : null,
    last_feed_updated: typeof raw.last_feed_updated === "string" ? raw.last_feed_updated : null,
    last_hook_scan: typeof raw.last_hook_scan === "string" ? raw.last_hook_scan : null,
    notified_matches: notifiedMatches,
  };
}

export async function loadState(stateFile: string): Promise<AdvisoryState> {
  try {
    const raw = await fs.readFile(stateFile, "utf8");
    return normalizeState(JSON.parse(raw));
  } catch {
    return { ...DEFAULT_STATE };
  }
}

export async function persistState(stateFile: string, state: AdvisoryState): Promise<void> {
  const normalized = normalizeState(state);
  await fs.mkdir(path.dirname(stateFile), { recursive: true });
  const tmpFile = `${stateFile}.tmp-${process.pid}-${Date.now()}`;
  await fs.writeFile(tmpFile, `${JSON.stringify(normalized, null, 2)}\n`, {
    encoding: "utf8",
    mode: 0o600,
  });
  await fs.rename(tmpFile, stateFile);
  try {
    await fs.chmod(stateFile, 0o600);
  } catch (err: unknown) {
    const code = err instanceof Error && "code" in err ? (err as { code: string }).code : undefined;
    if (code === "ENOTSUP" || code === "EPERM") {
      console.warn(
        `Warning: chmod 0600 failed for ${stateFile} (${code}). ` +
          "File permissions may not be enforced on this platform/filesystem.",
      );
    } else {
      throw err;
    }
  }
}


path: hooks/clawsec-advisory-guardian/lib/suppression.mjs
content: import fs from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import { isObject, normalizeSkillName, resolveUserPath } from "./utils.mjs";

const DEFAULT_PRIMARY_PATH = path.join(os.homedir(), ".openclaw", "security-audit.json");
const DEFAULT_FALLBACK_PATH = ".clawsec/allowlist.json";

const EMPTY_CONFIG = Object.freeze({
  suppressions: [],
  enabledFor: [],
  source: "none",
});

/**
 * @param {unknown} entry
 * @param {number} index
 * @param {string} source
 * @returns {{ checkId: string, skill: string, reason: string, suppressedAt: string }}
 */
function normalizeRule(entry, index, source) {
  if (!isObject(entry)) {
    throw new Error(`Suppression entry at index ${index} in ${source} must be an object`);
  }

  const checkId = typeof entry.checkId === "string" ? entry.checkId.trim() : "";
  const skill = typeof entry.skill === "string" ? entry.skill.trim() : "";
  const reason = typeof entry.reason === "string" ? entry.reason.trim() : "";
  const suppressedAt = typeof entry.suppressedAt === "string" ? entry.suppressedAt.trim() : "";

  if (!checkId) throw new Error(`Suppression entry at index ${index} in ${source} missing required field: checkId`);
  if (!skill) throw new Error(`Suppression entry at index ${index} in ${source} missing required field: skill`);
  if (!reason) throw new Error(`Suppression entry at index ${index} in ${source} missing required field: reason`);
  if (!suppressedAt) throw new Error(`Suppression entry at index ${index} in ${source} missing required field: suppressedAt`);

  return { checkId, skill, reason, suppressedAt };
}

/**
 * @param {unknown} raw
 * @param {string} source
 * @returns {{ suppressions: Array, enabledFor: string[], source: string }}
 */
function parseConfig(raw, source) {
  if (!isObject(raw)) {
    throw new Error(`Config at ${source} must be a JSON object`);
  }

  if (!Array.isArray(raw.suppressions)) {
    throw new Error(`Config at ${source} missing 'suppressions' array`);
  }

  const suppressions = [];
  for (let i = 0; i < raw.suppressions.length; i++) {
    suppressions.push(normalizeRule(raw.suppressions[i], i, source));
  }

  const enabledFor = Array.isArray(raw.enabledFor)
    ? raw.enabledFor
        .filter((v) => typeof v === "string" && v.trim() !== "")
        .map((v) => v.trim().toLowerCase())
    : [];

  return { suppressions, enabledFor, source };
}

/**
 * @param {string} configPath
 * @returns {Promise<{ suppressions: Array, enabledFor: string[], source: string } | null>}
 */
async function loadConfigFromPath(configPath) {
  try {
    const raw = await fs.readFile(configPath, "utf8");
    return parseConfig(JSON.parse(raw), configPath);
  } catch (err) {
    if (err.code === "ENOENT") return null;
    if (err.code === "EACCES") throw new Error(`Permission denied reading config: ${configPath}`, { cause: err });
    if (err instanceof SyntaxError) throw new Error(`Malformed JSON in ${configPath}: ${err.message}`, { cause: err });
    throw err;
  }
}

/**
 * Load advisory suppression config using the same 4-tier path resolution
 * as the audit watchdog config loader.
 *
 * The config file must include "advisory" in its enabledFor sentinel
 * array for advisory suppression to activate. No CLI flag needed -- the
 * sentinel in the config file IS the gate.
 *
 * @param {string} [configPath] - Optional explicit config file path
 * @returns {Promise<{ suppressions: Array, enabledFor: string[], source: string }>}
 */
export async function loadAdvisorySuppression(configPath) {
  // Priority 1: Explicit path
  if (configPath) {
    const resolved = resolveUserPath(configPath, { label: "advisory suppression config path" });
    const config = await loadConfigFromPath(resolved);
    if (!config) throw new Error(`Advisory suppression config not found: ${resolved}`);
    if (!config.enabledFor.includes("advisory")) return { ...EMPTY_CONFIG };
    return config;
  }

  // Priority 2: Environment variable
  const envPath = process.env.OPENCLAW_AUDIT_CONFIG;
  if (typeof envPath === "string" && envPath.trim()) {
    const resolved = resolveUserPath(envPath.trim(), { label: "OPENCLAW_AUDIT_CONFIG" });
    const config = await loadConfigFromPath(resolved);
    if (config && config.enabledFor.includes("advisory")) return config;
    return { ...EMPTY_CONFIG };
  }

  // Priority 3: Primary default path
  const primary = await loadConfigFromPath(DEFAULT_PRIMARY_PATH);
  if (primary && primary.enabledFor.includes("advisory")) return primary;

  // Priority 4: Fallback path
  const fallback = await loadConfigFromPath(DEFAULT_FALLBACK_PATH);
  if (fallback && fallback.enabledFor.includes("advisory")) return fallback;

  return { ...EMPTY_CONFIG };
}

/**
 * Check if an advisory match should be suppressed.
 *
 * Matching requires BOTH:
 *   - advisory.id === rule.checkId (exact)
 *   - normalizeSkillName(skill.name) === normalizeSkillName(rule.skill) (case-insensitive)
 *
 * @param {{ advisory: { id?: string }, skill: { name: string } }} match
 * @param {Array<{ checkId: string, skill: string }>} suppressions
 * @returns {boolean}
 */
export function isAdvisorySuppressed(match, suppressions) {
  if (!Array.isArray(suppressions) || suppressions.length === 0) return false;

  const advisoryId = match.advisory.id ?? "";
  const skillName = normalizeSkillName(match.skill.name);

  return suppressions.some(
    (rule) => rule.checkId === advisoryId && normalizeSkillName(rule.skill) === skillName,
  );
}


path: hooks/clawsec-advisory-guardian/lib/types.ts
content: export type HookEvent = {
  type?: string;
  action?: string;
  messages?: string[];
};

export type Advisory = {
  id?: string;
  ghsa_id?: string;
  cve_id?: string | null;
  status?: string;
  stale?: boolean;
  source_feed?: string;
  severity?: string;
  type?: string;
  application?: string | string[];
  title?: string;
  description?: string;
  action?: string;
  published?: string;
  updated?: string;
  affected?: string[];
  platforms?: string[];
  references?: string[];
  nvd_url?: string | null;
  github_advisory_url?: string;
};

export type FeedPayload = {
  version: string;
  updated?: string;
  advisories: Advisory[];
};

export type InstalledSkill = {
  name: string;
  dirName: string;
  version: string | null;
};

export type AdvisoryMatch = {
  advisory: Advisory;
  skill: InstalledSkill;
  matchedAffected: string[];
};

export type AdvisoryState = {
  schema_version: string;
  known_advisories: string[];
  last_feed_check: string | null;
  last_feed_updated: string | null;
  last_hook_scan: string | null;
  notified_matches: Record<string, string>;
};


path: scripts/local_file_io.mjs
content: import fs from "node:fs/promises";

export async function loadTextFile(filePath) {
  return await fs.readFile(filePath, "utf8");
}


Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal:  | SkillSpector: suspicious (HIGH)