Skip to main content
Glama
OpenGuard-Solana

OpenGuard-Solana

README.md
# OpenGuard-Solana

A fail-closed transaction firewall for Solana AI agents. It sits between the agent and the signer, decodes every transaction the agent wants signed, and returns one of three verdicts: `AutoApprove`, `HoldForHuman`, or `Reject`.

> **Status: Milestone-1 preview (`v0.1.0-preview.1`).** This repository is the public preview of the core SDK described in our Solana Foundation grant proposal, *OpenGuard-Solana: Open-Source MCP Transaction Firewall, Per-Request Intent Signing & SPL Spend-Cap SDK for Solana AI Agents*. It is not audited and has not been run against mainnet. See [What is not done yet](#what-is-not-done-yet) before you rely on it.

## Why

Most agent setups hand the runtime a keypair or a signing callback and sign whatever transaction a tool builds. On Solana that leaves three gaps:

1. **Instruction smuggling.** A prompt-injected agent can append `SetAuthority`, `CloseAccount` or `ApproveChecked` to an otherwise normal transfer, or hide the real recipient behind an address lookup table.
2. **No intent binding.** Nothing ties the bytes being signed to what a human or orchestrator actually authorised: which mint, which recipient, how much, until when.
3. **No pre-sign balance check.** Simulating without comparing exact pre/post balances misses hidden outflows from Token-2022 hooks or opaque programs.

OpenGuard-Solana closes those gaps without ever touching a private key.

## What it does

| Check | Behaviour |
| --- | --- |
| Wire decoding | Own bounds-checked decoder for legacy and v0 messages. Truncated input, trailing bytes, bad compact-u16, duplicate keys, out-of-range indexes: `Reject`. |
| Lookup tables | Resolves every ALT key (static map or RPC). Missing, deactivated, short, or duplicate-loading tables: `Reject`. |
| Program allowlist | System, SPL Token, Token-2022, Associated Token, Memo, Compute Budget. Anything else is `Reject`, unless opted in through `extraPrograms`, in which case it needs simulation evidence and a human. |
| Instruction allowlist | Only known-safe instruction types pass. `SetAuthority`, `CloseAccount`, `Assign`, durable-nonce `AdvanceNonceAccount`, `MintTo`, transfer-hook extra accounts and unknown extensions are blocked. |
| Approvals | Unlimited (`u64::MAX`) delegation is always rejected. Bounded approvals to a listed delegate go to a human. |
| Spend caps | Per-transaction, rolling 1h and rolling 24h caps per asset (`SOL` or mint). All math is `BigInt`; amounts in policy files are decimal strings, never floats. Pending holds reserve headroom. |
| Signed intents | `OPENGUARD_SOL_INTENT_v1`: RFC 8785 canonical JSON, Ed25519 signature, monotonic nonce, time bounds. The transaction must match the intent's asset, recipient and maximum. |
| Simulation guard | Optional `simulateTransaction` evidence. Hidden outflow, CPI into an unlisted program, or an owner change on an agent token account: `Reject`. |
| Replay guard | A message hash or idempotency key is approved once. Retry storms past `maxAttemptsPerWindow` are rejected. |
| Hold queue | `HoldForHuman` items wait for a person. Caps are re-checked at approval time. Agents cannot approve their own holds: there is no MCP tool for it. |
| Audit log | Every decision is appended to a SHA-256 hash chain (`audit.jsonl`). Editing, deleting or reordering an entry is detected on load. |

## Quick start

Requires Node.js 24.

```bash
npm install
npx tsc --noEmit
npm test
npm run build
```

Check a transaction (base64, or `@file`) against a policy:

```bash
node dist/cli/main.js check \
  --policy examples/policy.devnet.json \
  --state .openguard \
  --session demo-1 \
  --tx @tx.b64
```

Exit codes: `0` AutoApprove, `3` HoldForHuman, `1` Reject, `2` usage error. Other commands:

```bash
node dist/cli/main.js decode --tx @tx.b64
node dist/cli/main.js hold list --policy examples/policy.devnet.json --state .openguard
node dist/cli/main.js hold approve <id> --policy examples/policy.devnet.json --state .openguard --approver alice
node dist/cli/main.js audit verify --state .openguard
```

## Library use

```ts
import { Firewall, parsePolicy, FirewallState, FileStore, AuditLog, RpcLookupResolver, SolanaRpc } from "@openguard-solana/sdk";

const fw = new Firewall({
  policy: parsePolicy(JSON.parse(policyJson)),
  state: new FirewallState(new FileStore(".openguard/state.json")),
  audit: new AuditLog(".openguard/audit.jsonl"),
  lookupResolver: new RpcLookupResolver(new SolanaRpc("https://api.devnet.solana.com")),
});

const decision = await fw.evaluate({ tx: txBase64, sessionId: "agent-42", intent: signedIntent });
if (decision.verdict === "AutoApprove") {
  // hand the same bytes to your signer
}
```

The firewall never signs. Your signer should only sign bytes whose message hash matches an `AutoApprove` decision (`decision.txHash` is the SHA-256 of the serialized message).

## MCP server

`node dist/cli/main.js mcp --policy <file> --state <dir>` starts a stdio MCP server (newline-delimited JSON-RPC 2.0). It exposes the six tools named in the proposal:

| Tool | Purpose |
| --- | --- |
| `openguard_quote_policy` | Allowed programs, caps, remaining rolling headroom |
| `openguard_verify_intent` | Check a signed intent without consuming its nonce |
| `openguard_simulate_tx` | Dry-run verdict, no state change |
| `openguard_execute_spl` | Real evaluation: records spend and marks the tx hash used. Does **not** sign. |
| `openguard_revoke_session` | Kill a session and its pending holds |
| `openguard_audit_receipt` | One audit entry plus a full chain verification |

A sample client config is in [`examples/mcp.json`](examples/mcp.json). SSE transport and the signer adapter are Milestone 2.

## Signed intents

An orchestrator signs `"openguard-solana:intent:v1\n" + JCS(intent)` with its own Ed25519 key:

```json
{
  "version": "OPENGUARD_SOL_INTENT_v1",
  "kind": "transfer",
  "cluster": "devnet",
  "agent": "<agent wallet>",
  "sessionId": "agent-42",
  "asset": "SOL",
  "recipient": "<recipient wallet>",
  "maxAmount": "250000000",
  "nonce": "17",
  "notBefore": 1796040000000,
  "expiresAt": 1796040300000
}
```

The SDK exports `intentSigningBytes()` and `verifySignedIntent()`. It has no signing helper on purpose. Full rules are in [SPEC.md](SPEC.md).

## Tests

154 Vitest tests across seven files. Transactions in the tests are built with the reference `@solana/web3.js` and `@solana/spl-token` encoders (dev dependencies only), so the decoder is checked against the real wire format and not against itself. Adversarial fixtures include:

- SOL drain over cap, and the same drain split into 12 small transfers
- `SetAuthority` hijack smuggled after a legitimate transfer (Token and Token-2022)
- `CloseAccount` drain to the attacker
- Unknown program receiving the Token program for a CPI
- Unlimited `ApproveChecked`, and `Approve` to an unlisted delegate
- Several bounded approvals summed past the per-tx cap, and an approval piggybacked on an unrelated intent
- SOL laundered as rent for attacker-owned ATAs (per-tx, hourly, allowlist, intent)
- Opaque program with no simulation, and with a zero-delta simulation
- A caller-supplied clock, and a hold approved after policy was tightened
- Retry storm, tx replay, idempotency-key reuse
- `u64::MAX` transfers, a sum past 2^64, and a cap that a `Number` would round past (2^53 + 1)
- Durable nonce, `System::Assign`, priority-fee burn, duplicate compute budget
- Unresolvable, short, and duplicate-loading lookup tables
- Hidden simulation outflow, CPI to an unlisted program, owner change
- 2,000 mutated byte strings through the decoder
- 20 parallel requests racing the hourly cap (exactly 5 approved)

An attack-corpus test runs 15 fixtures and an R1 exploit corpus runs 9 more scenarios (with their own policies and intents); both assert zero `AutoApprove`.

## What is not done yet

Honest list, so nobody mistakes the preview for the finished product:

- **Not audited.** Do not put real funds behind it yet.
- **No live network runs.** RPC helpers are tested against a mocked transport only. Devnet and mainnet-beta verification bundles are Milestone 2.
- **Token-2022 extensions** (transfer fees, transfer hooks, confidential transfers) are rejected rather than understood.
- **Multisig token authorities** are rejected.
- **Opaque programs** such as swap routers can only be cleared through simulation evidence plus a human, because M1 cannot see where their funds go.
- **Persistence** is a single JSON file with atomic rename. It is safe for one process. SQLite/Redis stores with cross-process locking are Milestone 2.
- **Network fees** (base fee and priority fee) are bounded per transaction by `maxPriorityFeeLamports` but are not counted against the SOL spend caps.

## Repository layout

```
src/
  wire.ts          legacy + v0 transaction decoder
  alt.ts           lookup table parsing and resolution
  decoders/        System, Token, Token-2022, ATA, Memo, Compute Budget
  pda.ts           PDA / ATA derivation (pure BigInt curve check)
  intent.ts        OPENGUARD_SOL_INTENT_v1 verification
  jcs.ts           RFC 8785 canonical JSON
  policy.ts        policy parsing and validation
  state.ts         spend ledger, replay guard, nonces, holds
  simulation.ts    balance-delta guard and RPC helpers
  firewall.ts      the evaluation pipeline
  audit.ts         hash-chained audit log
  mcp/server.ts    stdio MCP server
  cli/main.ts      CLI
test/              Vitest suites and fixtures
docs/ci.example.yml
```

## License

Apache-2.0. See [LICENSE](LICENSE).