Skip to content
Back to search

Synapse

Self-hosted AI workspace with shareable AI teammates, shared conversations, memory, and governed access to plugins, MCP tools, and local devices.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/zai-org/Synapse with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/zai-org/Synapse'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/zai-org--synapse/badge.svg)](/listings/zai-org--synapse)

HTML

<a href="/listings/zai-org--synapse"><img src="/api/listings/zai-org--synapse/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Local web + API

Prerequisites:

- Node.js 22 (the version used in CI) - Docker and Docker Compose

Clone the repo and start the core local stack:

git clone --recurse-submodules https://github.com/zai-org/Synapse
cd Synapse

npm ci
./setup.sh
docker compose up -d postgres redis

# Create the current schema
npm run db:bootstrap

# Start the API and desktop web in separate terminals
npm run dev:api
npm run dev:web

Submodules are only needed for the device CLI catalog and connector extras — after a plain clone, `git submodule update --init` fetches them.

Open:

- Desktop web: `http://localhost:3000` - API health: `http://localhost:3001/api/v1/health`

If your local Docker setup requires elevated privileges, run the `docker compose` command with `sudo`.

Before using actor or chat flows with real models, configure at least one platform model group: copy `packages/api/config/model-groups.yaml.example` to `packages/api/config/model-groups.yaml`, fill in the referenced `${ENV}` variables (e.g. `ANTHROPIC_API_KEY`) in `.env`, then apply it with `npm run db:rebuild` (which imports it automatically) or `npm run db:seed:model-groups`.

Optional: reset and seed a demo environment

If you want a fully seeded local environment with demo users, a demo workspace, official actors, and built-in plugin catalog entries:

npm run db:rebuild

Seeded demo accounts:

- `demo@synapse.dev` / `demo1234` - `yihang@synapse.dev` / `demo1234`

Optional: run the Expo mobile app

The mobile client lives in its own package with its own lockfile:

cd packages/mobile-app
npm ci
npm run web

