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
15 changes: 13 additions & 2 deletions LAUNCHGUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,25 @@ documentation_url: https://ritualdev.in/agentshield
repository: https://github.com/RitualDev-Lab/AgentShield
homepage: https://ritualdev.in/agentshield
npm: "@ritualdev-lab/agentshield"
pypi: agentshield-defense
transport: stdio
command: npx
args: ["-y", "@ritualdev-lab/agentshield", "mcp"]
pricing:
type: freemium
license: Apache-2.0
environment_variables: []
environment_variables:
- name: AGENTSHIELD_AIR_GAPPED
description: Run strictly offline with zero external network connectivity (default: 1).
required: false
docs_url: https://ritualdev.in/agentshield#air-gapped
- name: AGENTSHIELD_LEDGER_KEY
description: Custom 32-byte secret key used to sign the append-only cryptographic audit ledger. Auto-generated on first run if omitted.
required: false
docs_url: https://ritualdev.in/agentshield#audit-ledger
- name: AGENTSHIELD_TOKEN
description: Optional enterprise organization or license token for central policy synchronization.
required: false
docs_url: https://ritualdev.in/agentshield#enterprise
---

# AgentShield MCP Security Server
Expand Down
7 changes: 7 additions & 0 deletions bin/mcp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env node
import { runAgentShieldMcpStdio } from "../dist/mcp-server.js";

