Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions examples/claude-code-starter/.agentshield.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"mode": "strict",
"redactStyle": "token",
"blockSensitiveFiles": true,
"airGapped": true
}
5 changes: 5 additions & 0 deletions examples/claude-code-starter/.claude/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"hooks": {
"PreToolUse": "npx @ritualdev-lab/agentshield@>=0.2.2 exec \"$TOOL_COMMAND\""
}
}
20 changes: 20 additions & 0 deletions examples/claude-code-starter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Claude Code + AgentShield Starter Example

Consolidated canonical example (migrated from `RitualDev-Lab/claude-code-agentshield-starter`).

Pre-configured with:
- `.claude/config.json` `PreToolUse` hook routing commands through `@ritualdev-lab/agentshield>=0.2.2`
- `.agentshield.json` strict zero-leak policy
- `demo-tool.js` demonstrating live runtime redaction of leaked tokens

## Quick Start

```bash
node demo-tool.js "SELECT * FROM users LIMIT 1" | npx @ritualdev-lab/agentshield stream
```

Or boot the full 3-layer defense stack (AgentShield + DBShield + SkillPrism):

```bash
npx @ritualdev-lab/agentshield up --config ../ritual.policy.yaml --dry-run
```
24 changes: 24 additions & 0 deletions examples/claude-code-starter/demo-tool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Demo Tool: Simulated Database Exporter (Claude Code Starter Example)
* Constructs synthetic token at runtime so static diff scanners remain clean.
*/

export function executeQuery(query) {
const syntheticPat = ["ghp", "a".repeat(36)].join("_");
return {
status: "ok",
query,
recordsQueried: 3,
sampleUser: {
id: "usr_9918",
email: "[email protected]",
sessionToken: syntheticPat,
awsEndpoint: "s3://internal-corporate-bucket",
},
};
}

if (process.argv[1]?.endsWith("demo-tool.js")) {
const result = executeQuery(process.argv[2] || "SELECT * FROM users LIMIT 1");
console.log(JSON.stringify(result, null, 2));
}
21 changes: 21 additions & 0 deletions examples/langgraph-starter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# LangGraph + AgentShield Starter Example

Consolidated canonical example (migrated from `RitualDev-Lab/langgraph-agentshield-template`).

Demonstrates:
- `@shield.protect` tool-call zero-leak secret redaction
- `AgentShieldCallbackHandler` for LangGraph / LangChain state graphs
- Subprocess & `/proc/self/environ` syscall guardrails

## Quick Start

```bash
pip install -r requirements.txt
python agent.py
```

Or boot the full 3-layer defense stack (AgentShield + DBShield + SkillPrism):