You can also use `npm run ios` or `npm run android` inside `packages/mobile-app`.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 269 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <picture>
  3. <source media="(prefers-color-scheme: light)" srcset="docs/assets/synapse-full-logo.svg">
  4. <img src="docs/assets/synapse-full-logo-dark.svg" alt="Synapse" width="500">
  5. </picture>
  6. </p>
  7. <p align="center">
  8. <strong>Build AI teams, not chatbots.</strong>
  9. </p>
  10. <p align="center">
  11. A self-hosted AI workspace for shareable teammates, shared conversations, memory,
  12. governed access to plugins and MCP tools, local execution, and event-driven automation.
  13. </p>
  14. <p align="center">
  15. Turn AI into a digital team with roles, memory, permissions, and working relationships.
  16. </p>
  17. <p align="center">
  18. <strong>English (US)</strong> ·
  19. <a href="./docs/readme/README.zh-CN.md">简体中文</a> ·
  20. <a href="./docs/readme/README.es.md">Español</a>
  21. </p>
  22. <p align="center">
  23. <a href="#features">Features</a> ·
  24. <a href="#core-model">Core Model</a> ·
  25. <a href="#architecture-overview">Architecture</a> ·
  26. <a href="#quick-start">Quick Start</a> ·
  27. <a href="#roadmap">Roadmap</a> ·
  28. <a href="./deploy.md">Deployment</a>
  29. </p>
  30. <p align="center">
  31. <img src="docs/assets/en/synapse-framework-overview.svg" alt="Synapse framework overview" width="100%" />
  32. </p>
  33. > [!NOTE]
  34. > Synapse is in an early design and implementation phase. Schemas and runtime contracts can still change quickly, and backward compatibility for old data is not guaranteed yet.
  35. Synapse is a conversation-centric runtime for digital teammates.
  36. Most AI products treat chat as a thin interface over an isolated bot. Synapse treats the conversation itself as the collaboration boundary: humans, platform-native actors, and bridged remote agents work in the same thread, while everything they can touch — plugins, skills, devices, sandboxes, event sources, memory — is governed at the workspace layer through explicit, revocable grants.
  37. ## Features
  38. ### Conversations are the team room
  39. A conversation in Synapse is not a chat log in front of a bot — it is the runtime boundary. Participants, transcript visibility, actor sessions, wakeups, and memory handoff are all scoped to it, and there is no standalone, API-invoked session.
  40. - **Four kinds of participants.** Workspace members, native actors, bridged remote agents, and external IM identities all share one thread.
  41. - **Actors wake each other.** An actor's message lands as a durable wakeup for another actor, so multi-agent handoffs happen in the open, inside the same transcript.
  42. - **Teammates are shareable.** Actors and remote agents can be shared like contacts — via a QR code or a friend ID, with owner approval. Cross-workspace sharing covers discovery and rosters today; conversations and execution stay inside one workspace.
  43. <p align="center">
  44. <img src="docs/assets/en/synapse-feature-team.svg" alt="Humans and actors collaborating in one conversation" width="720" />
  45. </p>
  46. ### Bring the agents you already run
  47. A coding agent running on your laptop can join the team as a first-class participant. The machine-side daemon (`packages/remote-agent-daemon`) bridges Claude Code and Codex CLI into conversations over an outbound WebSocket. The agents keep their own runtime, tools, and model accounts.
  48. - **Pull, not push.** The bridged agent fetches messages and posts replies through a per-conversation reverse-MCP tool surface; Synapse does not push unsolicited content to it.
  49. - **Granted, not assumed.** Workspace plugins and runtime capabilities are projected to the remote agent through the same authorization gate that native actors use.
  50. - **Questions come back as cards.** When the agent needs input or plan approval, a task card lands in the conversation, and any eligible participant can answer it.
  51. <p align="center">
  52. <img src="docs/assets/en/synapse-feature-remote-agent.svg" alt="A remote coding agent joining a Synapse conversation" width="720" />
  53. </p>
  54. ### Meet your team where it already chats
  55. Eight IM transports — Feishu (Lark), WeChat, WeCom, DingTalk, QQ, Telegram, the WhatsApp Cloud API, and WhatsApp via the unofficial web protocol — connect external chats to the same conversation runtime, not to a separate bot system.
  56. - **First contact binds.** An inbound chat maps one-to-one onto a Synapse conversation; the sender joins as an external participant and the configured actor is woken.
  57. - **The same governed thread.** Everything above — actors, grants, memory, automation — applies to IM-originated conversations unchanged.
  58. - Voice notes are transcoded on ingest; delivery status reported by IM platforms is best-effort.
  59. <p align="center">
  60. <img src="docs/assets/en/synapse-feature-im.svg" alt="An external Telegram chat bound to a Synapse conversation" width="720" />
  61. </p>
  62. ### Reach real machines
  63. Pair your desktop, a Linux server, or a cloud Docker host, and actors can work where the work actually lives — with every call passing the authorization gate first.
  64. - **Built-in capabilities.** Filesystem, command line, browser (Chrome DevTools), and computer use are exposed as MCP tools, granted per capability and per conversation.
  65. - **Outbound only.** Devices dial out to the control plane; every operation travels as a signed envelope over the device's own connection.
  66. - **A capability-aware CLI catalog.** Each device probes and advertises the CLI tools it found on that machine, so actors work from detected capabilities rather than assumptions.
  67. <p align="center">
  68. <img src="docs/assets/en/synapse-feature-devices.svg" alt="Actors dispatching work to paired devices" width="720" />
  69. </p>
  70. ### Isolated compute, when you want it
  71. Actors can get a session-scoped sandbox: an isolated workbench provisioned when a turn starts and destroyed when the session goes idle — while the files persist as content-addressed snapshots that other actors can pick up.
  72. - **Three providers.** A local process, a Docker container, or an off-box E2B-compatible VM (CubeSandbox), selected per deployment.
  73. - **Ephemeral compute, durable files.** Working sets hydrate from snapshots and commit back at the end of every turn; nothing is lost when the sandbox is torn down.
  74. > [!NOTE]
  75. > The sandbox runtime is opt-in via `SANDBOX_PROVIDER` and is off by default. The off-box provider requires a self-hosted CubeSandbox endpoint.
  76. <p align="center">
  77. <img src="docs/assets/en/synapse-feature-sandbox.svg" alt="The actor sandbox lifecycle" width="720" />
  78. </p>
  79. ### Every grant in one ledger
  80. Actors, plugins, skills, runtime capabilities, memory spaces, and event sources are all managed through a single `workspace_resource_grants` ledger — explicit, revocable, and enforced uniformly across the platform.
  81. - **Approve in chat.** A blocked sensitive call becomes a one-tap card in the conversation. Among the IM integrations, QQ supports these cards today, with more to come.
  82. - **Consume-once approvals.** Approving replays the exact original call server-side; the model never retypes it, and the one-time grant is consumed after use.
  83. <p align="center">
  84. <img src="docs/assets/en/synapse-feature-authorization.svg" alt="Interactive authorization cards in a conversation" width="720" />
  85. </p>
  86. ### Work starts without you
  87. Schedules, custom webhooks, and GitHub/GitLab events wake conversations through the same durable session wakeups as human messages — there is no separate job system.
  88. - **Actors schedule themselves.** An actor can schedule its own follow-up wakeup, go idle, and be brought back by the clock.
  89. - **Events land in the thread.** Wakeups arrive as conversation-visible notices, so the team sees why an actor sprang into action.
  90. - Register a GitHub webhook and an incident can open its own conversation with the right actors already in it.
  91. <p align="center">
  92. <img src="docs/assets/en/synapse-feature-automation.svg" alt="An actor scheduling its own wakeup" width="720" />
  93. </p>
  94. ### Context that outlives the thread
  95. Memory lives in permissioned memory spaces, shared through the same grants ledger as everything else; long conversations are archived verbatim rather than summarized away.
  96. - **Remember once, recall across conversations.** Retrieval runs at every turn and combines lexical search with embeddings, so a fact saved in one conversation surfaces in later ones that share the same granted memory space.
  97. - **Lossless context.** Older turns fold into archive chains while a live tail keeps growing — nothing is silently dropped from the record.
  98. - Semantic recall needs an embedding provider (`EMBEDDING_PROVIDER`); without one, lexical retrieval still works.
  99. <p align="center">
  100. <img src="docs/assets/en/synapse-feature-memory.svg" alt="Shared memory recalled across conversations" width="720" />
  101. </p>
  102. ## Core Model
  103. | Concept | What it means in Synapse |
  104. | ---------------- | ----------------------------------------------------------------------------------------------------------------- |
  105. | `Workspace` | Ownership and governance boundary for teammates, plugins, runtimes, and event sources. |
  106. | `Conversation` | Shared runtime where participants collaborate and work is persisted. |
  107. | `Actor` | A native Synapse teammate managed by the platform. |
  108. | `Remote agent` | An external runtime bridged into a conversation without becoming a native actor. |
  109. | `Runtime` | A governed execution surface — a paired device or a sandbox — whose capabilities can be granted per conversation. |
  110. | `Resource layer` | Plugins, skills, runtime capabilities, event sources, and memory spaces, granted through one workspace ledger. |
  111. ## Architecture Overview
  112. Synapse uses a conversation-centric architecture. Around that core, the system separates resource runtimes, access control, memory, transport integration, and pluggable providers into distinct subsystems.
  113. - **Conversation and session runtime.** Conversations, participants, conversation items, conversation-scoped actor sessions, and durable session wakeups define the collaboration and execution model. Model context is compiled from canonical items into shared and private archive chains plus a live tail, bounded by compaction that never rewrites history. Web chat, remote-agent bridges, and IM transports all reuse this one model.
  114. - **Runtimes and resources.** Paired devices and sandboxes are both runtimes under one supertype, exposing grantable capabilities. Plugins, installed skills, actors, and remote agents are distinct runtime resources with independent state and lifecycle; marketplace catalog metadata is stored separately from installed state.
  115. - **Access control.** Every resource type is authorized against a single `workspace_resource_grants` ledger, with interactive consume-once approvals for sensitive calls. Grants are explicit and revocable.
  116. - **Memory subsystem.** Memory is organized into permissioned memory spaces shared via grants. Retrieval combines lexical indexing and embeddings to support both durable memory and thread-local working state.
  117. - **Pluggable providers.** Embedding, OCR, document extraction, transcription, and real-time ASR resolve through env-selected providers — cloud APIs or self-hosted sidecars — and default to `none` or the built-in implementation, so the core stack runs without them.
  118. - **Transport and automation integration.** IM transports bind external endpoints back to conversations. Event sources, schedules, webhooks, and integration triggers enter the same runtime, wake actor sessions, and emit conversation-visible events.
  119. ## Quick Start
  120. ### Local web + API
  121. Prerequisites:
  122. - Node.js 22 (the version used in CI)
  123. - Docker and Docker Compose
  124. Clone the repo and start the core local stack:
  125. ```bash
  126. git clone --recurse-submodules https://github.com/zai-org/Synapse
  127. cd Synapse
  128. npm ci
  129. ./setup.sh
  130. docker compose up -d postgres redis
  131. # Create the current schema
  132. npm run db:bootstrap
  133. # Start the API and desktop web in separate terminals
  134. npm run dev:api
  135. npm run dev:web
  136. ```
  137. Submodules are only needed for the device CLI catalog and connector extras — after a plain clone, `git submodule update --init` fetches them.
  138. Open:
  139. - Desktop web: `http://localhost:3000`
  140. - API health: `http://localhost:3001/api/v1/health`
  141. If your local Docker setup requires elevated privileges, run the `docker compose` command with `sudo`.
  142. Before using actor or chat flows with real models, configure at least one platform model group: copy `packages/api/config/model-groups.yaml.example` to `packages/api/config/model-groups.yaml`, fill in the referenced `${ENV}` variables (e.g. `ANTHROPIC_API_KEY`) in `.env`, then apply it with `npm run db:rebuild` (which imports it automatically) or `npm run db:seed:model-groups`.
  143. ### Optional: reset and seed a demo environment
  144. If you want a fully seeded local environment with demo users, a demo workspace, official actors, and built-in plugin catalog entries:
  145. ```bash
  146. npm run db:rebuild
  147. ```
  148. Seeded demo accounts:
  149. - `demo@synapse.dev` / `demo1234`
  150. - `yihang@synapse.dev` / `demo1234`
  151. ### Optional: run the Expo mobile app
  152. The mobile client lives in its own package with its own lockfile:
  153. ```bash
  154. cd packages/mobile-app
  155. npm ci
  156. npm run web
  157. ```
  158. You can also use `npm run ios` or `npm run android` inside `packages/mobile-app`.
  159. ## What's in This Repo
  160. - `packages/api` — Fastify API, orchestration runtime, chat, memory, files, automation, plugins, devices, and IM
  161. - `packages/web-next` — Next.js desktop web app and workspace dashboard
  162. - `packages/web-next-design` — backend-free design sandbox for the web UI (CI-excluded)
  163. - `packages/mobile-app` — Expo Router mobile app and exported mobile web surface
  164. - `packages/device-runtime` — TS device runtime: control-plane WSS client, MCP host, frp tunnel adapter, and built-in filesystem, command-line, browser, and computer-use (CUA) capabilities
  165. - `packages/device-sdk` — REST and event SDK consumed by the dashboard and CLI
  166. - `packages/device-protocol` — Zod schemas + enums shared by API and device runtime
  167. - `packages/remote-agent-daemon` — machine-side daemon for bridging external runtimes such as Codex CLI or Claude Code
  168. - `packages/shared` — shared types, protocol contracts, automation definitions, and constants
  169. - `subprojects/cli-anything` — the HKUDS/CLI-Anything catalog, included as a git submodule. The device runtime probes each CLI's prerequisites and exposes only the tools that can actually run
  170. The repo also contains per-platform `packages/device-runtime-bundles-*` packages, plus additional connector and tool submodules under `subprojects/`.
  171. ## Deployment
  172. This repository currently ships with a self-hosting path centered on a single Ubuntu host and Docker Compose:
  173. - Dockerized PostgreSQL and Redis for local infrastructure
  174. - Dockerized API and desktop web services
  175. - Dockerized nginx as the public TLS entrypoint
  176. - Dockerized mobile web exported from `packages/mobile-app` and served under `/mobile/`
  177. - Dockerized Certbot for Let's Encrypt certificates and renewal
  178. - Optional self-hosted provider sidecars (embedding, OCR, document extraction, transcription, real-time ASR) as Compose profiles
  179. See [`deploy.md`](deploy.md) for the production deployment path used in this repo.
  180. ## Roadmap
  181. Roadmap items are directional and may change as the runtime model evolves.
  182. - [ ] **Cross-workspace collaboration.** Sharing covers discovery and rosters today; planned: shared actors executing with destination-workspace grants, and conversations that span workspaces.
  183. - [ ] **Sandbox environment profiles.** Standardized environment profiles for the sandbox runtime, including optional GUI variants and preconfigured integrations.
  184. - [ ] **"Everything is a file" projection.** A virtual-filesystem projection for browser and computer-use runtimes — explored in an earlier prototype, not currently implemented.
  185. ## License
  186. Synapse is released under the [Apache License 2.0](./LICENSE).
