openclawSecure key management for AI agents. Use when handling private keys, API secrets, wallet credentials, or when building systems that need agent-controlled funds. Covers secure storage, session keys, leak prevention, and prompt injection defense.
Install via ClawdBot CLI:
clawdbot install zscole/openclawSecure key management patterns for AI agents handling private keys and secrets. Designed to prevent:
op)references/secure-storage.md - 1Password patterns for agent secretsreferences/session-keys.md - ERC-4337 delegated access patternsreferences/leak-prevention.md - Pre-commit hooks and output sanitizationreferences/prompt-injection-defense.md - Input validation and output filtering# Retrieve key at runtime via 1Password
PRIVATE_KEY=$(op read "op://Agents/my-agent-wallet/private-key")
# Use environment injection (key never touches disk)
op run --env-file=.env.tpl -- node agent.js
# Use session keys with bounded permissions
# (delegate specific capabilities, not full wallet access)
# NEVER store keys in files
echo "PRIVATE_KEY=0x123..." > .env
# NEVER log or print keys
console.log("Key:", privateKey)
# NEVER store keys in memory/journal files
# Even in "private" agent memory - these can be exfiltrated
# NEVER trust unvalidated input near key operations
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā AI Agent ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā Session Key (time/value bounded) ā
ā - Expires after N hours ā
ā - Spending cap per operation ā
ā - Whitelist of allowed contracts ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā 1Password / Secret Manager ā
ā - Agent retrieves session key at runtime ā
ā - Never stores full private key ā
ā - Audit log of all accesses ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā ERC-4337 Smart Account ā
ā - Programmable permissions ā
ā - Recovery without private key exposure ā
ā - Multi-sig for high-value operations ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā Operator (Human) ā
ā - Holds master key in hardware wallet ā
ā - Issues/revokes session keys ā
ā - Monitors agent activity ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# Create dedicated vault (via 1Password app or CLI)
op vault create "Agent-Wallets" --description "AI agent wallet credentials"
# Store agent session key (not master key!)
op item create \
--vault "Agent-Wallets" \
--category "API Credential" \
--title "trading-bot-session" \
--field "session-key[password]=0xsession..." \
--field "expires=2026-02-15T00:00:00Z" \
--field "spending-cap=1000 USDC" \
--field "allowed-contracts=0xDEX1,0xDEX2"
import subprocess
import json
def get_session_key(item_name: str) -> dict:
"""Retrieve session key from 1Password at runtime."""
result = subprocess.run(
["op", "item", "get", item_name, "--vault", "Agent-Wallets", "--format", "json"],
capture_output=True, text=True, check=True
)
item = json.loads(result.stdout)
# Extract fields
fields = {f["label"]: f.get("value") for f in item.get("fields", [])}
# Validate session hasn't expired
from datetime import datetime
expires = datetime.fromisoformat(fields.get("expires", "2000-01-01"))
if datetime.now() > expires:
raise ValueError("Session key expired - request new key from operator")
return {
"session_key": fields.get("session-key"),
"expires": fields.get("expires"),
"spending_cap": fields.get("spending-cap"),
"allowed_contracts": fields.get("allowed-contracts", "").split(",")
}
# ā BAD - Key in logs
logger.info(f"Using key: {session_key}")
# ā
GOOD - Redacted identifier
logger.info(f"Using session key: {session_key[:8]}...{session_key[-4:]}")
# ā BAD - Key in memory file
with open("memory/today.md", "a") as f:
f.write(f"Session key: {session_key}")
# ā
GOOD - Reference only
with open("memory/today.md", "a") as f:
f.write(f"Session key: [stored in 1Password: trading-bot-session]")
Before any agent output (chat, logs, file writes), scan for key patterns:
import re
KEY_PATTERNS = [
r'0x[a-fA-F0-9]{64}', # ETH private keys
r'sk-[a-zA-Z0-9]{48,}', # OpenAI keys
r'sk-ant-[a-zA-Z0-9\-_]{80,}', # Anthropic keys
r'gsk_[a-zA-Z0-9]{48,}', # Groq keys
r'[A-Za-z0-9+/]{40,}={0,2}', # Base64 encoded (suspiciously long)
]
def sanitize_output(text: str) -> str:
"""Remove potential secrets from output."""
for pattern in KEY_PATTERNS:
text = re.sub(pattern, '[REDACTED]', text)
return text
# Apply to ALL agent outputs
def send_message(content: str):
content = sanitize_output(content)
# ... send to chat/log/file
Install this hook to prevent accidental commits of secrets:
#!/bin/bash
# .git/hooks/pre-commit
PATTERNS=(
'0x[a-fA-F0-9]{64}'
'sk-[a-zA-Z0-9]{48,}'
'sk-ant-api'
'PRIVATE_KEY='
'gsk_[a-zA-Z0-9]{48,}'
)
for pattern in "${PATTERNS[@]}"; do
if git diff --cached | grep -qE "$pattern"; then
echo "ā Potential secret detected matching: $pattern"
echo " Remove secrets before committing!"
exit 1
fi
done
# Secrets
.env
.env.*
*.pem
*.key
secrets/
credentials/
# Agent state that might contain secrets
memory/*.json
wallet-state.json
session-keys/
Before processing any user input that touches wallet operations:
DANGEROUS_PATTERNS = [
r'ignore.*(previous|above|prior).*instructions',
r'reveal.*(key|secret|password|credential)',
r'output.*(key|secret|private)',
r'print.*(key|secret|wallet)',
r'show.*(key|secret|password)',
r'what.*(key|secret|password)',
r'tell.*me.*(key|secret)',
r'disregard.*rules',
r'system.*prompt',
r'jailbreak',
r'dan.*mode',
]
def validate_input(text: str) -> bool:
"""Check for prompt injection attempts."""
text_lower = text.lower()
for pattern in DANGEROUS_PATTERNS:
if re.search(pattern, text_lower):
return False
return True
def process_wallet_request(user_input: str):
if not validate_input(user_input):
return "I can't help with that request."
# ... proceed with wallet operation
ALLOWED_WALLET_OPERATIONS = {
"check_balance": lambda: get_balance(),
"send_usdc": lambda to, amount: send_usdc(to, amount) if amount < DAILY_LIMIT else deny(),
"swap": lambda: swap_tokens() if within_limits() else deny(),
}
def execute_wallet_operation(operation: str, **kwargs):
"""Execute only explicitly allowed operations."""
if operation not in ALLOWED_WALLET_OPERATIONS:
raise ValueError(f"Operation '{operation}' not allowed")
return ALLOWED_WALLET_OPERATIONS[operation](**kwargs)
For agents needing on-chain access, use session keys instead of raw private keys.
See references/session-keys.md for full implementation details including:
# Emergency: Revoke 1Password item
op item delete "compromised-session-key" --vault "Agent-Wallets"
# Rotate to new session key
op item create --vault "Agent-Wallets" --category "API Credential" \
--title "trading-bot-session-v2" ...
Problem: Agents store keys in memory/*.md for "persistence"
# memory/2026-02-07.md
## Test Wallet
- Private key: 0x9f01dad551039daad3a8c4e43a32035bdd4da54e7b4292268be16e913b0b3e56
Fix: Store reference only: Private key: [1Password: test-wallet-session]
Problem: .env.example contains real keys
# .env.example
PRIVATE_KEY=sk-ant-api03-real-key-here... # "for testing"
Fix: Use obviously fake placeholders: PRIVATE_KEY=your-key-here
Problem: Error handling exposes keys
try:
sign_transaction(private_key, tx)
except Exception as e:
logger.error(f"Failed with key {private_key}: {e}") # ā
Fix: Never include credentials in error context
Problem: Hardcoded test keys make it to main branch
Fix: Use separate test vault, CI checks for key patterns
When running as an OpenClaw agent:
Example TOOLS.md entry:
### Agent Wallet
- Address: 0xABC123...
- Session key: [1Password: my-agent-session]
- Permissions: USDC transfers < 100, approved DEX only
- Expires: 2026-02-15
- To rotate: Ask operator via Telegram
Generated Mar 1, 2026
An AI agent executes trades on decentralized exchanges using session keys with spending caps and contract whitelists. It retrieves keys from 1Password at runtime to prevent exposure in logs or memory, ensuring secure, automated trading without full wallet access.
A SaaS platform uses this skill to manage API keys for third-party services like OpenAI or payment gateways. Keys are stored in 1Password and injected at runtime, reducing risk of leaks in code repositories and enabling audit trails for compliance.
DevOps pipelines integrate this skill to securely access credentials for cloud services, databases, and deployment tools. It prevents keys from being stored in environment files or logs, using 1Password CLI for runtime retrieval and output sanitization.
An AI agent processes sensitive patient data by accessing encrypted storage keys via 1Password. Session keys with time limits ensure compliance with regulations like HIPAA, while leak prevention techniques guard against accidental exposure in outputs.
In supply chain management, agents use this skill to handle credentials for IoT devices and logistics APIs. Secure key retrieval and delegated access patterns prevent unauthorized operations, with spending caps controlling transaction limits.
Offer a subscription-based service that provides AI agents with secure key management, including 1Password integration and session key issuance. Revenue comes from monthly fees per agent or transaction volume, targeting businesses needing compliance and leak prevention.
Provide consulting services to help companies integrate this skill into their existing AI systems, focusing on secure architecture setup and training. Revenue is generated through project-based fees and ongoing support contracts for maintenance.
Develop a platform where businesses can deploy pre-configured AI agents with built-in secure key management. Revenue streams include licensing fees for the platform and a percentage of transactions processed through agent-controlled wallets.
š¬ Integration Tip
Ensure the 1Password CLI ('op') is installed and configured before integration, and implement output sanitization early to prevent key leaks in logs or agent responses.
Set up and use 1Password CLI (op). Use when installing the CLI, enabling desktop app integration, signing in (single or multi-account), or reading/injecting/running secrets via op.
Security-first skill vetting for AI agents. Use before installing any skill from ClawdHub, GitHub, or other sources. Checks for red flags, permission scope, and suspicious patterns.
Perform a comprehensive read-only security audit of Clawdbot's own configuration. This is a knowledge-based skill that teaches Clawdbot to identify hardening opportunities across the system. Use when user asks to "run security check", "audit clawdbot", "check security hardening", or "what vulnerabilities does my Clawdbot have". This skill uses Clawdbot's internal capabilities and file system access to inspect configuration, detect misconfigurations, and recommend remediations. It is designed to be extensible - new checks can be added by updating this skill's knowledge.
Use when reviewing code for security vulnerabilities, implementing authentication flows, auditing OWASP Top 10, configuring CORS/CSP headers, handling secrets, input validation, SQL injection prevention, XSS protection, or any security-related code review.
Security check for ClawHub skills powered by Koi. Query the Clawdex API before installing any skill to verify it's safe.
Scan Clawdbot and MCP skills for malware, spyware, crypto-miners, and malicious code patterns before you install them. Security audit tool that detects data exfiltration, system modification attempts, backdoors, and obfuscation techniques.