
Clawsec Suite
- 761 installs
- 1.1k repo stars
- Updated August 4, 2026
- prompt-security/clawsec
ClawSec Suite is a Claude Code security skill that monitors advisory feeds, verifies cryptographic signatures, and blocks malicious AI-coding skills before they run for developers who install third-party agent skills.
About
ClawSec Suite is a ClawSec suite manager skill (version 0.1.8) that hardens OpenClaw-based agent workflows against untrusted skills. Setup installs an advisory hook under ~/.openclaw/hooks, optionally schedules an openclaw cron job, and can pull guard skills via npx clawhub@latest install. Runtime requires node, npx, openclaw, curl, jq, shasum, openssl, and unzip. Developers reach for ClawSec Suite when onboarding community skills into Claude Code or Cursor pipelines and need signature-checked, approval-gated blocking instead of running unknown SKILL.md payloads blindly.
- Monitors the ClawSec advisory feed and tracks new advisories since last check
- Cross-references advisories against locally installed skills
- Recommends removal for malicious-skill advisories with explicit approval gating
- Performs cryptographic signature verification on all artifacts
- Serves as the guided setup and management entrypoint for the full ClawSec protection suite
Clawsec Suite by the numbers
- 761 all-time installs (skills.sh)
- +4 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #442 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/prompt-security/clawsec --skill clawsec-suiteAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 761 |
|---|---|
| repo stars | ★ 1.1k |
| Security audit | 1 / 3 scanners passed |
| Last updated | August 4, 2026 |
| Repository | prompt-security/clawsec ↗ |
How do you block malicious Claude Code skills before execution?
Automatically monitor security advisories, verify signatures, and block malicious AI-coding skills before they run.
Who is it for?
Developers running OpenClaw or clawhub skill installs who need automated advisory monitoring and signature verification on untrusted agent skills.
Skip if: Teams without OpenClaw/clawhub in their stack or projects that only use built-in IDE features with no third-party SKILL.md installs.
When should I use this skill?
User installs community agent skills, mentions clawsec, clawhub, skill supply-chain risk, or wants advisory monitoring for OpenClaw hooks.
What you get
Advisory hook under ~/.openclaw/hooks, optional openclaw cron monitoring job, signature-verified skill approvals, and guard packages installed via clawhub.
- ~/.openclaw/hooks advisory hook
- Optional cron monitoring job
- Guard skills via clawhub
By the numbers
- Ships as clawsec-suite version 0.1.8
- Requires 8 runtime binaries including openclaw, openssl, and jq
Files
ClawSec Suite
Vercel Skills Installation
Install with the Vercel Skills CLI for this harness:
npx skills add prompt-security/clawsec --skill clawsec-suite -a openclaw -yOperational 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 unattendedopenclaw cronjob, and usenpx clawhub@latest installfor 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:
hooks/clawsec-advisory-guardian/ - 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:
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)
npx clawhub@latest install clawsec-suiteOption B: Manual download with signature + checksum verification
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="711424e4535f84093fefb024cd1ca4ec87439e53907b305b79a631d5befba9c8"
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:
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:
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:bootstrapand/new(command:new), - compare advisory
affectedentries against installed skills, - consider advisories with
application: "openclaw"(and legacy entries withoutapplicationfor 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:
SUITE_DIR="${INSTALL_ROOT:-$HOME/.openclaw/skills}/clawsec-suite"
node "$SUITE_DIR/scripts/guarded_skill_install.mjs" --skill helper-plus --version 1.0.1Behavior:
- If no advisory match is found, install proceeds.
- If
--versionis 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:
node "$SUITE_DIR/scripts/guarded_skill_install.mjs" --skill helper-plus --version 1.0.1 --confirm-advisoryThis 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 withCLAWSEC_FEED_SIG_URL) - Remote checksums manifest URL: sibling
checksums.json(override withCLAWSEC_FEED_CHECKSUMS_URL) - Local seed fallback:
~/.openclaw/skills/clawsec-suite/advisories/feed.json - Local feed signature:
${CLAWSEC_LOCAL_FEED}.sig(override withCLAWSEC_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 withCLAWSEC_FEED_PUBLIC_KEY) - State file:
~/.openclaw/clawsec-suite-feed-state.json - Hook rate-limit env (OpenClaw hook):
CLAWSEC_HOOK_INTERVAL_SECONDS(default300)
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
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"
fiExploitability 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, orunknown - 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.
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
{
"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-25593orCLAW-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:
{
"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:
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:
node "$SUITE_DIR/scripts/discover_skill_catalog.mjs" --jsonSecurity Notes
- Always verify
checksums.jsonsignature before trusting its file URLs/hashes, then verify each file checksum. - Verify advisory feed detached signatures; do not enable
CLAWSEC_ALLOW_UNSIGNED_FEEDoutside temporary migration windows. - Keep advisory polling rate-limited (at least 5 minutes between checks).
- Treat
criticalandhighadvisories 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.
# Exclude local caches and build outputs from ClawHub upload
.DS_Store
.git/
__pycache__/
*.pyc
*.pyo
*.egg-info/
dist/
build/
.env
.venv/
.cache/
# Exclude local test harness files from published payloads.
test/
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAS7nijfMcUoOBCj4yOXJX+GYGv2pFl2Yaha1P4v5Cm6A=
-----END PUBLIC KEY-----
{
"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"
}
]
}
Changelog
[0.1.10] - 2026-06-10
Changed
- Re-released skill package with updated marketplace grouping and signed release trust artifacts for Vercel-compatible skill installation.
All notable changes to the ClawSec Suite will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[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.jsonSBOM metadata so release archives include every file required by the advisory guardian hook.
[0.1.7] - 2026-04-16
Changed
- Added
.clawhubignorecoverage fortest/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.mjsandhooks/clawsec-advisory-guardian/lib/local_file_io.mjsso 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.mjsandscripts/setup_advisory_cron.mjs. - Regression coverage for setup disclosure behavior in
test/setup_disclosure.test.mjs.
Changed
- Declared
node,npx,openclaw, andunzipin the suite runtime metadata to match the documented setup and install flows. - Updated catalog messaging for
openclaw-audit-watchdogto 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.
- 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 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 withoutapplicationremain 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 withenabledFor: ["advisory"]sentinel gate.isAdvisorySuppressed()-- matchesadvisory.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.mjsto dynamically discover installable skills fromhttps://clawsec.prompt.security/skills/index.json. - Added
test/skill_catalog_discovery.test.mjsto validate remote-catalog loading and fallback behavior. - Added CI signing-key drift guard script:
scripts/ci/verify_signing_key_consistency.sh.
Changed
- Updated
SKILL.mdto 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-watchdogas a standalone skill (not embedded inclawsec-suite).
Security
- Signing key drift control: CI now enforces that all public key references (inline SKILL.md PEM, canonical
.pemfiles, 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.signaming 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.ymlworkflow to download release assets to temporary directory before signature verification, ensuring unverified files never reach public directory - Fixed schema mismatch: Updated
deploy-pages.ymlto generatechecksums.jsonwith properschema_versionandalgorithmfields that match parser expectations - Fixed missing checksums abort: Updated
loadRemoteFeedto gracefully skip checksum verification whenchecksums.jsonis missing (e.g., GitHub raw content), while still enforcing fail-closed signature verification - Fixed parser strictness: Enhanced
parseChecksumsManifestto 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
secureFetchwrapper 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 → skiptodownload 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:
## 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 publicationClawSec 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
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
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
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
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)
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
affectedlists, - 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:
highexploitability: Trivially or easily exploitable with public tooling, immediate action requiredmediumexploitability: Exploitable with specific conditions, standard prioritylowexploitability: 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.
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;
ClawSec Advisory Guardian Hook
This hook checks the ClawSec advisory feed against locally installed skills on:
agent:bootstrapcommand: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 siblingchecksums.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.CLAWSEC_VERIFY_CHECKSUM_MANIFEST: set to0only for emergency troubleshooting (default verifies checksums).CLAWSEC_ALLOW_UNSIGNED_FEED: set to1only 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 (default300).
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)
);
}
import crypto from "node:crypto";
import https from "node:https";
import path from "node:path";
import { loadTextFile } from "./local_file_io.mjs";
import { isObject } from "./utils.mjs";
/**
* Allowed domains for feed/signature fetching.
* Only connections to these domains are permitted for security.
*/
const ALLOWED_DOMAINS = [
"clawsec.prompt.security",
"prompt.security",
"raw.githubusercontent.com",
"github.com",
];
/**
* Custom error class for security policy violations.
* These errors should always propagate and never be silently caught.
*/
class SecurityPolicyError extends Error {
constructor(message) {
super(message);
this.name = "SecurityPolicyError";
}
}
/**
* Creates a secure HTTPS agent with TLS 1.2+ enforcement and certificate validation.
* @returns {https.Agent}
*/
function createSecureAgent() {
return new https.Agent({
// Enforce minimum TLS 1.2 (eliminate TLS 1.0, 1.1)
minVersion: "TLSv1.2",
// Ensure certificate validation is enabled (reject unauthorized certificates)
rejectUnauthorized: true,
// Use strong cipher suites
ciphers: "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256",
});
}
/**
* Validates that a URL is from an allowed domain.
* @param {string} url
* @returns {boolean}
*/
function isAllowedDomain(url) {
try {
const parsed = new URL(url);
// Only allow HTTPS protocol
if (parsed.protocol !== "https:") {
return false;
}
const hostname = parsed.hostname.toLowerCase();
// Check if hostname matches any allowed domain
return ALLOWED_DOMAINS.some(
(allowed) =>
hostname === allowed || hostname.endsWith(`.${allowed}`)
);
} catch {
return false;
}
}
/**
* Secure wrapper around fetch with TLS enforcement and domain validation.
* @param {string} url
* @param {RequestInit} [options]
* @returns {Promise<Response>}
* @throws {SecurityPolicyError} If URL is not from an allowed domain
*/
async function secureFetch(url, options = {}) {
// Validate domain before making request
if (!isAllowedDomain(url)) {
throw new SecurityPolicyError(
`Security policy violation: URL domain not allowed. ` +
`Only connections to ${ALLOWED_DOMAINS.join(", ")} are permitted. ` +
`Blocked: ${url}`
);
}
// Use secure HTTPS agent with TLS 1.2+ enforcement
const agent = createSecureAgent();
return globalThis.fetch(url, {
...options,
// Attach secure agent for Node.js fetch
// @ts-ignore - agent is supported in Node.js fetch
agent,
});
}
/**
* @param {string} rawSpecifier
* @returns {{ name: string; versionSpec: string } | null}
*/
export function parseAffectedSpecifier(rawSpecifier) {
const specifier = String(rawSpecifier ?? "").trim();
if (!specifier) return null;
const atIndex = specifier.lastIndexOf("@");
if (atIndex <= 0) {
return { name: specifier, versionSpec: "*" };
}
return {
name: specifier.slice(0, atIndex),
versionSpec: specifier.slice(atIndex + 1),
};
}
/**
* @param {unknown} raw
* @returns {raw is import("./types.ts").FeedPayload}
*/
export function isValidFeedPayload(raw) {
if (!isObject(raw)) return false;
if (typeof raw.version !== "string" || !raw.version.trim()) return false;
if (!Array.isArray(raw.advisories)) return false;
for (const advisory of raw.advisories) {
if (!isObject(advisory)) return false;
if (typeof advisory.id !== "string" || !advisory.id.trim()) return false;
if (typeof advisory.severity !== "string" || !advisory.severity.trim()) return false;
if (!Array.isArray(advisory.affected)) return false;
if (!advisory.affected.every((entry) => typeof entry === "string" && entry.trim())) return false;
}
return true;
}
/**
* @param {string} signatureRaw
* @returns {Buffer | null}
*/
function decodeSignature(signatureRaw) {
const trimmed = String(signatureRaw ?? "").trim();
if (!trimmed) return null;
let encoded = trimmed;
if (trimmed.startsWith("{")) {
try {
const parsed = JSON.parse(trimmed);
if (isObject(parsed) && typeof parsed.signature === "string") {
encoded = parsed.signature;
}
} catch {
return null;
}
}
const normalized = encoded.replace(/\s+/g, "");
if (!normalized) return null;
try {
return Buffer.from(normalized, "base64");
} catch {
return null;
}
}
/**
* @param {string} payloadRaw
* @param {string} signatureRaw
* @param {string} publicKeyPem
* @returns {boolean}
*/
export function verifySignedPayload(payloadRaw, signatureRaw, publicKeyPem) {
const signature = decodeSignature(signatureRaw);
if (!signature) return false;
const keyPem = String(publicKeyPem ?? "").trim();
if (!keyPem) return false;
try {
const publicKey = crypto.createPublicKey(keyPem);
return crypto.verify(null, Buffer.from(payloadRaw, "utf8"), publicKey, signature);
} catch {
return false;
}
}
/**
* @param {string | Buffer} content
* @returns {string}
*/
function sha256Hex(content) {
return crypto.createHash("sha256").update(content).digest("hex");
}
/**
* @param {unknown} value
* @returns {string | null}
*/
function extractSha256Value(value) {
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
return /^[a-f0-9]{64}$/.test(normalized) ? normalized : null;
}
if (isObject(value) && typeof value.sha256 === "string") {
const normalized = value.sha256.trim().toLowerCase();
return /^[a-f0-9]{64}$/.test(normalized) ? normalized : null;
}
return null;
}
/**
* @param {string} manifestRaw
* @returns {{ schemaVersion: string; algorithm: string; files: Record<string, string> }}
*/
function parseChecksumsManifest(manifestRaw) {
let parsed;
try {
parsed = JSON.parse(manifestRaw);
} catch {
throw new Error("Checksum manifest is not valid JSON");
}
if (!isObject(parsed)) {
throw new Error("Checksum manifest must be an object");
}
const algorithmRaw = typeof parsed.algorithm === "string" ? parsed.algorithm.trim().toLowerCase() : "sha256";
if (algorithmRaw !== "sha256") {
throw new Error(`Unsupported checksum manifest algorithm: ${algorithmRaw || "(empty)"}`);
}
// Support legacy manifest formats:
// - New standard: schema_version field
// - skill-release.yml: version field (e.g., "0.0.1")
// - deploy-pages.yml (pre-fix): generated_at field (e.g., "2026-02-08T...")
// - Ultimate fallback: "1"
const schemaVersion = (
typeof parsed.schema_version === "string" ? parsed.schema_version.trim() :
typeof parsed.version === "string" ? parsed.version.trim() :
typeof parsed.generated_at === "string" ? parsed.generated_at.trim() :
"1"
);
if (!schemaVersion) {
throw new Error("Checksum manifest missing schema_version");
}
if (!isObject(parsed.files)) {
throw new Error("Checksum manifest missing files object");
}
const files = /** @type {Record<string, string>} */ ({});
for (const [key, value] of Object.entries(parsed.files)) {
if (!String(key).trim()) continue;
const digest = extractSha256Value(value);
if (!digest) {
throw new Error(`Invalid checksum digest entry for ${key}`);
}
files[key] = digest;
}
if (Object.keys(files).length === 0) {
throw new Error("Checksum manifest has no usable file digests");
}
return {
schemaVersion,
algorithm: algorithmRaw,
files,
};
}
/**
* @param {string} entryName
* @returns {string}
*/
function normalizeChecksumEntryName(entryName) {
return String(entryName ?? "")
.trim()
.replace(/\\/g, "/")
.replace(/^(?:\.\/)+/, "")
.replace(/^\/+/, "");
}
/**
* @param {Record<string, string>} files
* @param {string} entryName
* @returns {{ key: string; digest: string } | null}
*/
function resolveChecksumManifestEntry(files, entryName) {
const normalizedEntry = normalizeChecksumEntryName(entryName);
if (!normalizedEntry) return null;
const directCandidates = [
normalizedEntry,
path.posix.basename(normalizedEntry),
`advisories/${path.posix.basename(normalizedEntry)}`,
].filter((candidate, index, all) => candidate && all.indexOf(candidate) === index);
for (const candidate of directCandidates) {
if (Object.prototype.hasOwnProperty.call(files, candidate)) {
return { key: candidate, digest: files[candidate] };
}
}
const basename = path.posix.basename(normalizedEntry);
if (!basename) return null;
const basenameMatches = Object.entries(files).filter(([key]) => {
const normalizedKey = normalizeChecksumEntryName(key);
return path.posix.basename(normalizedKey) === basename;
});
if (basenameMatches.length > 1) {
throw new Error(
`Checksum manifest entry is ambiguous for ${entryName}; ` +
`multiple manifest keys share basename ${basename}`,
);
}
if (basenameMatches.length === 1) {
const [resolvedKey, digest] = basenameMatches[0];
return { key: resolvedKey, digest };
}
return null;
}
/**
* @param {{ files: Record<string, string> }} manifest
* @param {Record<string, string | Buffer>} expectedEntries
*/
function verifyChecksums(manifest, expectedEntries) {
for (const [entryName, entryContent] of Object.entries(expectedEntries)) {
if (!entryName) continue;
const resolved = resolveChecksumManifestEntry(manifest.files, entryName);
if (!resolved) {
throw new Error(`Checksum manifest missing required entry: ${entryName}`);
}
const actualDigest = sha256Hex(entryContent);
if (actualDigest !== resolved.digest) {
throw new Error(`Checksum mismatch for ${entryName} (manifest key: ${resolved.key})`);
}
}
}
/**
* @param {string} feedUrl
* @returns {string}
*/
export function defaultChecksumsUrl(feedUrl) {
try {
return new URL("checksums.json", feedUrl).toString();
} catch {
const fallbackBase = String(feedUrl ?? "").replace(/\/?[^/]*$/, "");
return `${fallbackBase}/checksums.json`;
}
}
/**
* Safely extracts the basename from a URL or file path.
* @param {string} urlOrPath
* @param {string} fallback
* @returns {string}
*/
function safeBasename(urlOrPath, fallback) {
try {
// Try parsing as URL first
const parsed = new URL(urlOrPath);
const pathname = parsed.pathname;
const lastSlash = pathname.lastIndexOf("/");
if (lastSlash >= 0 && lastSlash < pathname.length - 1) {
return pathname.slice(lastSlash + 1);
}
} catch {
// Not a URL, try as path
const normalized = String(urlOrPath ?? "").trim();
const lastSlash = normalized.lastIndexOf("/");
if (lastSlash >= 0 && lastSlash < normalized.length - 1) {
return normalized.slice(lastSlash + 1);
}
}
return fallback;
}
/**
* @param {Function} fetchFn
* @param {string} targetUrl
* @returns {Promise<string | null>}
*/
async function fetchText(fetchFn, targetUrl) {
const controller = new globalThis.AbortController();
const timeout = globalThis.setTimeout(() => controller.abort(), 10000);
try {
const response = await fetchFn(targetUrl, {
method: "GET",
signal: controller.signal,
headers: { accept: "application/json,text/plain;q=0.9,*/*;q=0.8" },
});
if (!response.ok) return null;
return await response.text();
} catch (error) {
// Re-throw security policy violations - these should never be silently caught
if (error instanceof SecurityPolicyError) {
throw error;
}
// Network errors, timeouts, etc. return null (graceful degradation)
return null;
} finally {
globalThis.clearTimeout(timeout);
}
}
/**
* @param {string} feedPath
* @param {{
* signaturePath?: string;
* checksumsPath?: string;
* checksumsSignaturePath?: string;
* publicKeyPem?: string;
* checksumsPublicKeyPem?: string;
* allowUnsigned?: boolean;
* verifyChecksumManifest?: boolean;
* checksumFeedEntry?: string;
* checksumSignatureEntry?: string;
* checksumPublicKeyEntry?: string;
* }} [options]
* @returns {Promise<import("./types.ts").FeedPayload>}
*/
export async function loadLocalFeed(feedPath, options = {}) {
const signaturePath = options.signaturePath ?? `${feedPath}.sig`;
const checksumsPath = options.checksumsPath ?? path.join(path.dirname(feedPath), "checksums.json");
const checksumsSignaturePath = options.checksumsSignaturePath ?? `${checksumsPath}.sig`;
const publicKeyPem = String(options.publicKeyPem ?? "");
const checksumsPublicKeyPem = String(options.checksumsPublicKeyPem ?? publicKeyPem);
const allowUnsigned = options.allowUnsigned === true;
const verifyChecksumManifest = options.verifyChecksumManifest !== false;
const payloadRaw = await loadTextFile(feedPath);
if (!allowUnsigned) {
const signatureRaw = await loadTextFile(signaturePath);
if (!verifySignedPayload(payloadRaw, signatureRaw, publicKeyPem)) {
throw new Error(`Feed signature verification failed for local feed: ${feedPath}`);
}
if (verifyChecksumManifest) {
const checksumsRaw = await loadTextFile(checksumsPath);
const checksumsSignatureRaw = await loadTextFile(checksumsSignaturePath);
if (!verifySignedPayload(checksumsRaw, checksumsSignatureRaw, checksumsPublicKeyPem)) {
throw new Error(`Checksum manifest signature verification failed: ${checksumsPath}`);
}
const checksumsManifest = parseChecksumsManifest(checksumsRaw);
const checksumFeedEntry = options.checksumFeedEntry ?? path.basename(feedPath);
const checksumSignatureEntry = options.checksumSignatureEntry ?? path.basename(signaturePath);
const expectedEntries = /** @type {Record<string, string>} */ ({
[checksumFeedEntry]: payloadRaw,
[checksumSignatureEntry]: signatureRaw,
});
if (options.checksumPublicKeyEntry) {
expectedEntries[options.checksumPublicKeyEntry] = publicKeyPem;
}
verifyChecksums(checksumsManifest, expectedEntries);
}
}
const payload = JSON.parse(payloadRaw);
if (!isValidFeedPayload(payload)) {
throw new Error(`Invalid advisory feed format: ${feedPath}`);
}
return payload;
}
/**
* @param {string} feedUrl
* @param {{
* signatureUrl?: string;
* checksumsUrl?: string;
* checksumsSignatureUrl?: string;
* publicKeyPem?: string;
* checksumsPublicKeyPem?: string;
* allowUnsigned?: boolean;
* verifyChecksumManifest?: boolean;
* checksumFeedEntry?: string;
* checksumSignatureEntry?: string;
* }} [options]
* @returns {Promise<import("./types.ts").FeedPayload | null>}
*/
export async function loadRemoteFeed(feedUrl, options = {}) {
// Use secure fetch with TLS 1.2+ enforcement and domain validation
const fetchFn = secureFetch;
if (typeof fetchFn !== "function") return null;
const signatureUrl = options.signatureUrl ?? `${feedUrl}.sig`;
const checksumsUrl = options.checksumsUrl ?? defaultChecksumsUrl(feedUrl);
const checksumsSignatureUrl = options.checksumsSignatureUrl ?? `${checksumsUrl}.sig`;
const publicKeyPem = String(options.publicKeyPem ?? "");
const checksumsPublicKeyPem = String(options.checksumsPublicKeyPem ?? publicKeyPem);
const allowUnsigned = options.allowUnsigned === true;
const verifyChecksumManifest = options.verifyChecksumManifest !== false;
try {
const payloadRaw = await fetchText(fetchFn, feedUrl);
if (!payloadRaw) return null;
if (!allowUnsigned) {
const signatureRaw = await fetchText(fetchFn, signatureUrl);
if (!signatureRaw) return null;
if (!verifySignedPayload(payloadRaw, signatureRaw, publicKeyPem)) {
return null;
}
// Only verify checksums if explicitly requested AND both checksum files are available.
// Note: Many upstream workflows (e.g., GitHub raw content) don't publish checksums.json,
// so we gracefully skip verification when these files are missing.
if (verifyChecksumManifest) {
const checksumsRaw = await fetchText(fetchFn, checksumsUrl);
const checksumsSignatureRaw = await fetchText(fetchFn, checksumsSignatureUrl);
// Only proceed if BOTH checksum files are present
if (checksumsRaw && checksumsSignatureRaw) {
if (!verifySignedPayload(checksumsRaw, checksumsSignatureRaw, checksumsPublicKeyPem)) {
return null; // Fail-closed: invalid signature
}
const checksumsManifest = parseChecksumsManifest(checksumsRaw);
// Derive checksum entry names from actual URLs (supports any filename, not just feed.json)
const checksumFeedEntry = options.checksumFeedEntry ?? safeBasename(feedUrl, "feed.json");
const checksumSignatureEntry = options.checksumSignatureEntry ?? safeBasename(signatureUrl, "feed.json.sig");
verifyChecksums(checksumsManifest, {
[checksumFeedEntry]: payloadRaw,
[checksumSignatureEntry]: signatureRaw,
});
}
// If checksum files missing: continue without checksum verification
// (feed signature was already verified above at line 328)
}
}
try {
const payload = JSON.parse(payloadRaw);
if (!isValidFeedPayload(payload)) return null;
return payload;
} catch {
return null;
}
} catch (error) {
// Security policy violations (invalid URLs, non-HTTPS, disallowed domains) return null
// to allow graceful fallback to local feed
if (error instanceof SecurityPolicyError) {
return null;
}
// Re-throw unexpected errors
throw error;
}
}
import fs from "node:fs/promises";
export async function loadTextFile(filePath) {
return await fs.readFile(filePath, "utf8");
}
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");
}
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;
}
}
}
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,
);
}
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>;
};
import os from "node:os";
import path from "node:path";
/**
* @param {unknown} value
* @returns {value is Record<string, unknown>}
*/
export function isObject(value) {
return typeof value === "object" && value !== null;
}
/**
* @param {string} value
* @returns {string}
*/
export function normalizeSkillName(value) {
return String(value ?? "")
.trim()
.toLowerCase();
}
/**
* @param {string[]} values
* @returns {string[]}
*/
export function uniqueStrings(values) {
return Array.from(new Set(values));
}
function detectHomeDirectory(env = process.env) {
if (typeof env.HOME === "string" && env.HOME.trim()) return env.HOME.trim();
if (typeof env.USERPROFILE === "string" && env.USERPROFILE.trim()) return env.USERPROFILE.trim();
if (
typeof env.HOMEDRIVE === "string" &&
env.HOMEDRIVE.trim() &&
typeof env.HOMEPATH === "string" &&
env.HOMEPATH.trim()
) {
return `${env.HOMEDRIVE.trim()}${env.HOMEPATH.trim()}`;
}
return os.homedir();
}
const UNEXPANDED_HOME_TOKEN_PATTERN =
/(?:^|[\\/])(?:\\?\$HOME|\\?\$\{HOME\}|\\?\$USERPROFILE|\\?\$\{USERPROFILE\}|%HOME%|%USERPROFILE%|\$env:HOME|\$env:USERPROFILE)(?:$|[\\/])/i;
/**
* @param {string} value
* @returns {string}
*/
function expandKnownHomeTokens(value) {
const homeDir = detectHomeDirectory(process.env);
if (!homeDir) return value;
let expanded = String(value ?? "");
if (expanded === "~") {
expanded = homeDir;
} else if (expanded.startsWith("~/") || expanded.startsWith("~\\")) {
expanded = path.join(homeDir, expanded.slice(2));
}
expanded = expanded
.replace(/(?<!\\)\$\{HOME\}/g, homeDir)
.replace(/(?<!\\)\$HOME(?=$|[\\/])/g, homeDir)
.replace(/(?<!\\)\$\{USERPROFILE\}/gi, homeDir)
.replace(/(?<!\\)\$USERPROFILE(?=$|[\\/])/gi, homeDir)
.replace(/%HOME%/gi, homeDir)
.replace(/%USERPROFILE%/gi, homeDir)
.replace(/(?<!\\)\$env:HOME/gi, homeDir)
.replace(/(?<!\\)\$env:USERPROFILE/gi, homeDir);
return expanded;
}
/**
* @param {string} value
* @returns {boolean}
*/
export function hasUnexpandedHomeToken(value) {
return UNEXPANDED_HOME_TOKEN_PATTERN.test(String(value ?? "").trim());
}
/**
* Expand `~` and known home env var patterns in user-provided path-like strings.
* Also fails fast when unresolved home tokens remain.
*
* @param {string} inputPath
* @param {{label?: string}} [options]
* @returns {string}
*/
export function resolveUserPath(inputPath, { label = "path" } = {}) {
const raw = String(inputPath ?? "").trim();
if (!raw) return raw;
const expanded = expandKnownHomeTokens(raw);
const normalized = path.normalize(expanded);
if (hasUnexpandedHomeToken(normalized)) {
throw new Error(
`Unexpanded home token detected in ${label}: ${raw}. ` +
"Use an absolute path or an unquoted home-path expression.",
);
}
return normalized;
}
/**
* Resolve an optional explicit path; if invalid, fall back to a default path.
*
* @param {string | undefined} explicitPath
* @param {string} fallbackPath
* @param {{label?: string, onInvalid?: (error: unknown, rawValue: string) => void}} [options]
* @returns {string}
*/
export function resolveConfiguredPath(
explicitPath,
fallbackPath,
{ label = "path", onInvalid } = {},
) {
const explicit = typeof explicitPath === "string" ? explicitPath.trim() : "";
if (!explicit) {
return resolveUserPath(fallbackPath, { label });
}
try {
return resolveUserPath(explicit, { label });
} catch (error) {
if (typeof onInvalid === "function") {
onInvalid(error, explicit);
}
return resolveUserPath(fallbackPath, { label });
}
}
/**
* @param {string} version
* @returns {[number, number, number] | null}
*/
export function parseSemver(version) {
const cleaned = String(version ?? "")
.trim()
.replace(/^v/i, "")
.split("-")[0];
const parts = cleaned.split(".");
if (parts.length === 0) return null;
const normalized = parts.slice(0, 3).map((part) => Number.parseInt(part, 10));
while (normalized.length < 3) {
normalized.push(0);
}
if (normalized.some((part) => Number.isNaN(part))) {
return null;
}
return /** @type {[number, number, number]} */ (normalized);
}
/**
* @param {string} left
* @param {string} right
* @returns {number | null}
*/
export function compareSemver(left, right) {
const a = parseSemver(left);
const b = parseSemver(right);
if (!a || !b) return null;
for (let index = 0; index < 3; index += 1) {
if (a[index] > b[index]) return 1;
if (a[index] < b[index]) return -1;
}
return 0;
}
/**
* @param {string} value
* @returns {string}
*/
export function escapeRegex(value) {
return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* @param {string | null} version
* @param {string} rawSpec
* @returns {boolean}
*/
export function versionMatches(version, rawSpec) {
const spec = String(rawSpec ?? "").trim();
if (!spec || spec === "*" || spec.toLowerCase() === "any") return true;
if (!version || String(version).trim().toLowerCase() === "unknown") return false;
const normalizedVersion = String(version).trim().replace(/^v/i, "");
if (spec.includes("*")) {
const regex = new RegExp(`^${escapeRegex(spec).replace(/\\\*/g, ".*")}$`);
return regex.test(normalizedVersion);
}
const comparatorMatch = spec.match(/^(>=|<=|>|<|=)\s*(.+)$/);
if (comparatorMatch) {
const operator = comparatorMatch[1];
const targetVersion = comparatorMatch[2].trim();
const compared = compareSemver(normalizedVersion, targetVersion);
if (compared === null) return false;
if (operator === ">=") return compared >= 0;
if (operator === "<=") return compared <= 0;
if (operator === ">") return compared > 0;
if (operator === "<") return compared < 0;
return compared === 0;
}
if (spec.startsWith("^")) {
const target = parseSemver(spec.slice(1));
const current = parseSemver(normalizedVersion);
if (!target || !current) return false;
if (current[0] !== target[0]) return false;
if (target[0] === 0 && current[1] !== target[1]) return false;
return compareSemver(normalizedVersion, spec.slice(1)) !== -1;
}
if (spec.startsWith("~")) {
const target = parseSemver(spec.slice(1));
const current = parseSemver(normalizedVersion);
if (!target || !current) return false;
return (
current[0] === target[0] &&
current[1] === target[1] &&
compareSemver(normalizedVersion, spec.slice(1)) !== -1
);
}
return normalizedVersion === spec || normalizedVersion === spec.replace(/^v/i, "");
}
Clawsec Suite
ClawSec suite manager with embedded advisory-feed monitoring, cryptographic signature verification, approval-gated malicious-skill response, and guided setup for additional security skills.
Vercel Skills Installation
Install with the Vercel Skills CLI for this harness:
npx skills add prompt-security/clawsec --skill clawsec-suite -a openclaw -y#!/usr/bin/env node
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadTextFile } from "./local_file_io.mjs";
const DEFAULT_INDEX_URL = "https://clawsec.prompt.security/skills/index.json";
const DEFAULT_TIMEOUT_MS = 5000;
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
const SUITE_DIR = path.resolve(SCRIPT_DIR, "..");
const SUITE_SKILL_JSON = path.join(SUITE_DIR, "skill.json");
function isObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function normalizeSkillId(value) {
return String(value ?? "")
.trim()
.toLowerCase();
}
function normalizeBoolean(value) {
return value === true;
}
const ENVIRONMENT = (() => {
const runtimeProcess = Reflect.get(globalThis, "process");
if (!runtimeProcess || typeof runtimeProcess !== "object") return {};
if (!("env" in runtimeProcess)) return {};
const env = runtimeProcess.env;
return env && typeof env === "object" ? env : {};
})();
function envVar(name) {
const value = ENVIRONMENT[name];
return typeof value === "string" ? value.trim() : "";
}
function parseTimeoutMs() {
const raw = envVar("CLAWSEC_SKILLS_INDEX_TIMEOUT_MS");
if (!raw) return DEFAULT_TIMEOUT_MS;
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
return DEFAULT_TIMEOUT_MS;
}
return parsed;
}
function parseArgs(argv) {
const args = {
json: false,
};
for (const token of argv) {
if (token === "--json") {
args.json = true;
continue;
}
if (token === "--help" || token === "-h") {
printUsage();
process.exit(0);
}
throw new Error(`Unknown argument: ${token}`);
}
return args;
}
function printUsage() {
process.stdout.write(
[
"Usage:",
" node scripts/discover_skill_catalog.mjs [--json]",
"",
"Behavior:",
" - Fetches dynamic catalog from CLAWSEC_SKILLS_INDEX_URL (default: https://clawsec.prompt.security/skills/index.json)",
" - Falls back to suite-local catalog metadata in skill.json when remote index is unavailable/invalid",
"",
"Environment:",
" CLAWSEC_SKILLS_INDEX_URL Override remote catalog index URL",
" CLAWSEC_SKILLS_INDEX_TIMEOUT_MS HTTP timeout in milliseconds (default: 5000)",
"",
].join("\n"),
);
}
function normalizeRemoteSkills(payload) {
if (!isObject(payload)) {
throw new Error("Catalog index payload must be a JSON object");
}
const rawSkills = payload.skills;
if (!Array.isArray(rawSkills)) {
throw new Error("Catalog index missing skills array");
}
const dedup = new Map();
for (const entry of rawSkills) {
if (!isObject(entry)) continue;
const id = normalizeSkillId(entry.id ?? entry.name);
if (!id) continue;
dedup.set(id, {
id,
name: String(entry.name ?? id),
version: String(entry.version ?? "").trim() || null,
description: String(entry.description ?? "").trim() || null,
emoji: String(entry.emoji ?? "").trim() || null,
category: String(entry.category ?? "").trim() || null,
tag: String(entry.tag ?? "").trim() || null,
trust: entry.trust ?? null,
source: "remote",
});
}
return {
version: String(payload.version ?? "").trim() || null,
updated: String(payload.updated ?? "").trim() || null,
skills: [...dedup.values()].sort((a, b) => a.id.localeCompare(b.id)),
};
}
async function loadFallbackCatalog() {
const raw = await loadTextFile(SUITE_SKILL_JSON);
const parsed = JSON.parse(raw);
const catalogSkills = isObject(parsed?.catalog?.skills) ? parsed.catalog.skills : {};
const dedup = new Map();
for (const [rawId, meta] of Object.entries(catalogSkills)) {
const id = normalizeSkillId(rawId);
if (!id) continue;
const safeMeta = isObject(meta) ? meta : {};
dedup.set(id, {
id,
name: id,
version: null,
description: String(safeMeta.description ?? "").trim() || null,
emoji: null,
category: null,
tag: null,
trust: null,
source: "fallback",
integrated_in_suite: normalizeBoolean(safeMeta.integrated_in_suite),
requires_explicit_consent: normalizeBoolean(safeMeta.requires_explicit_consent),
default_install: normalizeBoolean(safeMeta.default_install),
});
}
return {
version: null,
updated: null,
skills: [...dedup.values()].sort((a, b) => a.id.localeCompare(b.id)),
};
}
function mergeWithFallbackMetadata(remoteSkills, fallbackSkills) {
const fallbackById = new Map(fallbackSkills.map((skill) => [skill.id, skill]));
return remoteSkills.map((skill) => {
const fallback = fallbackById.get(skill.id);
if (!fallback) {
return {
...skill,
integrated_in_suite: false,
requires_explicit_consent: false,
default_install: false,
};
}
return {
...skill,
description: skill.description || fallback.description || null,
integrated_in_suite: normalizeBoolean(fallback.integrated_in_suite),
requires_explicit_consent: normalizeBoolean(fallback.requires_explicit_consent),
default_install: normalizeBoolean(fallback.default_install),
};
});
}
async function loadRemoteCatalog(indexUrl, timeoutMs) {
if (typeof globalThis.fetch !== "function") {
throw new Error("fetch is unavailable in this runtime");
}
if (typeof globalThis.AbortController !== "function") {
throw new Error("AbortController is unavailable in this runtime");
}
const controller = new globalThis.AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await globalThis.fetch(indexUrl, {
method: "GET",
headers: { Accept: "application/json" },
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status} while fetching catalog`);
}
const payload = await response.json();
return normalizeRemoteSkills(payload);
} finally {
clearTimeout(timeout);
}
}
function formatFlags(skill) {
const flags = [];
if (skill.id === "clawsec-suite") {
flags.push("this suite");
}
if (skill.integrated_in_suite) {
flags.push("already integrated in suite");
}
if (skill.requires_explicit_consent) {
flags.push("explicit opt-in");
}
if (skill.default_install) {
flags.push("recommended default");
}
return flags;
}
function printHumanSummary(result) {
process.stdout.write("=== ClawSec Skill Catalog Discovery ===\n");
process.stdout.write(`Source: ${result.source}\n`);
process.stdout.write(`Index URL: ${result.index_url}\n`);
if (result.updated) {
process.stdout.write(`Catalog updated: ${result.updated}\n`);
}
if (result.warning) {
process.stdout.write(`Fallback reason: ${result.warning}\n`);
}
process.stdout.write("\nAvailable installable skills:\n");
if (!Array.isArray(result.skills) || result.skills.length === 0) {
process.stdout.write("- none\n");
return;
}
for (const skill of result.skills) {
const label = skill.version ? `${skill.id} (v${skill.version})` : skill.id;
process.stdout.write(`- ${label}\n`);
if (skill.description) {
process.stdout.write(` ${skill.description}\n`);
}
const flags = formatFlags(skill);
if (flags.length > 0) {
process.stdout.write(` notes: ${flags.join("; ")}\n`);
}
process.stdout.write(` install: npx clawhub@latest install ${skill.id}\n`);
}
}
async function discoverCatalog() {
const indexUrl = envVar("CLAWSEC_SKILLS_INDEX_URL") || DEFAULT_INDEX_URL;
const timeoutMs = parseTimeoutMs();
const fallback = await loadFallbackCatalog();
try {
const remote = await loadRemoteCatalog(indexUrl, timeoutMs);
return {
source: "remote",
index_url: indexUrl,
version: remote.version,
updated: remote.updated,
skills: mergeWithFallbackMetadata(remote.skills, fallback.skills),
warning: null,
};
} catch (error) {
return {
source: "fallback",
index_url: indexUrl,
version: fallback.version,
updated: fallback.updated,
skills: fallback.skills,
warning: String(error),
};
}
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const result = await discoverCatalog();
if (args.json) {
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
return;
}
printHumanSummary(result);
}
main().catch((error) => {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
});
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
const DEFAULT_FILES = ["feed-signing-public.pem", "feed.json", "feed.json.sig"];
function usage() {
process.stderr.write(
[
"Usage:",
" node scripts/generate_checksums_json.mjs --out advisories/checksums.json [--base advisories] [--file feed.json --file feed.json.sig ...]",
"",
"Defaults:",
" --base <dirname(--out)>",
` --file ${DEFAULT_FILES.join(" --file ")}`,
"",
].join("\n"),
);
}
function parseArgs(argv) {
const parsed = { files: [] };
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === "--out") {
parsed.outPath = argv[++i];
} else if (token === "--base") {
parsed.baseDir = argv[++i];
} else if (token === "--file") {
parsed.files.push(argv[++i]);
} else if (token === "-h" || token === "--help") {
parsed.help = true;
} else {
throw new Error(`Unknown argument: ${token}`);
}
}
return parsed;
}
function sha256Hex(buffer) {
return crypto.createHash("sha256").update(buffer).digest("hex");
}
async function main() {
const { outPath, baseDir, files, help } = parseArgs(process.argv.slice(2));
if (help) {
usage();
process.exit(0);
}
if (!outPath) {
usage();
throw new Error("Missing required argument: --out");
}
const resolvedBase = path.resolve(baseDir ?? path.dirname(outPath));
const fileList = files.length > 0 ? files : DEFAULT_FILES;
const checksums = {};
for (const relativePath of [...fileList].sort((a, b) => a.localeCompare(b))) {
const absolutePath = path.resolve(resolvedBase, relativePath);
const content = await fs.readFile(absolutePath);
checksums[relativePath] = sha256Hex(content);
}
const payload = {
schema_version: "1.0",
algorithm: "sha256",
files: checksums,
};
await fs.writeFile(`${outPath}`, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
process.stdout.write(`Wrote ${outPath}\n`);
}
main().catch((error) => {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
});
#!/usr/bin/env node
import { spawnSync as runProcessSync } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { normalizeSkillName, uniqueStrings, resolveUserPath } from "../hooks/clawsec-advisory-guardian/lib/utils.mjs";
import { versionMatches } from "../hooks/clawsec-advisory-guardian/lib/version.mjs";
import {
defaultChecksumsUrl,
parseAffectedSpecifier,
loadLocalFeed,
loadRemoteFeed,
} from "../hooks/clawsec-advisory-guardian/lib/feed.mjs";
const DEFAULT_FEED_URL =
"https://clawsec.prompt.security/advisories/feed.json";
const DEFAULT_SUITE_DIR = path.join(os.homedir(), ".openclaw", "skills", "clawsec-suite");
const DEFAULT_LOCAL_FEED = path.join(DEFAULT_SUITE_DIR, "advisories", "feed.json");
const DEFAULT_LOCAL_FEED_SIG = `${DEFAULT_LOCAL_FEED}.sig`;
const DEFAULT_LOCAL_FEED_CHECKSUMS = path.join(DEFAULT_SUITE_DIR, "advisories", "checksums.json");
const DEFAULT_LOCAL_FEED_CHECKSUMS_SIG = `${DEFAULT_LOCAL_FEED_CHECKSUMS}.sig`;
const DEFAULT_FEED_PUBLIC_KEY = path.join(DEFAULT_SUITE_DIR, "advisories", "feed-signing-public.pem");
const EXIT_CONFIRM_REQUIRED = 42;
function envPathOrDefault(name, fallback, label) {
const envValue = process.env[name];
const candidate = typeof envValue === "string" && envValue.trim() ? envValue.trim() : fallback;
return resolveUserPath(candidate, { label });
}
function printUsage() {
process.stderr.write(
[
"Usage:",
" node scripts/guarded_skill_install.mjs --skill <skill-name> [--version <version>] [--confirm-advisory] [--dry-run]",
"",
"Examples:",
" node scripts/guarded_skill_install.mjs --skill helper-plus --version 1.0.1",
" node scripts/guarded_skill_install.mjs --skill helper-plus --version 1.0.1 --confirm-advisory",
"",
"Exit codes:",
" 0 success / no advisory block",
" 42 advisory matched and second confirmation is required",
" 1 error",
"",
].join("\n"),
);
}
function parseArgs(argv) {
const parsed = {
skill: "",
version: "",
confirmAdvisory: false,
dryRun: false,
};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === "--skill") {
parsed.skill = String(argv[i + 1] ?? "").trim();
i += 1;
continue;
}
if (token === "--version") {
parsed.version = String(argv[i + 1] ?? "").trim();
i += 1;
continue;
}
if (token === "--confirm-advisory") {
parsed.confirmAdvisory = true;
continue;
}
if (token === "--dry-run") {
parsed.dryRun = true;
continue;
}
if (token === "--help" || token === "-h") {
printUsage();
process.exit(0);
}
throw new Error(`Unknown argument: ${token}`);
}
if (!parsed.skill) {
throw new Error("Missing required argument: --skill");
}
if (!/^[a-z0-9-]+$/.test(parsed.skill)) {
throw new Error("Invalid --skill value. Use lowercase letters, digits, and hyphens only.");
}
return parsed;
}
function affectedSpecifierMatches(specifier, skillName, version) {
const parsed = parseAffectedSpecifier(specifier);
if (!parsed) return false;
if (normalizeSkillName(parsed.name) !== normalizeSkillName(skillName)) return false;
return versionMatches(version, parsed.versionSpec);
}
function affectedSpecifierMatchesWithoutVersion(specifier, skillName) {
const parsed = parseAffectedSpecifier(specifier);
if (!parsed) return false;
return normalizeSkillName(parsed.name) === normalizeSkillName(skillName);
}
function advisoryLooksHighRisk(advisory) {
const type = String(advisory.type ?? "").toLowerCase();
const severity = String(advisory.severity ?? "").toLowerCase();
const combined = `${advisory.title ?? ""} ${advisory.description ?? ""} ${advisory.action ?? ""}`.toLowerCase();
if (type === "malicious_skill" || type === "malicious_plugin") return true;
if (/\b(malicious|exfiltrate|exfiltration|backdoor|trojan|stealer|credential theft)\b/.test(combined)) return true;
if (/\b(remove|uninstall|disable|do not use|quarantine)\b/.test(combined)) return true;
if (severity === "critical") return true;
return false;
}
async function loadFeed() {
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 localFeedPath = envPathOrDefault("CLAWSEC_LOCAL_FEED", DEFAULT_LOCAL_FEED, "CLAWSEC_LOCAL_FEED");
const localFeedSigPath = envPathOrDefault("CLAWSEC_LOCAL_FEED_SIG", DEFAULT_LOCAL_FEED_SIG, "CLAWSEC_LOCAL_FEED_SIG");
const localFeedChecksumsPath = envPathOrDefault(
"CLAWSEC_LOCAL_FEED_CHECKSUMS",
DEFAULT_LOCAL_FEED_CHECKSUMS,
"CLAWSEC_LOCAL_FEED_CHECKSUMS",
);
const localFeedChecksumsSigPath = envPathOrDefault(
"CLAWSEC_LOCAL_FEED_CHECKSUMS_SIG",
DEFAULT_LOCAL_FEED_CHECKSUMS_SIG,
"CLAWSEC_LOCAL_FEED_CHECKSUMS_SIG",
);
const feedPublicKeyPath = envPathOrDefault("CLAWSEC_FEED_PUBLIC_KEY", DEFAULT_FEED_PUBLIC_KEY, "CLAWSEC_FEED_PUBLIC_KEY");
const allowUnsigned = process.env.CLAWSEC_ALLOW_UNSIGNED_FEED === "1";
const verifyChecksumManifest = process.env.CLAWSEC_VERIFY_CHECKSUM_MANIFEST !== "0";
if (allowUnsigned) {
process.stderr.write(
"WARNING: CLAWSEC_ALLOW_UNSIGNED_FEED=1 is enabled. This temporary migration compatibility bypass should be removed once signed feed artifacts are available.\n",
);
}
const publicKeyPem = allowUnsigned ? "" : await fs.readFile(feedPublicKeyPath, "utf8");
const remoteFeed = await loadRemoteFeed(feedUrl, {
signatureUrl: feedSignatureUrl,
checksumsUrl: feedChecksumsUrl,
checksumsSignatureUrl: feedChecksumsSignatureUrl,
publicKeyPem,
checksumsPublicKeyPem: publicKeyPem,
allowUnsigned,
verifyChecksumManifest,
});
if (remoteFeed) return { feed: remoteFeed, source: `remote:${feedUrl}` };
const localFeed = await loadLocalFeed(localFeedPath, {
signaturePath: localFeedSigPath,
checksumsPath: localFeedChecksumsPath,
checksumsSignaturePath: localFeedChecksumsSigPath,
publicKeyPem,
checksumsPublicKeyPem: publicKeyPem,
allowUnsigned,
verifyChecksumManifest,
checksumPublicKeyEntry: path.basename(feedPublicKeyPath),
});
return { feed: localFeed, source: `local:${localFeedPath}` };
}
function findMatches(feed, skillName, version) {
const advisories = Array.isArray(feed.advisories) ? feed.advisories : [];
const matches = [];
for (const advisory of advisories) {
const affected = Array.isArray(advisory.affected) ? advisory.affected : [];
if (affected.length === 0) continue;
const matchedAffected = uniqueStrings(
affected.filter((specifier) =>
version
? affectedSpecifierMatches(specifier, skillName, version)
: affectedSpecifierMatchesWithoutVersion(specifier, skillName),
),
);
if (matchedAffected.length > 0) {
matches.push({ advisory, matchedAffected });
}
}
return matches;
}
function printMatches(matches, skillName, version) {
process.stdout.write("Advisory matches detected for requested install target.\n");
process.stdout.write(`Target: ${skillName}${version ? `@${version}` : ""}\n`);
for (const entry of matches) {
const advisory = entry.advisory;
const severity = String(advisory.severity ?? "unknown").toUpperCase();
const advisoryId = advisory.id ?? "unknown-id";
const title = advisory.title ?? "Untitled advisory";
process.stdout.write(`- [${severity}] ${advisoryId}: ${title}\n`);
process.stdout.write(` matched: ${entry.matchedAffected.join(", ")}\n`);
if (advisory.action) {
process.stdout.write(` action: ${advisory.action}\n`);
}
}
}
function runInstall(skillName, version) {
const target = version ? `${skillName}@${version}` : skillName;
process.stdout.write(`Install target: ${target}\n`);
const result = runProcessSync("npx", ["clawhub@latest", "install", target], {
stdio: "inherit",
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const { feed, source } = await loadFeed();
const matches = findMatches(feed, args.skill, args.version);
const highRisk = matches.some((entry) => advisoryLooksHighRisk(entry.advisory));
process.stdout.write(`Advisory source: ${source}\n`);
if (!args.version) {
process.stdout.write(
"No --version provided. Conservatively matching any advisory for the requested skill name.\n",
);
}
if (matches.length > 0) {
printMatches(matches, args.skill, args.version);
process.stdout.write("\n");
process.stdout.write("Install request recognized as first confirmation.\n");
process.stdout.write("Additional explicit confirmation is required with advisory context.\n");
if (!args.confirmAdvisory) {
process.stdout.write(
"Re-run with --confirm-advisory to proceed after the user explicitly confirms.\n",
);
process.exit(EXIT_CONFIRM_REQUIRED);
}
process.stdout.write("Second confirmation provided via --confirm-advisory.\n");
}
if (args.dryRun) {
process.stdout.write("Dry run only; install command was not executed.\n");
return;
}
if (highRisk) {
process.stdout.write(
"High-risk advisory context acknowledged. Proceeding only because --confirm-advisory was provided.\n",
);
}
runInstall(args.skill, args.version);
}
main().catch((error) => {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
});
import fs from "node:fs/promises";
export async function loadTextFile(filePath) {
return await fs.readFile(filePath, "utf8");
}
#!/usr/bin/env node
import { spawnSync as runProcessSync } from "node:child_process";
const JOB_NAME = process.env.CLAWSEC_ADVISORY_CRON_NAME?.trim() || "ClawSec Advisory Scan";
const JOB_EVERY = process.env.CLAWSEC_ADVISORY_CRON_EVERY?.trim() || "6h";
const JOB_DESCRIPTION =
"Trigger a periodic ClawSec advisory scan in the main session and ask for approval before removing flagged skills.";
const SYSTEM_EVENT =
"Run ClawSec advisory scan. If installed skills are flagged as malicious or removal is recommended, notify the user and request explicit approval before any removal.";
function sh(cmd, args) {
const result = runProcessSync(cmd, args, {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const details = (result.stderr || result.stdout || "").trim();
throw new Error(`${cmd} ${args.join(" ")} failed${details ? `: ${details}` : ""}`);
}
return result.stdout;
}
function requireOpenClawCli() {
try {
sh("openclaw", ["--version"]);
} catch (error) {
throw new Error(
"openclaw CLI is required. Install OpenClaw and ensure `openclaw` is available in PATH. " +
`Original error: ${String(error)}`,
{ cause: error },
);
}
}
function findExistingJobId(jobsPayload) {
if (!jobsPayload || !Array.isArray(jobsPayload.jobs)) return null;
const existing = jobsPayload.jobs.find((job) => job && job.name === JOB_NAME);
return existing?.id ?? null;
}
function addJob() {
const out = sh("openclaw", [
"cron",
"add",
"--name",
JOB_NAME,
"--description",
JOB_DESCRIPTION,
"--every",
JOB_EVERY,
"--session",
"main",
"--system-event",
SYSTEM_EVENT,
"--wake",
"now",
"--json",
]);
try {
const payload = JSON.parse(out);
return payload?.id ?? null;
} catch {
return null;
}
}
function editJob(jobId) {
sh("openclaw", [
"cron",
"edit",
jobId,
"--name",
JOB_NAME,
"--description",
JOB_DESCRIPTION,
"--enable",
"--every",
JOB_EVERY,
"--session",
"main",
"--system-event",
SYSTEM_EVENT,
"--wake",
"now",
]);
}
function printPreflightSummary() {
const lines = [
"Preflight review:",
"- This setup creates or updates an unattended openclaw cron job in the main session.",
"- Required runtime: openclaw CLI, node.",
`- Schedule: every ${JOB_EVERY}`,
"- The system event triggers an advisory scan and must request explicit approval before any removal.",
];
process.stdout.write(lines.join("\n") + "\n\n");
}
function main() {
requireOpenClawCli();
printPreflightSummary();
const jobsOut = sh("openclaw", ["cron", "list", "--json"]);
const jobsPayload = JSON.parse(jobsOut);
const existingJobId = findExistingJobId(jobsPayload);
if (existingJobId) {
editJob(existingJobId);
process.stdout.write(`Updated cron job ${existingJobId}: ${JOB_NAME}\n`);
} else {
const createdId = addJob();
if (createdId) {
process.stdout.write(`Created cron job ${createdId}: ${JOB_NAME}\n`);
} else {
process.stdout.write(`Created cron job: ${JOB_NAME}\n`);
}
}
process.stdout.write(`Schedule: every ${JOB_EVERY}\n`);
process.stdout.write("Session target: main (system event + wake now)\n");
}
try {
main();
} catch (error) {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
}
#!/usr/bin/env node
import { spawnSync as runProcessSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const HOOK_NAME = "clawsec-advisory-guardian";
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
const SUITE_DIR = path.resolve(SCRIPT_DIR, "..");
const SOURCE_HOOK_DIR = path.join(SUITE_DIR, "hooks", HOOK_NAME);
const HOOKS_ROOT = path.join(os.homedir(), ".openclaw", "hooks");
const TARGET_HOOK_DIR = path.join(HOOKS_ROOT, HOOK_NAME);
function sh(cmd, args) {
const result = runProcessSync(cmd, args, {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const details = (result.stderr || result.stdout || "").trim();
throw new Error(`${cmd} ${args.join(" ")} failed${details ? `: ${details}` : ""}`);
}
return result.stdout;
}
function requireOpenClawCli() {
try {
sh("openclaw", ["--version"]);
} catch (error) {
throw new Error(
"openclaw CLI is required. Install OpenClaw and ensure `openclaw` is available in PATH. " +
`Original error: ${String(error)}`,
{ cause: error },
);
}
}
function assertSourceHookExists() {
const requiredFiles = [
"HOOK.md",
"handler.ts",
"lib/utils.mjs",
"lib/version.mjs",
"lib/feed.mjs",
];
for (const file of requiredFiles) {
const fullPath = path.join(SOURCE_HOOK_DIR, file);
if (!fs.existsSync(fullPath)) {
throw new Error(`Missing required hook file: ${fullPath}`);
}
}
}
function installHookFiles() {
fs.mkdirSync(HOOKS_ROOT, { recursive: true });
fs.rmSync(TARGET_HOOK_DIR, { recursive: true, force: true });
fs.cpSync(SOURCE_HOOK_DIR, TARGET_HOOK_DIR, { recursive: true });
}
function printPreflightSummary() {
const lines = [
"Preflight review:",
`- This setup installs a persistent OpenClaw hook under ${TARGET_HOOK_DIR} and enables it globally.`,
"- Required runtime: openclaw CLI, node.",
"- The installed hook fetches signed advisory feed data and may recommend removal of risky skills, but destructive actions remain approval-gated.",
`- Source hook files: ${SOURCE_HOOK_DIR}`,
"- Restart your OpenClaw gateway process after setup so the hook loads intentionally.",
];
process.stdout.write(lines.join("\n") + "\n\n");
}
function enableHook() {
sh("openclaw", ["hooks", "enable", HOOK_NAME]);
}
function main() {
assertSourceHookExists();
printPreflightSummary();
requireOpenClawCli();
installHookFiles();
enableHook();
process.stdout.write(`Installed hook files to: ${TARGET_HOOK_DIR}\n`);
process.stdout.write(`Enabled hook: ${HOOK_NAME}\n`);
process.stdout.write("Restart your OpenClaw gateway process so the hook is loaded.\n");
process.stdout.write("After restart, run /new once to trigger an immediate advisory scan.\n");
}
try {
main();
} catch (error) {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
}
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs/promises";
function usage() {
process.stderr.write(
[
"Usage:",
" node scripts/sign_detached_ed25519.mjs --key <private-key.pem> --in <file> --out <file.sig>",
"",
"Signs <file> with Ed25519 private key and writes base64 detached signature to <file.sig>.",
"",
].join("\n"),
);
}
function parseArgs(argv) {
const parsed = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === "--key") {
parsed.keyPath = argv[++i];
} else if (token === "--in") {
parsed.inPath = argv[++i];
} else if (token === "--out") {
parsed.outPath = argv[++i];
} else if (token === "-h" || token === "--help") {
parsed.help = true;
} else {
throw new Error(`Unknown argument: ${token}`);
}
}
return parsed;
}
async function main() {
const { keyPath, inPath, outPath, help } = parseArgs(process.argv.slice(2));
if (help) {
usage();
process.exit(0);
}
if (!keyPath || !inPath || !outPath) {
usage();
throw new Error("Missing required arguments: --key, --in, --out");
}
const privateKeyPem = await fs.readFile(keyPath, "utf8");
const privateKey = crypto.createPrivateKey(privateKeyPem);
const data = await fs.readFile(inPath);
const signature = crypto.sign(null, data, privateKey);
const signatureBase64 = signature.toString("base64");
await fs.writeFile(outPath, `${signatureBase64}\n`, "utf8");
process.stdout.write(`Signed ${inPath} -> ${outPath}\n`);
}
main().catch((error) => {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
});
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs/promises";
function usage() {
process.stderr.write(
[
"Usage:",
" node scripts/verify_detached_ed25519.mjs --key <public-key.pem> --in <file> --sig <file.sig>",
"",
"Verifies Ed25519 detached signature against <file>.",
"Exits 0 on success, 1 on verification failure.",
"",
].join("\n"),
);
}
function parseArgs(argv) {
const parsed = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === "--key") {
parsed.keyPath = argv[++i];
} else if (token === "--in") {
parsed.inPath = argv[++i];
} else if (token === "--sig") {
parsed.sigPath = argv[++i];
} else if (token === "-h" || token === "--help") {
parsed.help = true;
} else {
throw new Error(`Unknown argument: ${token}`);
}
}
return parsed;
}
async function main() {
const { keyPath, inPath, sigPath, help } = parseArgs(process.argv.slice(2));
if (help) {
usage();
process.exit(0);
}
if (!keyPath || !inPath || !sigPath) {
usage();
throw new Error("Missing required arguments: --key, --in, --sig");
}
const publicKeyPem = await fs.readFile(keyPath, "utf8");
const publicKey = crypto.createPublicKey(publicKeyPem);
const data = await fs.readFile(inPath);
const signatureRaw = await fs.readFile(sigPath, "utf8");
const signature = Buffer.from(signatureRaw.trim(), "base64");
const valid = crypto.verify(null, data, publicKey, signature);
if (valid) {
process.stdout.write(`Signature valid: ${inPath}\n`);
process.exit(0);
} else {
process.stderr.write(`Signature INVALID: ${inPath}\n`);
process.exit(1);
}
}
main().catch((error) => {
process.stderr.write(`${String(error)}\n`);
process.exit(1);
});
#!/usr/bin/env node
/**
* Advisory application scope tests:
* - openclaw advisories are considered
* - nanoclaw advisories are ignored
* - legacy advisories without application remain eligible
*
* Run: node skills/clawsec-suite/test/advisory_application_scope.test.mjs
*/
import path from "node:path";
import { fileURLToPath } from "node:url";
import { pass, fail, report, exitWithResults } from "./lib/test_harness.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const LIB_PATH = path.resolve(__dirname, "..", "hooks", "clawsec-advisory-guardian", "lib");
const { advisoryAppliesToOpenclaw } = await import(`${LIB_PATH}/advisory_scope.mjs`);
function testFindMatchesFiltersByApplicationScope() {
const testName = "advisoryAppliesToOpenclaw: openclaw + legacy advisories are considered";
const inputs = [
{ id: "ADV-OPENCLAW-001", application: "openclaw", expect: true },
{ id: "ADV-NANOCLAW-001", application: "nanoclaw", expect: false },
{ id: "ADV-LEGACY-001", expect: true },
];
for (const input of inputs) {
const result = advisoryAppliesToOpenclaw({ application: input.application });
if (result !== input.expect) {
fail(testName, `Unexpected result for ${input.id}: expected ${input.expect}, got ${result}`);
return;
}
}
pass(testName);
}
function testApplicationAllAccepted() {
const testName = "advisoryAppliesToOpenclaw: application=all is considered";
const result = advisoryAppliesToOpenclaw({ application: "all" });
if (!result) {
fail(testName, "Expected true for application=all");
return;
}
pass(testName);
}
function testFindMatchesAcceptsApplicationArray() {
const testName = "advisoryAppliesToOpenclaw: application array containing openclaw is considered";
const result = advisoryAppliesToOpenclaw({ application: ["nanoclaw", "openclaw"] });
if (!result) {
fail(testName, "Expected true for application array containing openclaw");
return;
}
pass(testName);
}
function testInvalidApplicationValueFallsBackCompat() {
const testName = "advisoryAppliesToOpenclaw: invalid application values keep legacy compatibility";
const result = advisoryAppliesToOpenclaw({ application: { invalid: true } });
if (!result) {
fail(testName, "Expected true for non-string application to preserve backward compatibility");
return;
}
pass(testName);
}
function runTests() {
console.log("=== ClawSec Advisory Application Scope Tests ===\n");
testFindMatchesFiltersByApplicationScope();
testApplicationAllAccepted();
testFindMatchesAcceptsApplicationArray();
testInvalidApplicationValueFallsBackCompat();
report();
exitWithResults();
}
runTests();
#!/usr/bin/env node
/**
* Property-based fuzzing checks for core advisory parsing/path helpers.
*
* Run: node skills/clawsec-suite/test/fuzz_properties.test.mjs
*/
import { pass, fail, report, exitWithResults } from "./lib/test_harness.mjs";
import { runFuzzProperties } from "./fuzz_properties.js";
console.log("=== ClawSec Fast-Check Fuzz Properties ===\n");
try {
runFuzzProperties();
pass("Property-based fuzz tests");
} catch (error) {
fail("Property-based fuzz tests", error);
}
report();
exitWithResults();
Related skills
How it compares
Pick ClawSec Suite when the workflow centers on OpenClaw/clawhub skill installs and ongoing advisory monitoring rather than one-off static code scans.
FAQ
What does ClawSec Suite install on a developer machine?
ClawSec Suite installs an advisory hook under ~/.openclaw/hooks, can create an unattended openclaw cron job, and may deploy guard skills through npx clawhub@latest install during guided setup.
Which runtimes does ClawSec Suite require?
ClawSec Suite requires node, npx, openclaw, curl, jq, shasum, openssl, and unzip. Setup scripts use those tools for feed fetching, signature checks, and package installation.
Is Clawsec Suite safe to install?
skills.sh reports 1 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.