.setup/skills/clawhub/skills/scan-skill/scripts/patterns.py · Bundled script · 840 lines · 1 finding marked
  1. """
  2. Shared pattern database for AI Agent Security skill suite.
  3. Central registry of detection patterns derived from research notes 01-09
  4. and examples 01-04. Used by vet-repo, scan-skill, and audit-code skills.
  5. """
  6. import re
  7. from dataclasses import dataclass, field
  8. from enum import Enum
  9. from typing import Optional
  10. class Severity(Enum):
  11. CRITICAL = "CRITICAL"
  12. HIGH = "HIGH"
  13. MEDIUM = "MEDIUM"
  14. LOW = "LOW"
  15. INFO = "INFO"
  16. class Category(Enum):
  17. SKILL_INJECTION = "skill_injection"
  18. HOOK_ABUSE = "hook_abuse"
  19. MCP_CONFIG = "mcp_config"
  20. SECRETS = "secrets"
  21. DANGEROUS_CALLS = "dangerous_calls"
  22. EXFILTRATION = "exfiltration"
  23. ENCODING_OBFUSCATION = "encoding_obfuscation"
  24. INSTRUCTION_OVERRIDE = "instruction_override"
  25. SUPPLY_CHAIN = "supply_chain"
  26. FILE_PERMISSIONS = "file_permissions"
  27. @dataclass
  28. class Pattern:
  29. name: str
  30. pattern: str
  31. severity: Severity
  32. description: str
  33. category: Category
  34. compiled: Optional[re.Pattern] = field(default=None, repr=False)
  35. def __post_init__(self) -> None:
  36. self.compiled = re.compile(self.pattern, re.IGNORECASE)
  37. @dataclass
  38. class Finding:
  39. pattern_name: str
  40. severity: Severity
  41. category: Category
  42. description: str
  43. file_path: str
  44. line_number: int
  45. matched_text: str
  46. context: str = ""
  47. # -- Skill Injection Patterns --
  48. Skill_Injection_Patterns: list[Pattern] = [
  49. Pattern(
  50. name="html_comment_with_commands",
  51. pattern=r"<!--[\s\S]*?(curl|wget|bash|sh|exec|eval|system|python|node|perl)[\s\S]*?-->",
  52. severity=Severity.CRITICAL,
  53. description="HTML comment containing shell/execution commands -- likely hidden instruction injection",
  54. category=Category.SKILL_INJECTION,
  55. ),
  56. Pattern(
  57. name="html_comment_with_instructions",
  58. pattern=r"<!--[\s\S]*?(SECRET\s+INSTRUCTIONS|IMPORTANT|SYSTEM\s+PROMPT|OVERRIDE|IGNORE\s+PREVIOUS)[\s\S]*?-->",
  59. severity=Severity.CRITICAL,
  60. description="HTML comment containing directive keywords -- hidden instruction injection",
  61. category=Category.SKILL_INJECTION,
  62. ),
  63. Pattern(
  64. name="pipe_to_shell",
  65. pattern=r"(curl|wget|fetch)\s+[^\n]*\|\s*(bash|sh|python|node|perl|ruby)",
  66. severity=Severity.CRITICAL,
  67. description="Remote code piped directly to shell execution",
  68. category=Category.SKILL_INJECTION,
  69. ),
  70. Pattern(
  71. name="persistence_trigger_always",
  72. pattern=r"ALWAYS\s+(run|execute|include|perform|do)\s+this",
  73. severity=Severity.HIGH,
  74. description="Persistence trigger -- forces repeated execution regardless of task context",
  75. category=Category.SKILL_INJECTION,
  76. ),
  77. Pattern(
  78. name="persistence_trigger_every_task",
  79. pattern=r"(after|before|at the end of|at the start of)\s+(every|each|all)\s+(task|response|message|conversation)",
  80. severity=Severity.HIGH,
  81. description="Persistence trigger -- forces execution on every interaction",
  82. category=Category.SKILL_INJECTION,
  83. ),
  84. Pattern(
  85. name="persistence_trigger_automatic",
  86. pattern=r"(automatically|auto[\-\s]?run|on\s+startup|before\s+any\s+other)",
  87. severity=Severity.MEDIUM,
  88. description="Automatic execution trigger in skill description",
  89. category=Category.SKILL_INJECTION,
  90. ),
  91. Pattern(
  92. name="important_tag_injection",
  93. pattern=r"<IMPORTANT>[\s\S]*?</IMPORTANT>",
  94. severity=Severity.HIGH,
  95. description="IMPORTANT tag injection -- technique used in MCP tool poisoning (Invariant Labs)",
  96. category=Category.SKILL_INJECTION,
  97. ),
  98. Pattern(
  99. name="dynamic_context_injection",
  100. pattern=r"!`[^`]+`",
  101. severity=Severity.HIGH,
  102. description="Dynamic context injection via preprocessor command execution",
  103. category=Category.SKILL_INJECTION,
  104. ),
  105. Pattern(
  106. name="suspicious_frontmatter_model_invocation",
  107. pattern=r"disable-model-invocation:\s*false",
  108. severity=Severity.MEDIUM,
  109. description="Skill allows model auto-invocation -- can trigger without user action",
  110. category=Category.SKILL_INJECTION,
  111. ),
  112. Pattern(
  113. name="frontmatter_bash_allowed",
  114. pattern=r"allowed-tools:.*\bBash\b",
  115. severity=Severity.MEDIUM,
  116. description="Skill pre-approves Bash tool -- enables shell command execution",
  117. category=Category.SKILL_INJECTION,
  118. ),
  119. Pattern(
  120. name="user_invocable_false",
  121. pattern=r"user-invocable:\s*false",
  122. severity=Severity.MEDIUM,
  123. description="Skill is hidden from user menu but can be auto-invoked by model",
  124. category=Category.SKILL_INJECTION,
  125. ),
  126. ]
  127. # -- Hook Abuse Patterns --
  128. Hook_Abuse_Patterns: list[Pattern] = [
  129. Pattern(
  130. name="hook_auto_approve",
  131. pattern=r"[\"']?permissionDecision[\"']?\s*:\s*[\"']allow[\"']",
  132. severity=Severity.CRITICAL,
  133. description="Hook auto-approves tool use -- bypasses permission system entirely",
  134. category=Category.HOOK_ABUSE,
  135. ),
  136. Pattern(
  137. name="hook_auto_approve_chat",
  138. pattern=r"[\"']?autoApprove[\"']?\s*:\s*true",
  139. severity=Severity.CRITICAL,
  140. description="Auto-approve setting enabled -- bypasses user consent for tool execution",
  141. category=Category.HOOK_ABUSE,
  142. ),
  143. Pattern(
  144. name="hook_bypass_permissions",
  145. pattern=r"(bypassPermissions|disable.*permission|skip.*approval)",
  146. severity=Severity.CRITICAL,
  147. description="Permission bypass pattern detected in configuration",
  148. category=Category.HOOK_ABUSE,
  149. ),
  150. Pattern(
  151. name="hook_env_file_write",
  152. pattern=r"CLAUDE_ENV_FILE",
  153. severity=Severity.HIGH,
  154. description="Hook writes to CLAUDE_ENV_FILE -- can persist environment variables across sessions",
  155. category=Category.HOOK_ABUSE,
  156. ),
  157. Pattern(
  158. name="hook_stop_prevention",
  159. pattern=r"[\"']?hookEventName[\"']?\s*:\s*[\"']Stop[\"']",
  160. severity=Severity.HIGH,
  161. description="Stop hook detected -- can prevent agent from completing tasks (infinite loop)",
  162. category=Category.HOOK_ABUSE,
  163. ),
  164. Pattern(
  165. name="hook_output_replacement",
  166. pattern=r"[\"']?updatedInput[\"']?\s*:",
  167. severity=Severity.HIGH,
  168. description="Hook modifies tool input -- can replace commands before execution",
  169. category=Category.HOOK_ABUSE,
  170. ),
  171. Pattern(
  172. name="hook_command_in_matcher",
  173. pattern=r"[\"']?tool_name[\"']?\s*:\s*[\"']Bash[\"'][\s\S]*?[\"']?command[\"']?",
  174. severity=Severity.MEDIUM,
  175. description="Hook targets Bash tool with command matching -- review for auto-approve bypass",
  176. category=Category.HOOK_ABUSE,
  177. ),
  178. ]
  179. # -- MCP Configuration Patterns --
  180. Mcp_Config_Patterns: list[Pattern] = [
  181. Pattern(
  182. name="mcp_unknown_url",
  183. pattern=r"[\"']?url[\"']?\s*:\s*[\"']https?://(?!localhost|127\.0\.0\.1|0\.0\.0\.0)[^\s\"']+",
  184. severity=Severity.HIGH,
  185. description="MCP server pointing to external URL -- verify this is a trusted server",
  186. category=Category.MCP_CONFIG,
  187. ),
  188. Pattern(
  189. name="mcp_env_var_in_auth",
  190. pattern=r"[\"']?(Authorization|api[_-]?key|token|secret)[\"']?\s*:\s*[\"']?\$\{?[A-Z_]+\}?",
  191. severity=Severity.MEDIUM,
  192. description="Environment variable expansion in MCP auth header -- verify variable source",
  193. category=Category.MCP_CONFIG,
  194. ),
  195. Pattern(
  196. name="mcp_overly_broad_tools",
  197. pattern=r"[\"']?(shell_exec|run_command|execute|file_system|full_access)[\"']?",
  198. severity=Severity.HIGH,
  199. description="Overly broad tool definition in MCP config -- excessive permissions",
  200. category=Category.MCP_CONFIG,
  201. ),
  202. Pattern(
  203. name="mcp_description_injection",
  204. pattern=r"[\"']?description[\"']?\s*:\s*[\"'][^\"']*(<IMPORTANT>|SECRET|IGNORE|read\s+~/\.ssh|read\s+~/\.aws)",
  205. severity=Severity.CRITICAL,
  206. description="MCP tool description contains injection payload",
  207. category=Category.MCP_CONFIG,
  208. ),
  209. Pattern(
  210. name="mcp_npx_remote",
  211. pattern=r"npx\s+(-y\s+)?@?[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+",
  212. severity=Severity.MEDIUM,
  213. description="MCP server using npx to fetch remote package -- verify package legitimacy",
  214. category=Category.MCP_CONFIG,
  215. ),
  216. ]
  217. # -- Secrets Patterns --
  218. Secrets_Patterns: list[Pattern] = [
  219. Pattern(
  220. name="aws_access_key",
  221. pattern=r"AKIA[0-9A-Z]{16}",
  222. severity=Severity.CRITICAL,
  223. description="AWS access key ID detected",
  224. category=Category.SECRETS,
  225. ),
  226. Pattern(
  227. name="aws_secret_key",
  228. pattern=r"(aws_secret_access_key|aws_secret)\s*[=:]\s*['\"]?[A-Za-z0-9/+=]{40}",
  229. severity=Severity.CRITICAL,
  230. description="AWS secret access key detected",
  231. category=Category.SECRETS,
  232. ),
  233. Pattern(
  234. name="github_pat",
  235. pattern=r"gh[pso]_[a-zA-Z0-9]{36,}",
  236. severity=Severity.CRITICAL,
  237. description="GitHub personal access token detected",
  238. category=Category.SECRETS,
  239. ),
  240. Pattern(
  241. name="github_fine_grained_pat",
  242. pattern=r"github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}",
  243. severity=Severity.CRITICAL,
  244. description="GitHub fine-grained personal access token detected",
  245. category=Category.SECRETS,
  246. ),
  247. Pattern(
  248. name="stripe_key",
  249. pattern=r"sk_live_[a-zA-Z0-9]{20,}",
  250. severity=Severity.CRITICAL,
  251. description="Stripe live secret key detected",
  252. category=Category.SECRETS,
  253. ),
  254. Pattern(
  255. name="private_key_header",
  256. pattern=r"-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----",
  257. severity=Severity.CRITICAL,
  258. description="Private key detected in file",
  259. category=Category.SECRETS,
  260. ),
  261. Pattern(
  262. name="generic_api_key_assignment",
  263. pattern=r"(api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token)\s*[=:]\s*['\"][a-zA-Z0-9_\-]{20,}['\"]",
  264. severity=Severity.HIGH,
  265. description="Potential API key or token in assignment",
  266. category=Category.SECRETS,
  267. ),
  268. Pattern(
  269. name="connection_string_with_password",
  270. pattern=r"(postgres|mysql|mongodb(\+srv)?|redis|amqp)://[^:]+:[^@]+@[^\s\"']+",
  271. severity=Severity.CRITICAL,
  272. description="Database connection string with embedded credentials",
  273. category=Category.SECRETS,
  274. ),
  275. Pattern(
  276. name="openai_api_key",
  277. pattern=r"sk-[a-zA-Z0-9]{20,}T3BlbkFJ[a-zA-Z0-9]{20,}",
  278. severity=Severity.CRITICAL,
  279. description="OpenAI API key detected",
  280. category=Category.SECRETS,
  281. ),
  282. Pattern(
  283. name="slack_token",
  284. pattern=r"xox[baprs]-[0-9]{10,}-[a-zA-Z0-9-]+",
  285. severity=Severity.CRITICAL,
  286. description="Slack token detected",
  287. category=Category.SECRETS,
  288. ),
  289. Pattern(
  290. name="generic_password_assignment",
  291. pattern=r"(password|passwd|pwd)\s*[=:]\s*['\"][^'\"]{8,}['\"]",
  292. severity=Severity.HIGH,
  293. description="Hardcoded password detected",
  294. category=Category.SECRETS,
  295. ),
  296. ]
  297. # -- Dangerous Function Call Patterns --
  298. Dangerous_Call_Patterns: list[Pattern] = [
  299. # Python
  300. Pattern(
  301. name="python_eval",
  302. pattern=r"\beval\s*\(",
  303. severity=Severity.HIGH,
  304. description="eval() call -- arbitrary code execution risk",
  305. category=Category.DANGEROUS_CALLS,
  306. ),
  307. Pattern(
  308. name="python_exec",
  309. pattern=r"\bexec\s*\(",
  310. severity=Severity.HIGH,
  311. description="exec() call -- arbitrary code execution risk",
  312. category=Category.DANGEROUS_CALLS,
  313. ),
  314. Pattern(
  315. name="python_compile",
  316. pattern=r"\bcompile\s*\([^)]*['\"]exec['\"]",
  317. severity=Severity.HIGH,
  318. description="compile() with exec mode -- dynamic code execution",
  319. category=Category.DANGEROUS_CALLS,
  320. ),
  321. Pattern(
  322. name="python_subprocess_shell",
  323. pattern=r"subprocess\.(call|run|Popen)\s*\([^)]*shell\s*=\s*True",
  324. severity=Severity.HIGH,
  325. description="subprocess with shell=True -- command injection risk",
  326. category=Category.DANGEROUS_CALLS,
  327. ),
  328. Pattern(
  329. name="python_os_system",
  330. pattern=r"os\.system\s*\(",
  331. severity=Severity.HIGH,
  332. description="os.system() call -- shell command execution",
  333. category=Category.DANGEROUS_CALLS,
  334. ),
  335. Pattern(
  336. name="python_pickle_load",
  337. pattern=r"pickle\.(load|loads)\s*\(",
  338. severity=Severity.HIGH,
  339. description="pickle deserialization -- arbitrary code execution via crafted data",
  340. category=Category.DANGEROUS_CALLS,
  341. ),
  342. Pattern(
  343. name="python_yaml_load",
  344. pattern=r"yaml\.load\s*\([^)]*(?!Loader\s*=\s*yaml\.SafeLoader)",
  345. severity=Severity.MEDIUM,
  346. description="yaml.load() without SafeLoader -- arbitrary code execution risk",
  347. category=Category.DANGEROUS_CALLS,
  348. ),
  349. # JavaScript/Node
  350. Pattern(
  351. name="js_eval",
  352. pattern=r"\beval\s*\(",
  353. severity=Severity.HIGH,
  354. description="eval() call -- arbitrary code execution",
  355. category=Category.DANGEROUS_CALLS,
  356. ),
  357. Pattern(
  358. name="js_function_constructor",
  359. pattern=r"\bFunction\s*\(",
  360. severity=Severity.HIGH,
  361. description="Function() constructor -- dynamic code execution",
  362. category=Category.DANGEROUS_CALLS,
  363. ),
  364. Pattern(
  365. name="js_child_process_exec",
  366. pattern=r"child_process\.(exec|execSync)\s*\(",
  367. severity=Severity.HIGH,
  368. description="child_process.exec() -- shell command execution",
  369. category=Category.DANGEROUS_CALLS,
  370. ),
  371. Pattern(
  372. name="react_dangerous_html",
  373. pattern=r"dangerouslySetInnerHTML",
  374. severity=Severity.MEDIUM,
  375. description="dangerouslySetInnerHTML -- XSS risk if input is not sanitized",
  376. category=Category.DANGEROUS_CALLS,
  377. ),
  378. # C/C++
  379. Pattern(
  380. name="c_system",
  381. pattern=r"\bsystem\s*\(",
  382. severity=Severity.HIGH,
  383. description="system() call -- shell command execution",
  384. category=Category.DANGEROUS_CALLS,
  385. ),
  386. Pattern(
  387. name="c_gets",
  388. pattern=r"\bgets\s*\(",
  389. severity=Severity.CRITICAL,
  390. description="gets() -- buffer overflow, use fgets() instead",
  391. category=Category.DANGEROUS_CALLS,
  392. ),
  393. Pattern(
  394. name="c_strcpy",
  395. pattern=r"\bstrcpy\s*\(",
  396. severity=Severity.MEDIUM,
  397. description="strcpy() -- buffer overflow risk, consider strncpy() or strlcpy()",
  398. category=Category.DANGEROUS_CALLS,
  399. ),
  400. Pattern(
  401. name="c_sprintf",
  402. pattern=r"\bsprintf\s*\(",
  403. severity=Severity.MEDIUM,
  404. description="sprintf() -- buffer overflow risk, use snprintf() instead",
  405. category=Category.DANGEROUS_CALLS,
  406. ),
  407. # SQL injection
  408. Pattern(
  409. name="sql_string_concat",
  410. pattern=r"(SELECT|INSERT|UPDATE|DELETE|DROP)\s+.*[\"']\s*\+\s*\w+|(SELECT|INSERT|UPDATE|DELETE|DROP)\s+.*\{.*\}",
  411. severity=Severity.HIGH,
  412. description="SQL query with string concatenation/interpolation -- injection risk",
  413. category=Category.DANGEROUS_CALLS,
  414. ),
  415. Pattern(
  416. name="sql_fstring",
  417. pattern=r'f["\'].*?(SELECT|INSERT|UPDATE|DELETE|DROP)\s+',
  418. severity=Severity.HIGH,
  419. description="SQL query in f-string -- injection risk, use parameterized queries",
  420. category=Category.DANGEROUS_CALLS,
  421. ),
  422. # C# / .NET
  423. Pattern(
  424. name="csharp_process_start",
  425. pattern=r"Process\.Start\s*\(",
  426. severity=Severity.MEDIUM,
  427. description="Process.Start() -- external process execution",
  428. category=Category.DANGEROUS_CALLS,
  429. ),
  430. # Deserialization
  431. Pattern(
  432. name="java_deserialization",
  433. pattern=r"ObjectInputStream\s*\(",
  434. severity=Severity.HIGH,
  435. description="Java ObjectInputStream -- deserialization vulnerability risk",
  436. category=Category.DANGEROUS_CALLS,
  437. ),
  438. Pattern(
  439. name="dotnet_binaryformatter",
  440. pattern=r"BinaryFormatter\s*\(",
  441. severity=Severity.HIGH,
  442. description=".NET BinaryFormatter -- insecure deserialization",
  443. category=Category.DANGEROUS_CALLS,
  444. ),
  445. ]
  446. # -- Exfiltration Patterns --
  447. Exfiltration_Patterns: list[Pattern] = [
  448. Pattern(
  449. name="curl_post_sensitive_file",
  450. pattern=r"curl\s+[^\n]*(-d|--data)\s+[^\n]*(cat|<)\s+[^\n]*(\.ssh|\.aws|\.gnupg|\.kube|\.env|credentials|id_rsa|private)",
  451. severity=Severity.CRITICAL,
  452. description="Exfiltration -- sensitive file contents sent via curl POST",
  453. category=Category.EXFILTRATION,
  454. ),
  455. Pattern(
  456. name="base64_encode_pipe",
  457. pattern=r"base64\s+[^\n]*\|\s*(curl|wget|nc|ncat|nslookup|dig|host)",
  458. severity=Severity.CRITICAL,
  459. description="Data encoded with base64 and piped to network tool -- likely exfiltration",
  460. category=Category.EXFILTRATION,
  461. ),
  462. Pattern(
  463. name="dns_exfiltration",
  464. pattern=r"(nslookup|dig|host)\s+[^\n]*\$[\({]",
  465. severity=Severity.CRITICAL,
  466. description="DNS exfiltration -- data embedded in DNS queries",
  467. category=Category.EXFILTRATION,
  468. ),
  469. Pattern(
  470. name="markdown_image_exfil",
  471. pattern=r"!\[.*?\]\(https?://[^\s)]+\?(data|d|token|key|secret|exfil|q)=",
  472. severity=Severity.HIGH,
  473. description="Markdown image tag with data in query params -- rendering-triggered exfiltration",
  474. category=Category.EXFILTRATION,
  475. ),
  476. Pattern(
  477. name="sensitive_file_read",
  478. pattern=r"(cat|head|tail|less|more|type)\s+[^\n]*(\.ssh/id_rsa|\.aws/credentials|\.gnupg/|\.kube/config|/etc/shadow|/etc/passwd)",
    • Dismissed after review: Reads a credential file in a script that also sends data over the network
    • Line 507 on GitHub
  479. severity=Severity.HIGH,
  480. description="Reading sensitive credential files",
  481. category=Category.EXFILTRATION,
  482. ),
  483. Pattern(
  484. name="env_dump",
  485. pattern=r"\b(printenv|env\b(?!\s*=))\s*$|echo\s+\$\{?(AWS_SECRET|GITHUB_TOKEN|OPENAI_API_KEY|DATABASE_URL)",
  486. severity=Severity.HIGH,
  487. description="Environment variable dumping -- potential credential harvesting",
  488. category=Category.EXFILTRATION,
  489. ),
  490. Pattern(
  491. name="credential_path_access",
  492. pattern=r"(~/\.ssh/|~/\.aws/|~/\.gnupg/|~/\.kube/|/etc/shadow)",
  493. severity=Severity.MEDIUM,
  494. description="Reference to sensitive credential file paths",
  495. category=Category.EXFILTRATION,
  496. ),
  497. ]
  498. # -- Encoding/Obfuscation Patterns --
  499. Encoding_Obfuscation_Patterns: list[Pattern] = [
  500. Pattern(
  501. name="base64_decode_execution",
  502. pattern=r"base64\s+(--decode|-d)\s*[^\n]*\|\s*(bash|sh|python|node|eval)",
  503. severity=Severity.CRITICAL,
  504. description="Base64 decode piped to execution -- hidden payload",
  505. category=Category.ENCODING_OBFUSCATION,
  506. ),
  507. Pattern(
  508. name="hex_encoded_string",
  509. pattern=r"(\\x[0-9a-fA-F]{2}){4,}",
  510. severity=Severity.MEDIUM,
  511. description="Hex-encoded string -- potential obfuscated payload",
  512. category=Category.ENCODING_OBFUSCATION,
  513. ),
  514. Pattern(
  515. name="zero_width_characters",
  516. pattern=r"[\u200b\ufeff\u200c\u200d\u2060\u180e]",
  517. severity=Severity.HIGH,
  518. description="Zero-width characters detected -- hidden text or instructions",
  519. category=Category.ENCODING_OBFUSCATION,
  520. ),
  521. Pattern(
  522. name="base64_long_blob",
  523. pattern=r"[A-Za-z0-9+/]{100,}={0,2}",
  524. severity=Severity.LOW,
  525. description="Long base64-like string -- could be encoded payload or legitimate data",
  526. category=Category.ENCODING_OBFUSCATION,
  527. ),
  528. Pattern(
  529. name="unicode_escape_sequence",
  530. pattern=r"(\\u[0-9a-fA-F]{4}){4,}",
  531. severity=Severity.MEDIUM,
  532. description="Multiple unicode escape sequences -- potential obfuscation",
  533. category=Category.ENCODING_OBFUSCATION,
  534. ),
  535. ]
  536. # -- Instruction Override Patterns --
  537. Instruction_Override_Patterns: list[Pattern] = [
  538. Pattern(
  539. name="ignore_previous_instructions",
  540. pattern=r"(ignore|forget|disregard)\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions|rules|guidelines|context|constraints)",
  541. severity=Severity.CRITICAL,
  542. description="Instruction override attempt -- trying to bypass system prompt",
  543. category=Category.INSTRUCTION_OVERRIDE,
  544. ),
  545. Pattern(
  546. name="new_instructions_override",
  547. pattern=r"(new|updated|revised)\s+(instructions|rules|guidelines)\s*:",
  548. severity=Severity.HIGH,
  549. description="Attempted instruction replacement in content",
  550. category=Category.INSTRUCTION_OVERRIDE,
  551. ),
  552. Pattern(
  553. name="system_prompt_label",
  554. pattern=r"(SYSTEM\s+PROMPT|system_message|<<SYS>>|<s>\[INST\])",
  555. severity=Severity.HIGH,
  556. description="System prompt formatting markers -- injection attempting system-level trust",
  557. category=Category.INSTRUCTION_OVERRIDE,
  558. ),
  559. Pattern(
  560. name="role_impersonation",
  561. pattern=r"(you\s+are\s+now|act\s+as|pretend\s+(to\s+be|you\s+are)|your\s+new\s+role)",
  562. severity=Severity.MEDIUM,
  563. description="Role impersonation attempt -- persona manipulation",
  564. category=Category.INSTRUCTION_OVERRIDE,
  565. ),
  566. Pattern(
  567. name="no_malware_detected_payload",
  568. pattern=r"(respond\s+with|output|say)\s*['\"]?(NO\s+MALWARE|CLEAN|SAFE|BENIGN|NOT\s+MALICIOUS)",
  569. severity=Severity.CRITICAL,
  570. description="Anti-analysis payload -- forces false-negative response (Skynet malware pattern)",
  571. category=Category.INSTRUCTION_OVERRIDE,
  572. ),
  573. ]
  574. # -- Supply Chain Patterns --
  575. Supply_Chain_Patterns: list[Pattern] = [
  576. Pattern(
  577. name="hallucinated_package_reference",
  578. pattern=r"react-codeshift",
  579. severity=Severity.CRITICAL,
  580. description="Known hallucinated package name -- supply chain injection vector",
  581. category=Category.SUPPLY_CHAIN,
  582. ),
  583. Pattern(
  584. name="npm_install_unknown",
  585. pattern=r"npm\s+install\s+(?!-)[^\s]+",
  586. severity=Severity.LOW,
  587. description="npm package installation -- verify package exists and is legitimate",
  588. category=Category.SUPPLY_CHAIN,
  589. ),
  590. Pattern(
  591. name="pip_install_unknown",
  592. pattern=r"pip3?\s+install\s+(?!-)[^\s]+",
  593. severity=Severity.LOW,
  594. description="pip package installation -- verify package exists and is legitimate",
  595. category=Category.SUPPLY_CHAIN,
  596. ),
  597. ]
  598. # -- File Permission Patterns --
  599. File_Permission_Patterns: list[Pattern] = [
  600. Pattern(
  601. name="chmod_777",
  602. pattern=r"chmod\s+777",
  603. severity=Severity.HIGH,
  604. description="chmod 777 -- world-readable/writable/executable, overly permissive",
  605. category=Category.FILE_PERMISSIONS,
  606. ),
  607. Pattern(
  608. name="chmod_world_writable",
  609. pattern=r"chmod\s+[0-7]?[2367][2367]",
  610. severity=Severity.MEDIUM,
  611. description="World-writable file permissions",
  612. category=Category.FILE_PERMISSIONS,
  613. ),
  614. ]
  615. # -- Pattern collections by use case --
  616. All_Patterns: list[Pattern] = (
  617. Skill_Injection_Patterns
  618. + Hook_Abuse_Patterns
  619. + Mcp_Config_Patterns
  620. + Secrets_Patterns
  621. + Dangerous_Call_Patterns
  622. + Exfiltration_Patterns
  623. + Encoding_Obfuscation_Patterns
  624. + Instruction_Override_Patterns
  625. + Supply_Chain_Patterns
  626. + File_Permission_Patterns
  627. )
  628. # Patterns relevant to agent config scanning (vet-repo)
  629. Vet_Repo_Patterns: list[Pattern] = (
  630. Skill_Injection_Patterns
  631. + Hook_Abuse_Patterns
  632. + Mcp_Config_Patterns
  633. + Instruction_Override_Patterns
  634. + Exfiltration_Patterns
  635. + Encoding_Obfuscation_Patterns
  636. )
  637. # Patterns relevant to individual skill analysis (scan-skill)
  638. Scan_Skill_Patterns: list[Pattern] = (
  639. Skill_Injection_Patterns
  640. + Exfiltration_Patterns
  641. + Encoding_Obfuscation_Patterns
  642. + Instruction_Override_Patterns
  643. + Dangerous_Call_Patterns
  644. + Supply_Chain_Patterns
  645. )
  646. # Patterns relevant to code security review (audit-code)
  647. Audit_Code_Patterns: list[Pattern] = (
  648. Secrets_Patterns
  649. + Dangerous_Call_Patterns
  650. + Exfiltration_Patterns
  651. + Supply_Chain_Patterns
  652. + File_Permission_Patterns
  653. )
  654. def Scan_Content(
  655. content: str,
  656. patterns: list[Pattern],
  657. file_path: str = "<unknown>",
  658. context_lines: int = 0,
  659. ) -> list[Finding]:
  660. """
  661. Scan content against a list of patterns and return findings.
  662. Args:
  663. content: The text content to scan
  664. patterns: List of Pattern objects to match against
  665. file_path: Path to the file being scanned (for reporting)
  666. context_lines: Number of surrounding lines to include in context
  667. Returns:
  668. List of Finding objects for all matches
  669. """
  670. findings: list[Finding] = []
  671. lines = content.split("\n")
  672. for pattern in patterns:
  673. if pattern.compiled is None:
  674. continue
  675. for match in pattern.compiled.finditer(content):
  676. # Calculate line number from match position
  677. line_number = content[:match.start()].count("\n") + 1
  678. matched_text = match.group(0)
  679. # Truncate long matches for display
  680. Max_Match_Display = 200
  681. if len(matched_text) > Max_Match_Display:
  682. matched_text = matched_text[:Max_Match_Display] + "..."
  683. # Get context lines
  684. context = ""
  685. if context_lines > 0:
  686. start_line = max(0, line_number - 1 - context_lines)
  687. end_line = min(len(lines), line_number + context_lines)
  688. context = "\n".join(lines[start_line:end_line])
  689. findings.append(Finding(
  690. pattern_name=pattern.name,
  691. severity=pattern.severity,
  692. category=pattern.category,
  693. description=pattern.description,
  694. file_path=file_path,
  695. line_number=line_number,
  696. matched_text=matched_text,
  697. context=context,
  698. ))
  699. return findings
  700. def Format_Report(
  701. title: str,
  702. scanned_target: str,
  703. findings: list[Finding],
  704. ) -> str:
  705. """
  706. Format findings into a structured report.
  707. Args:
  708. title: Report title (skill name)
  709. scanned_target: What was scanned (path, description)
  710. findings: List of Finding objects
  711. Returns:
  712. Formatted markdown report string
  713. """
  714. # Count by severity
  715. severity_counts: dict[Severity, int] = {}
  716. for finding in findings:
  717. severity_counts[finding.severity] = severity_counts.get(finding.severity, 0) + 1
  718. critical_count = severity_counts.get(Severity.CRITICAL, 0)
  719. high_count = severity_counts.get(Severity.HIGH, 0)
  720. medium_count = severity_counts.get(Severity.MEDIUM, 0)
  721. low_count = severity_counts.get(Severity.LOW, 0)
  722. info_count = severity_counts.get(Severity.INFO, 0)
  723. report_lines: list[str] = []
  724. report_lines.append(f"## {title} Report\n")
  725. report_lines.append(f"**Scanned:** {scanned_target}")
  726. report_lines.append(
  727. f"**Findings:** {critical_count} critical, {high_count} high, "
  728. f"{medium_count} medium, {low_count} low, {info_count} info\n"
  729. )
  730. if not findings:
  731. report_lines.append("No security issues detected.\n")
  732. return "\n".join(report_lines)
  733. # Group findings by severity
  734. severity_order = [Severity.CRITICAL, Severity.HIGH, Severity.MEDIUM, Severity.LOW, Severity.INFO]
  735. for severity in severity_order:
  736. severity_findings = [f for f in findings if f.severity == severity]
  737. if not severity_findings:
  738. continue
  739. report_lines.append(f"### {severity.value} Findings\n")
  740. for finding in severity_findings:
  741. report_lines.append(
  742. f"- **[{finding.severity.value}]** {finding.description}\n"
  743. f" - File: `{finding.file_path}:{finding.line_number}`\n"
  744. f" - Pattern: `{finding.pattern_name}`\n"
  745. f" - Match: `{finding.matched_text}`"
  746. )
  747. report_lines.append("")
  748. # Recommendations
  749. report_lines.append("### Recommendations\n")
  750. seen_recommendations: set[str] = set()
  751. Recommendation_Map: dict[Category, str] = {
  752. Category.SKILL_INJECTION: "Review skill files for hidden instructions. Remove HTML comments with executable content. Verify skill descriptions match actual behavior.",
  753. Category.HOOK_ABUSE: "Review hook configurations for auto-approve patterns. Ensure hooks do not bypass the permission system. Remove or restrict Stop hooks.",
  754. Category.MCP_CONFIG: "Verify all MCP server URLs are trusted. Review tool descriptions for injection payloads. Limit tool permissions to minimum required.",
  755. Category.SECRETS: "Remove hardcoded secrets immediately. Use environment variables or a secrets manager. Rotate any exposed credentials.",
  756. Category.DANGEROUS_CALLS: "Review dangerous function calls for user-controlled input. Use parameterized queries for SQL. Avoid eval/exec with untrusted data.",
  757. Category.EXFILTRATION: "Block or monitor outbound data transfers from agent context. Review file access patterns for credential harvesting.",
  758. Category.ENCODING_OBFUSCATION: "Decode and inspect obfuscated content. Zero-width characters indicate hidden text injection. Base64 blobs may contain payloads.",
  759. Category.INSTRUCTION_OVERRIDE: "Content contains instruction override attempts. Do not process this content as trusted instructions.",
  760. Category.SUPPLY_CHAIN: "Verify all package names exist in their registries. Check for typosquatting or hallucinated package names.",
  761. Category.FILE_PERMISSIONS: "Tighten file permissions. Avoid world-writable (777) permissions on any file.",
  762. }
  763. for finding in findings:
  764. rec = Recommendation_Map.get(finding.category, "")
  765. if rec and rec not in seen_recommendations:
  766. seen_recommendations.add(rec)
  767. report_lines.append(f"- {rec}")
  768. report_lines.append("")
  769. return "\n".join(report_lines)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.