actionfence
CLAUDE.md9 starsChanged 7 months agoMITView on GitHub
ActionFence is an embeddable AI action firewall for MCP servers and APIs. It enforces policies, manages spend caps, rate limits, and generates signed receipts for all agent actions. The library supports both MCP and Express/HTTP middleware, with pluggable storage backends (SQLite, PostgreSQL, or in-memory). Requires Node.js >= 20.0.0
- Installs packages
In this repository3 other files it gives its agents.
- .github/copilot-instructions.mdCopilot instructions
- llms-full.txtllms.txt
- llms.txtllms.txt
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
24 rules. About 0 are common, 5 are distinctive, and 19 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
19
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 56
sqlite-adapter.ts: Default SQLite backend (zero-config, single-instance)
- Very specific: line 94
Capability Check: If JWT includes capabilities claim, verify action is in the list
- Very specific: line 95
Action Rule Check: Look up action in policy; verify allowed flag and identity tier requirement
- Distinctive: line 96
Rate Limiting: Check request/transaction counts against limits
- Very specific: line 102
When both the per-agent mutex (GuardEngine.evaluate()) and the ReceiptStore insert mutex are needed, the agent mutex MUST be acquired first …
- Very specific: line 117
When session_max is configured but session_timeout_minutes is omitted → defaults to 60 minutes
- Very specific: line 118
When session_timeout_minutes is explicitly 0 → idle timeout is disabled
- Distinctive: line 119
When neither is configured → no timeout
- Distinctive: line 151
Run a single test file:
- Very specific: line 158
Fake timers: Use vi.useFakeTimers() / vi.setSystemTime() for time-sensitive spend-tracker and rate-limiter tests
- Very specific: line 160
Concurrency tests: Use Promise.all() with controlled async barriers to verify mutex behavior
- Very specific: line 166
Update src/types/policy.ts to add the field to ActionRule
- Very specific: line 167
Update schemas/guard-policy.schema.json to include the field in the JSON schema
- Very specific: line 168
Update src/core/policy-evaluator.ts to evaluate the new field
- Very specific: line 169
Add tests in tests/core/policy-evaluator.test.ts
- Distinctive: line 170
Update README.md with the new field in the Policy Reference table
- Very specific: line 174
Update SpendLimitsConfig in src/types/policy.ts
- Very specific: line 175
Update schemas/guard-policy.schema.json under spend_limits.properties
- Very specific: line 176
Update src/core/spend-tracker.ts to enforce/track the new field
- Very specific: line 177
If the field affects evaluation, update resolveSpendLimitReason() in src/middleware/engine.ts
- Very specific: line 178
Add tests in tests/core/spend-tracker.test.ts and tests/middleware/engine.test.ts
- Very specific: line 182
Create src/storage/my-adapter.ts implementing StorageAdapter interface
- Very specific: line 184
Add adapter type to StorageConfig union in src/types/config.ts
- Distinctive: line 186
Update README.md with setup instructions
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
ActionFence is an embeddable AI action firewall for MCP servers and APIs. It enforces policies, manages spend caps, rate limits, and generates signed receipts for all agent actions. The library supports both MCP and Express/HTTP middleware, with pluggable storage backends (SQLite, PostgreSQL, or in-memory).
Requires Node.js >= 20.0.0
Build & Development Commands
# Install dependencies
npm install
# Development
npm run dev # Watch mode with tsup
npm run typecheck # TypeScript type checking
npm run lint # ESLint check
npm run format # Prettier format
# Testing
npm test # Run all tests once
npm test:watch # Watch mode for tests
npm test:coverage # Coverage report
# Build
npm run build # Build ESM and CJS bundles
# CLI tools
npx actionfence init # Create guard-policy.json
npx actionfence validate guard-policy.json # Validate policy
npx actionfence simulate guard-policy.json --action X # Dry-run simulationArchitecture
Core Modules (src/core/)
- policy-loader.ts: Loads and validates
guard-policy.jsonfiles; supports file watching for hot-reload - policy-evaluator.ts: Evaluates whether an action is allowed based on policy rules, identity tier, and capabilities
- identity-reader.ts: Resolves agent identity from requests; supports JWT verification via JWKS. Exports
sanitizeIdentity()to striprawTokenfromAgentIdentity→SafeAgentIdentity - rate-limiter.ts: Tracks request and transaction rates; enforces per-minute and per-day limits
- spend-tracker.ts: Tracks cumulative spend across sessions, days, and rolling windows; enforces spend caps. Supports idle-timeout session resets and hot-reload via
updateConfig() - receipt-signer.ts: Signs and hash-chains receipts using HMAC-SHA256
- receipt-store.ts: Persists and verifies receipts; delegates to storage adapters
Utilities (src/utils/)
- async-mutex.ts: Simple async mutex for serializing concurrent operations. Tracks waiter count via
hasWaitersso callers can safely evict the mutex from per-key pools without breaking queued waiters. Used byGuardEnginefor per-agent evaluation serialization.
Storage Adapters (src/storage/)
- adapter.ts: Abstract
StorageAdapterinterface andReceiptFilterstype for receipt queries - sqlite-adapter.ts: Default SQLite backend (zero-config, single-instance)
- postgres-adapter.ts: PostgreSQL backend for multi-instance deployments
- memory-adapter.ts: In-memory storage for testing
Middleware (src/middleware/)
- engine.ts: Core guard engine; orchestrates policy evaluation, rate limiting, spend tracking, and receipt signing. Uses per-agent
AsyncMutexto prevent TOCTOU race conditions on concurrent evaluations - mcp.ts: MCP server integration via
withGuard() - express.ts: Express/HTTP middleware via
guard() - simulation.ts: Dry-run mode that evaluates policies without executing handlers or storing receipts. Returns
SimulationPreviewobjects
CLI (src/cli/)
- index.ts: Entry point; routes to init, validate, or simulate commands
- init.ts: Scaffolds a new
guard-policy.json - validate.ts: Validates policy against schema
- simulate.ts: Runs policy evaluation in dry-run mode with CLI output
Types (src/types/)
- policy.ts: Policy schema types (actions, rules, rate limits, spend limits including
session_timeout_minutes) - identity.ts: Identity classification,
AgentIdentity,SafeAgentIdentity(withoutrawToken), andIdentityReaderLikeinterface - decision.ts:
DecisionStatus('PASSED' | 'BLOCKED') andEvaluationDecision - receipt.ts: Receipt structure, verification types, and
ReceiptVerificationFailureReasonunion - config.ts:
GuardOptionswith DI hooks (actionResolver,spendExtractor,transactionResolver,onDecision, etc.) andStorageConfigunion - spend.ts:
SpendSnapshotandSpendRecordResult - errors.ts:
PolicyValidationError,PolicyLoadError,IdentityError— each with a uniquecodeproperty
Reporters (src/reporters/)
- console.ts: Formats and logs decisions to console (used in CLI and optional in middleware)
Key Concepts
Policy Evaluation Flow
- Identity Resolution: Extract and verify agent identity (anonymous → token → verified)
- Per-Agent Mutex: Acquire an
AsyncMutexkeyed byagentIdto serialize the remaining steps - Capability Check: If JWT includes
capabilitiesclaim, verify action is in the list - Action Rule Check: Look up action in policy; verify
allowedflag andidentitytier requirement - Rate Limiting: Check request/transaction counts against limits
- Spend Tracking: Extract spend amount; check against per-action, session, daily, and rolling-window caps
- Receipt Generation: Sign and store decision (unless in simulation mode)
Concurrency & Lock Ordering
When both the per-agent mutex (GuardEngine.evaluate()) and the ReceiptStore insert mutex are needed, the agent mutex MUST be acquired first to prevent deadlocks. ReceiptStore.insert() acquires its internal mutex inside the agent-mutex critical section.
Identity Tiers
- anonymous: No credentials
- token: Bearer token present but not verified
- verified: JWT passed JWKS signature verification
SafeAgentIdentity
AgentIdentity contains a rawToken field with the bearer JWT. SafeAgentIdentity is Omit<AgentIdentity, 'rawToken'> — used in GuardEvaluationResult.identity so callers never see raw credentials. Use sanitizeIdentity() from identity-reader.ts to convert.
Session Idle Timeout
SpendTracker supports idle-timeout-based session resets via session_timeout_minutes in SpendLimitsConfig:
- When
session_maxis configured butsession_timeout_minutesis omitted → defaults to 60 minutes - When
session_timeout_minutesis explicitly0→ idle timeout is disabled - When neither is configured → no timeout
updateConfig()supports hot-reload of the timeout value without resetting tracked state
Storage Modes
- SQLite (default): Single-instance, zero-config, file-based (
.actionfence/receipts.db) - PostgreSQL: Multi-instance, requires
pgdriver andDATABASE_URL - Memory: Testing only
GuardOptions Callbacks
actionResolver(toolName, params): Map a tool name + params to a policy action name. Defaults to usingtoolNamedirectlyspendExtractor(params): Extract a spend amount from tool parameters. Returnnullfor no spendtransactionResolver(toolName, params, decision): Override whether a passed action counts toward the transaction-per-day limit. Defaults totruewhenspendAmount !== null || requiresHumanApprovalonDecision(decision): Callback fired after every evaluation decision (for telemetry, logging, etc.)payloadRedactor(params): Optional. Redact sensitive fields from tool params before persisting in receipts. The receipt hash uses the original params (integrity); only the storedpayload_jsonis redacted (privacy). Must return a sanitized copy — do not mutate the input.maxPayloadBytes: Optional number (default: 65536). Maximum byte length for persistedpayload_json. Payloads exceeding this are replaced with a truncation marker containing the original hash.
Testing
Tests are organized by module:
tests/
├── core/ # Policy evaluator, identity reader, rate limiter, spend tracker
├── middleware/ # MCP and Express integration, engine concurrency tests
├── storage/ # Storage adapter tests
├── cli/ # CLI command tests
├── reporters/ # Console reporter tests
└── fixtures/ # Shared test data (policies, identities, receipts)Run a single test file:
npm test -- tests/core/policy-evaluator.test.tsTest Patterns
- Fake timers: Use
vi.useFakeTimers()/vi.setSystemTime()for time-sensitive spend-tracker and rate-limiter tests - Inline helpers: Tests use local factory functions (e.g.,
makeIdentity()) rather than centralized utilities - Concurrency tests: Use
Promise.all()with controlled async barriers to verify mutex behavior
Common Tasks
Adding a New Policy Rule Field
- Update
src/types/policy.tsto add the field toActionRule - Update
schemas/guard-policy.schema.jsonto include the field in the JSON schema - Update
src/core/policy-evaluator.tsto evaluate the new field - Add tests in
tests/core/policy-evaluator.test.ts - Update README.md with the new field in the Policy Reference table
Adding a New Spend Limits Field
- Update
SpendLimitsConfiginsrc/types/policy.ts - Update
schemas/guard-policy.schema.jsonunderspend_limits.properties - Update
src/core/spend-tracker.tsto enforce/track the new field - If the field affects evaluation, update
resolveSpendLimitReason()insrc/middleware/engine.ts - Add tests in
tests/core/spend-tracker.test.tsandtests/middleware/engine.test.ts
Adding a New Storage Adapter
- Create
src/storage/my-adapter.tsimplementingStorageAdapterinterface - Export from
src/storage/index.ts - Add adapter type to
StorageConfigunion insrc/types/config.ts - Add tests in
tests/storage/my-adapter.test.ts - Update README.md with setup instructions
Modifying Spend Tracking Logic
Spend tracking is split across:
- spend-tracker.ts: Accumulates spend across windows and enforces caps; manages idle-timeout session resets
- policy-evaluator.ts: Checks spend against policy limits
- engine.ts: Extracts spend from request via
spendExtractorcallback; callsspendTracker.updateConfig()on hot-reload
Changes to spend logic should be tested in tests/core/spend-tracker.test.ts and tests/middleware/engine.test.ts.
Build Output
- dist/index.js: ESM export (main library)
- dist/index.cjs: CommonJS export
- dist/cli.js: CLI entry point
- dist/*.d.ts: TypeScript declarations
The build is configured in tsup.config.ts to produce both formats with source maps and type definitions.
Linting & Formatting
- ESLint: Strict TypeScript rules; no unused variables/parameters (unless prefixed with
_) - Prettier: Configured in
.prettierrc - TypeScript: Strict mode enabled;
noUnusedLocalsandnoUnusedParametersenforced
Run before committing:
npm run format && npm run lint && npm run typecheckDependencies
Core
- ajv: JSON schema validation (for policy validation)
- jose: JWT verification and signing
- chalk: Colored console output (CLI)
- better-sqlite3: SQLite storage backend (bundled in dist)
Optional (Peer)
- @modelcontextprotocol/sdk: For MCP server integration
- pg: For PostgreSQL storage adapter
Dev
- vitest: Test runner
- typescript: Type checking
- eslint: Linting
- prettier: Formatting
- tsup: Build tool
Notes
- Receipts are hash-chained and HMAC-signed; verification is append-only and cryptographically sound
- SQLite storage is single-instance; use PostgreSQL for horizontally-scaled deployments
- Policy hot-reload is opt-in via
watchPolicy: truein guard options - Simulation mode runs the full pipeline without side effects (no handler execution, no receipt storage)
- The CLI is a separate entry point (
dist/cli.js) and can be used standalone - JWKS verification fails closed: any error (network, DNS, OOM) returns
ANONYMOUS_IDENTITY— never falls back totokentier - Per-agent mutex in
GuardEngineprevents TOCTOU race conditions on concurrent spend/rate-limit checks
Security Hardening (v0.2.0)
- HMAC key minimum: Signing secrets shorter than 16 bytes are rejected at startup
- Payload redaction:
payloadRedactorandmaxPayloadBytesoptions prevent PII retention in receipts - Atomic Postgres inserts:
PostgresAdapter.insertAtomic()prevents hash-chain fork under concurrent writers (advisory lock) - Path traversal guard:
loadPolicy()rejects paths that resolve outsideprocess.cwd() - Agent ID sanitization: JWT
subandazp/ownerclaims are stripped of control characters and length-capped at 256 - Spend/receipt consistency: In enforce mode, spend is committed before receipt insertion so spend caps remain conservative if receipt persistence fails. Receipt insert failures are logged and the evaluation returns
receipt: null - Map eviction:
SpendTracker(50k cap, 5 min cleanup),RateLimiter(50k cap, 60s cleanup), andGuardEngine.agentMutexes(10k cap, on-access eviction) prevent unbounded memory growth - Postgres pool lifecycle:
engine.dispose()explicitly closes any Postgres adapter the engine created - Credential masking: Postgres connection errors mask passwords in
postgres://connection strings - Key file permissions: Legacy key migration forces
0o600permissions (best-effort on non-POSIX)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