runAgentShieldMcpStdio().catch((err) => {
console.error("Fatal error starting AgentShield MCP server:", err);
process.exit(1);
});
6 changes: 3 additions & 3 deletions examples/langgraph-starter/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
agentshield-defense>=0.2.2
langgraph>=0.2.0
langchain-core>=0.3.0
pytest>=8.0.0
langgraph>=0.2.70
langchain-core>=0.3.74
pytest>=8.3.4
14 changes: 12 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"type": "module",
"bin": {
"agentshield": "dist/cli.js",
"ashield": "dist/cli.js"
"ashield": "dist/cli.js",
"agentshield-mcp": "bin/mcp.js"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand All @@ -15,7 +16,16 @@
"./core-redactor": "./dist/core-redactor.js"
},
"icon": "assets/logo.png",
"files": ["dist", "README.md", "LICENSE", "SKILL.md", "action.yml", "assets/logo.png"],
"files": [
"dist",
"bin",
"README.md",
"LICENSE",
"SKILL.md",
"action.yml",
"assets/logo.png",
"LAUNCHGUIDE.md"
],
"repository": {
"type": "git",
"url": "git+https://github.com/RitualDev-Lab/AgentShield.git"
Expand Down
71 changes: 54 additions & 17 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ async function main() {
process.exit(0);
}

if (command === "mcp" || (args.length === 0 && !process.stdin.isTTY)) {
const { runAgentShieldMcpStdio } = await import("./mcp-server.js");
await runAgentShieldMcpStdio();
return;
}

if (
!command ||
command === "--help" ||
Expand All @@ -114,12 +120,6 @@ async function main() {
process.exit(0);
}

if (command === "mcp") {
const { runAgentShieldMcpStdio } = await import("./mcp-server.js");
await runAgentShieldMcpStdio();
return;
}

if (command === "up") {
const { generateDefaultRitualPolicyYaml, loadRitualPolicyFile, resolveOrchestrationPlan } =
await import("./policy-manifest.js");
Expand Down Expand Up @@ -262,7 +262,7 @@ async function main() {

if (command === "db-proxy" || command === "compact") {
const targetPkg =
command === "db-proxy" ? "@ritualdev-lab/dbshield" : "@ritualdev-lab/skillprism";
command === "db-proxy" ? "@ritualdev-lab/dbshield@0.2.1" : "@ritualdev-lab/skillprism@0.1.0";
const passthroughArgs = args.slice(1);
const delegatedArgs =
command === "db-proxy" && passthroughArgs.length === 0 ? ["proxy"] : passthroughArgs;
Expand All @@ -272,7 +272,8 @@ async function main() {
JSON.stringify(
{
routedCommand: command,
targetPackage: targetPkg,
targetPackage:
command === "db-proxy" ? "@ritualdev-lab/dbshield" : "@ritualdev-lab/skillprism",
execArgs: ["npx", "-y", targetPkg, ...delegatedArgs],
},
null,
Expand Down Expand Up @@ -336,7 +337,7 @@ async function main() {
}

const { EnterpriseComplianceBundleGenerator } = await import("./enterprise-bundle.js");
const { TamperEvidentLedger } = await import("./ledger.js");
const { TamperEvidentLedger, getOrCreateLocalLedgerKey } = await import("./ledger.js");

const ledgerPath = join(process.cwd(), ".agentshield", "audit.ledger.jsonl");
const ledger = new TamperEvidentLedger(ledgerPath);
Expand All @@ -350,7 +351,7 @@ async function main() {
const bundle = EnterpriseComplianceBundleGenerator.generateBundle(
[],
ledgerEntries,
process.env.AGENTSHIELD_LEDGER_KEY || "agentshield-tamper-evident-salt-v1",
process.env.AGENTSHIELD_LEDGER_KEY || getOrCreateLocalLedgerKey(),
{ organizationName: orgName, frameworks },
);

Expand Down Expand Up @@ -527,13 +528,34 @@ Direct verification link:

const orgIdx = args.indexOf("--org");
if (orgIdx !== -1 && args[orgIdx + 1]) orgId = args[orgIdx + 1];
orgId = orgId || process.env.AGENTSHIELD_ORG_ID || "";

const tokenIdx =
args.indexOf("--token") !== -1 ? args.indexOf("--token") : args.indexOf("--key");
if (tokenIdx !== -1 && args[tokenIdx + 1]) token = args[tokenIdx + 1];
if (tokenIdx !== -1 && args[tokenIdx + 1]) {
console.warn(
"⚠️ Security Notice: Passing tokens via CLI arguments can expose them in process listings (ps). We recommend setting AGENTSHIELD_TOKEN env var or using 'agentshield login --stdin'.",
);
token = args[tokenIdx + 1];
}

const licenseIdx = args.indexOf("--license");
if (licenseIdx !== -1 && args[licenseIdx + 1]) token = args[licenseIdx + 1];
if (licenseIdx !== -1 && args[licenseIdx + 1]) {
console.warn(
"⚠️ Security Notice: Passing license keys via CLI arguments can expose them in process listings (ps). We recommend setting AGENTSHIELD_LICENSE_KEY env var or using 'agentshield login --stdin'.",
);
token = args[licenseIdx + 1];
}

if (args.includes("--stdin") && !token) {
try {
token = readFileSync(0, "utf-8").trim();
} catch {
// silent fallback
}
}

token = token || process.env.AGENTSHIELD_TOKEN || process.env.AGENTSHIELD_LICENSE_KEY || "";

if (!orgId && token) {
if (token.startsWith("ASHIELD-PRO-")) {
Expand Down Expand Up @@ -701,8 +723,15 @@ Direct verification link:
const apiKey =
(keyIdx !== -1 ? args[keyIdx + 1] : undefined) ||
process.env.DD_API_KEY ||
process.env.SPLUNK_TOKEN ||
"test_api_key_token";
process.env.SPLUNK_TOKEN;

if ((target === "datadog" || target === "splunk") && !apiKey) {
console.error(
`❌ Error: API key or token is required for ${target.toUpperCase()} SIEM test.\n` +
` Please provide --key <key> or set ${target === "datadog" ? "DD_API_KEY" : "SPLUNK_TOKEN"} env var.`,
);
process.exit(1);
}

const sampleFinding = {
file: "src/autonomous_agent.py",
Expand Down Expand Up @@ -748,7 +777,15 @@ Direct verification link:
);
}
} else {
const webhookUrl = targetUrl || "https://ritualdev.in/api/v1/telemetry";
const webhookUrl = targetUrl || process.env.SIEM_WEBHOOK_URL;
if (!webhookUrl) {
console.error(
"❌ Error: Missing target webhook URL for SIEM testing.\n" +
" Please provide --url <url> or set SIEM_WEBHOOK_URL environment variable.\n" +
" (AgentShield is 100% local by default and never dispatches telemetry without an explicit target endpoint).",
);
process.exit(1);
}
const result = await SiemExporter.forwardToWebhook(testEvent, { url: webhookUrl, format });
const latency = Date.now() - startTime;
if (result.delivered) {
Expand Down Expand Up @@ -802,7 +839,7 @@ Direct verification link:
const outPath = outIdx !== -1 ? args[outIdx + 1] : null;

const { EnterpriseComplianceBundleGenerator } = await import("./enterprise-bundle.js");
const { TamperEvidentLedger } = await import("./ledger.js");
const { TamperEvidentLedger, getOrCreateLocalLedgerKey } = await import("./ledger.js");

// Load ledger entries from local workspace ledger if available
const ledgerPath = join(process.cwd(), ".agentshield", "audit.ledger.jsonl");
Expand All @@ -817,7 +854,7 @@ Direct verification link:
const bundle = EnterpriseComplianceBundleGenerator.generateBundle(
[],
ledgerEntries,
process.env.AGENTSHIELD_LEDGER_KEY || "agentshield-tamper-evident-salt-v1",
process.env.AGENTSHIELD_LEDGER_KEY || getOrCreateLocalLedgerKey(),
{ organizationName: orgName },
);

Expand Down
9 changes: 3 additions & 6 deletions src/enterprise-bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from "./compliance.js";
import type { FleetAgentTelemetryReport } from "./control-plane.js";
import { AgentShieldEngine } from "./engine.js";
import { type AuditLedgerEntry, TamperEvidentLedger } from "./ledger.js";
import { type AuditLedgerEntry, TamperEvidentLedger, getOrCreateLocalLedgerKey } from "./ledger.js";
import type { DetectedSecret } from "./types.js";

export interface ComplianceBundleOptions {
Expand Down Expand Up @@ -83,8 +83,7 @@ export class EnterpriseComplianceBundleGenerator {
public static generateBundle(
fleetReports: FleetAgentTelemetryReport[],
allLedgerEntries: AuditLedgerEntry[] = [],
ledgerSigningKey: string = process.env.AGENTSHIELD_LEDGER_KEY ||
"agentshield-tamper-evident-salt-v1",
ledgerSigningKey: string = process.env.AGENTSHIELD_LEDGER_KEY || getOrCreateLocalLedgerKey(),
options: ComplianceBundleOptions = { organizationName: "Enterprise Organization" },
): ComplianceAttestationPackage {
const frameworks = options.frameworks || ["soc2", "pci_dss", "hipaa", "iso27001"];
Expand Down Expand Up @@ -169,9 +168,7 @@ export class EnterpriseComplianceBundleGenerator {
: auditReport.status;
const complianceScore = isCorrupted ? 0 : auditReport.score;

const isDefaultKey =
ledgerSigningKey === "agentshield-tamper-evident-salt-v1" ||
!process.env.AGENTSHIELD_LEDGER_KEY;
const isDefaultKey = !ledgerSigningKey || ledgerSigningKey.length < 16;
const signingKeyTrust: "AUTHENTICATED_KEY" | "DEFAULT_INSECURE_SALT" = isDefaultKey
? "DEFAULT_INSECURE_SALT"
: "AUTHENTICATED_KEY";
Expand Down
52 changes: 48 additions & 4 deletions src/ledger.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHmac, sign, verify } from "node:crypto";
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { createHmac, randomBytes, sign, verify } from "node:crypto";
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import {
type KeystoreBackend,
Expand Down Expand Up @@ -39,6 +40,49 @@ export interface LedgerOptions {
legacyHmacOnly?: boolean;
}

let cachedLedgerKey: string | null = null;

/**
* Resolves or generates a secure per-installation ledger secret key.
* Never falls back to a public static salt.
*/
export function getOrCreateLocalLedgerKey(): string {
if (process.env.AGENTSHIELD_LEDGER_KEY) {
return process.env.AGENTSHIELD_LEDGER_KEY;
}
if (cachedLedgerKey) {
return cachedLedgerKey;
}

const globalDir = join(homedir(), ".agentshield");
const keyFile = join(globalDir, "ledger.key");

try {
if (existsSync(keyFile)) {
const savedKey = readFileSync(keyFile, "utf-8").trim();
if (savedKey.length >= 32) {
cachedLedgerKey = savedKey;
return savedKey;
}
}
} catch {
// fallback to generation
}

// Generate per-installation cryptographically secure random key
const generated = randomBytes(32).toString("hex");
cachedLedgerKey = generated;
try {
if (!existsSync(globalDir)) {
mkdirSync(globalDir, { recursive: true, mode: 0o700 });
}
writeFileSync(keyFile, generated, { encoding: "utf-8", mode: 0o600 });
} catch {
// If filesystem write fails, return in-memory generated key
}
return generated;
}

/**
* Cryptographic Tamper-Evident Write-Ahead Audit Ledger:
* Stores append-only audit events with sequential hash-chaining AND asymmetric Ed25519 signatures
Expand All @@ -57,7 +101,7 @@ export class TamperEvidentLedger {

constructor(
ledgerPath: string = join(process.cwd(), ".agentshield", "audit.ledger"),
secretKey: string = process.env.AGENTSHIELD_LEDGER_KEY || "agentshield-tamper-evident-salt-v1",
secretKey: string = getOrCreateLocalLedgerKey(),
options: LedgerOptions = {},
) {
this.ledgerPath = ledgerPath;
Expand Down Expand Up @@ -274,7 +318,7 @@ export class TamperEvidentLedger {
*/
public static verifyEntries(
entries: AuditLedgerEntry[],
secretKey: string = process.env.AGENTSHIELD_LEDGER_KEY || "agentshield-tamper-evident-salt-v1",
secretKey: string = getOrCreateLocalLedgerKey(),
publicKeyPem?: string,
): LedgerVerificationResult {
let prevHash = TamperEvidentLedger.GENESIS_HASH;
Expand Down
8 changes: 4 additions & 4 deletions src/policy-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,11 +375,11 @@ export function resolveOrchestrationPlan(
layersEnabled.push("dbshield");
steps.push({
layer: "dbshield",
packageName: "@ritualdev-lab/dbshield",
packageName: "@ritualdev-lab/dbshield@0.2.1",
command: "npx",
args: [
"-y",
"@ritualdev-lab/dbshield",
"@ritualdev-lab/dbshield@0.2.1",
"proxy",
"--port",
String(manifest.dbshield.listenPort),
Expand All @@ -402,11 +402,11 @@ export function resolveOrchestrationPlan(
layersEnabled.push("skillprism");
steps.push({
layer: "skillprism",
packageName: "@ritualdev-lab/skillprism",
packageName: "@ritualdev-lab/skillprism@0.1.0",
command: "npx",
args: [
"-y",
"@ritualdev-lab/skillprism",
"@ritualdev-lab/skillprism@0.1.0",
"proxy",
"--port",
String(manifest.skillprism.listenPort),
Expand Down
4 changes: 2 additions & 2 deletions src/zygote-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export interface ZygoteTelemetry {
p50Micros: number;
p90Micros: number;
p99Micros: number;
p99TargetMet: boolean; // true if P99 < 100 microseconds (0.10ms)
p99TargetMet: boolean; // true if P99 < 500 microseconds (0.50ms)
ebpfStatus?: EbpfLsmStatus;
}

Expand Down Expand Up @@ -354,7 +354,7 @@ export class ZygoteProcessPool extends EventEmitter {
p50Micros,
p90Micros,
p99Micros,
p99TargetMet: p99Micros < 100, // < 100μs (0.10ms)
p99TargetMet: p99Micros < 500, // < 500μs (0.50ms) SLA
ebpfStatus: this.ebpfController?.getStatus(),
};
}
Expand Down
Loading
Loading