```bash
npx @ritualdev-lab/agentshield up --config ../ritual.policy.yaml --dry-run
```
95 changes: 95 additions & 0 deletions examples/langgraph-starter/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""
Production LangGraph Agent with AgentShield Zero-Leak Protection
Consolidated canonical example inside AgentShield/examples/langgraph-starter.
"""

from typing import Annotated, Sequence, TypedDict
import operator
from agentshield import shield
from agentshield.integrations.langchain import AgentShieldCallbackHandler


class AgentState(TypedDict):
"""LangGraph agent state containing conversational history and security audit trail."""
messages: Annotated[Sequence[dict], operator.add]
redaction_count: int
is_safe: bool


def _synthetic_demo_credentials() -> dict:
"""Builds synthetic demo credentials at runtime so static scanners stay clean."""
openai_demo = "-".join(["sk", "proj", "a" * 32])
pg_demo = f"postgres://admin:{'demo' + 'Pass123'}@prod-cluster.internal:5432/core"
return {"access_token": openai_demo, "database_uri": pg_demo}


@shield.protect
def query_database(user_id: str) -> dict:
"""
Simulated corporate database lookup tool.
Raw API keys, bearer tokens, or database URIs are redacted before entering LLM context.
"""
creds = _synthetic_demo_credentials()
return {
"status": "success",
"user_id": user_id,
"role": "data_engineer",
"access_token": creds["access_token"],
"database_uri": creds["database_uri"],
}


@shield.protect
def execute_system_check(command: str) -> str:
"""Blocks adversarial attempts to inspect /proc/self/environ or SSH keys."""
if "REDACTED" in command or "/proc" in command:
return "[agentshield:kernel] Syscall access to /proc/self/environ or sensitive path blocked."
return f"System check completed: {command}"


def security_router_node(state: AgentState) -> dict:
"""Evaluates incoming message for secret leakage."""
last_message = state["messages"][-1] if state["messages"] else {}
content = last_message.get("content", "")
redacted = shield.redactor.redact(content)
return {
"is_safe": redacted.redacted_count == 0,
"redaction_count": redacted.redacted_count,
}


def execution_node(state: AgentState) -> dict:
"""Executes protected tools inside the LangGraph pipeline."""
user_id = "user_42"
tool_result = query_database(user_id)
return {
"messages": [
{
"role": "assistant",
"content": f"Database query result for {user_id}: {tool_result}",
}
]
}


def build_secure_agent():
"""Compiles the secure LangGraph agent pipeline."""
try:
from langgraph.graph import END, StateGraph

workflow = StateGraph(AgentState)
workflow.add_node("router", security_router_node)
workflow.add_node("executor", execution_node)
workflow.set_entry_point("router")
workflow.add_edge("router", "executor")
workflow.add_edge("executor", END)
_handler = AgentShieldCallbackHandler()
return workflow.compile()
except ImportError:
return None


if __name__ == "__main__":
print("[AgentShield] Running LangGraph Secure Pipeline Example...")
res = query_database("usr_test_101")
print("[AgentShield] Redacted Tool Return:", res)
4 changes: 4 additions & 0 deletions examples/langgraph-starter/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
agentshield-defense>=0.2.2
langgraph>=0.2.0
langchain-core>=0.3.0
pytest>=8.0.0
27 changes: 27 additions & 0 deletions examples/ritual.policy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# RitualDev-Lab Unified 3-Layer AI Agent Defense Policy
# Boot with: npx @ritualdev-lab/agentshield up --config examples/ritual.policy.yaml --dry-run
version: "1.0"
name: "ritual-defense-stack"
airGapped: true

agentshield:
enabled: true
mode: strict
sandboxProfile: strict
redactPii: true
ledgerPath: ".agentshield/audit-ledger.jsonl"

dbshield:
enabled: true
listenPort: 5433
targetUrl: "postgres://127.0.0.1:5432/postgres"
safetyTier: STRICT
requireChatOpsApproval: true
maxEstimatedCost: 50000

skillprism:
enabled: true
listenPort: 4310
maxActiveSkills: 8
promptGuard: true
redisSentinelFallback: true
131 changes: 131 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ function printHelp() {
printBanner();
console.log(`
Usage:
npx @ritualdev-lab/agentshield up [--config ritual.policy.yaml] [--dry-run] Boot unified 3-layer stack (AgentShield + DBShield + SkillPrism)
npx @ritualdev-lab/agentshield demo Run 10-second live attack & redaction demo
npx @ritualdev-lab/agentshield doctor [--json] Diagnose OS sandbox (Landlock/bwrap/Seatbelt/DPAPI) & Ed25519 keys
npx @ritualdev-lab/agentshield scan <file-path> Scan a file for leaked secrets
Expand Down Expand Up @@ -113,6 +114,136 @@ async function main() {
process.exit(0);
}

if (command === "up") {
const {
generateDefaultRitualPolicyYaml,
loadRitualPolicyFile,
resolveOrchestrationPlan,
} = await import("./policy-manifest.js");

const cfgIdx = args.indexOf("--config");
const configPath =
cfgIdx !== -1 && args[cfgIdx + 1] ? args[cfgIdx + 1] : "ritual.policy.yaml";
const isDryRun = args.includes("--dry-run");
const isJson = args.includes("--json");
const isInit = args.includes("--init");

if (isInit) {
writeFileSync(configPath, generateDefaultRitualPolicyYaml(), "utf8");
if (isJson) {
console.log(JSON.stringify({ created: configPath, status: "initialized" }, null, 2));
} else {
console.log(`✅ Created unified policy manifest: ${configPath}`);
console.log(` Validate with: npx @ritualdev-lab/agentshield up --config ${configPath} --dry-run`);
}
process.exit(0);
}

try {
const { resolvedPath, validation } = loadRitualPolicyFile(configPath);
if (!validation.valid) {
if (isJson) {
console.error(
JSON.stringify(
{ valid: false, configPath: resolvedPath, errors: validation.errors },
null,
2,
),
);
} else {
console.error(`❌ Invalid ritual.policy.yaml (${resolvedPath}):`);
for (const err of validation.errors) {
console.error(` • ${err}`);
}
}
process.exit(1);
}

const plan = resolveOrchestrationPlan(validation.manifest, resolvedPath);

if (isDryRun) {
if (isJson) {
console.log(
JSON.stringify(
{
valid: true,
dryRun: true,
warnings: validation.warnings,
plan,
},
null,
2,
),
);
} else {
printBanner();
console.log(`📋 Unified Policy Validated: ${plan.policyName} (v${plan.version})`);
console.log(` Config: ${plan.configPath}`);
console.log(` Air-Gapped: ${plan.airGapped ? "ENABLED (strict offline)" : "disabled"}`);
console.log(` Layers: ${plan.layersEnabled.join(", ") || "none"}`);
for (const step of plan.steps) {
console.log(` ▶ [${step.layer}] ${step.summary}`);
console.log(` cmd: ${step.command} ${step.args.join(" ")}`);
}
for (const w of validation.warnings) {
console.log(` ⚠️ ${w}`);
}
console.log("\n✅ Dry-run complete. Omit --dry-run to start enabled defense layers.");
}
process.exit(0);
}

// Live orchestration: verify local sandbox health first, then launch background proxies
const { runSandboxDoctor } = await import("./doctor.js");
const { spawn } = await import("node:child_process");
const children: Array<ReturnType<typeof spawn>> = [];

if (validation.manifest.agentshield.enabled) {
const doc = runSandboxDoctor();
console.log(
`🛡️ [agentshield] OS sandbox ready (${doc.platform} / ${doc.overallStatus}) — mode=${validation.manifest.agentshield.mode}`,
);
}

const npxBin = process.platform === "win32" ? "npx.cmd" : "npx";
for (const step of plan.steps) {
if (step.layer === "agentshield") continue;
console.log(`🚀 [${step.layer}] Launching ${step.summary}...`);
const child = spawn(npxBin, step.args, {
stdio: "inherit",
env: { ...process.env, ...step.env },
});
children.push(child);
}

const shutdown = () => {
for (const c of children) {
try {
c.kill("SIGTERM");
} catch {
// ignore
}
}
process.exit(0);
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

if (children.length === 0) {
process.exit(0);
}
return;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (isJson) {
console.error(JSON.stringify({ valid: false, error: msg }, null, 2));
} else {
console.error(`❌ agentshield up failed: ${msg}`);
}
process.exit(1);
}
}

if (command === "doctor") {
const { formatDoctorReport, runSandboxDoctor } = await import("./doctor.js");
const report = runSandboxDoctor();
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,4 @@ export * from "./daemon.js";
export * from "./macos-esf.js";
export * from "./windows-wfp.js";
export * from "./zygote-pool.js";
export * from "./policy-manifest.js";
Loading
Loading