Back to skill

Security audit

spanDEX Trader

Security checks for vulnerabilities and agentic risk

Overview

This is a real Base trading skill, but it needs review because it handles wallet private keys and can create persistent token approvals or sign remotely supplied order data without enough safeguards.

Install only after reviewing the financial-risk tradeoffs. Use a dedicated low-balance wallet, prefer dry-run and quote commands first, verify token addresses, amounts, chain, slippage, spender addresses, and order terms before any live action, and be prepared to revoke ERC-20 approvals after use. Avoid putting a valuable private key in shell history or broad environment scope, and prefer pinned dependencies or a reviewed lockfile before running the npm install step.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
Findings (5)

T09 · Insecure Skill Coding Practices

Error
Location
scripts/spandex_trade.mjs:499
Finding
Remote EIP-712 Order Data Is Signed Without Local Intent Validation<![CDATA[ ## Vulnerability Details **File Location**: `scripts/spandex_trade.mjs:499-522` and `scripts/spandex_trade.mjs:559-578` **Vulnerability Type**: Insufficient validation of remotely supplied signing payloads **Risk Level**: High ### Vulnerable Code ```js const signMsgRes = await fetch(`${KYBER_LO_DOMAIN}/write/api/v1/orders/sign-message`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(unsignedBody), }).then(r => r.json()); if (signMsgRes.code !== 0) die(`KyberSwap sign-message failed: ${signMsgRes.message}`); const eip712Data = signMsgRes.data; // Sign + submit const signature = await walletClient.signTypedData({ domain: { ...eip712Data.domain, chainId: parseInt(eip712Data.domain.chainId) }, types: { Order: eip712Data.types.Order }, primaryType: 'Order', message: eip712Data.message, }); const createRes = await fetch(`${KYBER_LO_DOMAIN}/write/api/v1/orders`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...unsignedBody, salt: eip712Data.message.salt, signature }), }).then(r => r.json()); ``` The same pattern is used when canceling an order: ```js const cancelSignRes = await fetch(`${KYBER_LO_DOMAIN}/write/api/v1/orders/cancel-sign`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chainId: '8453', maker: account.address, orderIds: [parseInt(args['order-id'])] }), }).then(r => r.json()); if (cancelSignRes.code !== 0) die(`KyberSwap cancel-sign failed: ${cancelSignRes.message}`); const eip712Data = cancelSignRes.data; const signature = await walletClient.signTypedData({ domain: { ...eip712Data.domain, chainId: parseInt(eip712Data.domain.chainId) }, types: { CancelOrder: eip712Data.types.CancelOrder }, primaryType: 'CancelOrder', message: eip712Data.message, }); const cancelRes = await fetch(`${KYBER_LO_DOMAIN}/write/api/v1/orders/cancel`, { method: 'POST', headers: { 'Content-Type': 'applicatio ...[truncated 1938 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Construct the complete EIP-712 message locally wherever the protocol permits. - Before signing, require the returned chain ID to equal Base chain ID `8453`. - Allowlist the expected verifying contract for the selected operation. - Compare the maker, assets, amounts, expiration, and order IDs byte-for-byte against locally derived values. - Validate the exact EIP-712 domain name, version, primary type, and field schema. - Reject extra fields, unsupported schemas, unexpected contracts, invalid addresses, and mismatched values. - Display the validated signing terms and require explicit confirmation before producing an asset-affecting signature. - Add tests using malicious API responses with modified contracts, assets, amounts, makers, and order IDs. ]]>

T05 · Unauthorized Access and Privilege Escalation

Error
Location
scripts/spandex_trade.mjs:350
Finding
Persistent Unlimited Token Allowances Exceed Required Trading Privileges<![CDATA[ ## Vulnerability Details **File Location**: `scripts/spandex_trade.mjs:350-353` and `scripts/spandex_trade.mjs:487-493` **Vulnerability Type**: Excessive and persistent token approval **Risk Level**: High ### Vulnerable Code The swap flow explicitly requests unlimited allowance: ```js const calls = await buildCalls({ quote, swap: swapParams, config: spandexConfig, publicClient, allowanceMode: 'unlimited', }); ``` The limit-order flow separately grants the maximum possible ERC-20 allowance: ```js if (allowance < totalNeeded) { out({ status: 'approving', token: sellInfo.address, spender: KYBER_LO_CONTRACT }); const approveHash = await walletClient.writeContract({ address: sellInfo.address, abi: erc20Abi, functionName: 'approve', args: [KYBER_LO_CONTRACT, maxUint], ...gasParams, }); await publicClient.waitForTransactionReceipt({ hash: approveHash }); out({ status: 'approved', txHash: approveHash }); } ``` ### Technical Analysis ERC-20 allowances remain active until consumed, replaced, or revoked. The requested trade requires authority over only a bounded token quantity, but these flows grant effectively unlimited access. In the swap flow, spender addresses are derived from calls built through third-party provider data. In the limit-order flow, the KyberSwap contract receives `maxUint`. A router or contract compromise can therefore affect the wallet's future token balance, rather than only the amount involved in the current order. This exceeds the minimum privilege required for the declared trading operation. ### Attack Path 1. The user completes a swap or creates a limit order. 2. The Skill grants an unlimited allowance to a provider-selected spender or the KyberSwap limit-order contract. 3. The allowance persists after the requested operation. 4. The approved spender is later compromised, upgraded maliciously, or otherwise abused. 5. The spender invokes `transferFrom` against the user's wallet. 6. Tokens can be removed up ...[truncated 402 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Replace unlimited approval mode with exact-amount or narrowly bounded approvals. - For a swap, approve no more than the exact input amount required by the selected route. - For limit orders, approve no more than the active making amount plus the new order amount. - Verify every provider-generated spender against a chain-specific allowlist before signing an approval. - Prefer permit-based, Permit2, or transaction-scoped authorization where supported and appropriately validated. - Offer automatic revocation after a completed or canceled operation. - Clearly display the spender, token, and allowance amount before approval. - Detect and warn about existing excessive allowances. ]]>

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
scripts/spandex_trade.mjs:210
Finding
Read-Only Operations Unnecessarily Load the Wallet Private Key<![CDATA[ ## Vulnerability Details **File Location**: `scripts/spandex_trade.mjs:210-239`, with read-only use at `scripts/spandex_trade.mjs:254`, `scripts/spandex_trade.mjs:428`, and `scripts/spandex_trade.mjs:548` **Vulnerability Type**: Violation of least-privilege credential handling **Risk Level**: Medium ### Vulnerable Code ```js function createSetup() { const pk = loadPrivateKey(); const account = privateKeyToAccount(pk); const publicClient = createPublicClient({ chain: base, transport: http(RPC_URL) }); const walletClient = createWalletClient({ chain: base, transport: http(RPC_URL), account }); // spanDEX config: 6 free providers (no API keys needed) const spandexConfig = createConfig({ providers: [ fabric({ appId: APP_ID }), kyberswap({ clientId: APP_ID }), odos({}), velora({}), lifi({}), relay({}), ], options: { deadlineMs: 15_000, numRetries: 1, }, clients: [publicClient], logging: process.env.SPANDEX_DEBUG ? { level: 'debug' } : undefined, }); return { publicClient, walletClient, account, spandexConfig }; } ``` Read-only actions call the same setup routine: ```js const { publicClient, account, spandexConfig } = createSetup(); ``` ```js const { publicClient, account } = createSetup(); ``` ```js const { account } = createSetup(); ``` ### Technical Analysis The `quote`, `balance`, and `orders` operations need a public wallet address but do not need private-key signing authority. Nevertheless, `createSetup()` always reads and parses the private key and creates a wallet client. This unnecessarily places the private key into process memory during harmless read-only actions. Because the process imports and executes third-party packages, loading the key expands the consequences of dependency compromise or runtime instrumentation. ### Attack Path 1. A user requests a quote, balance check, or order listing. 2. The common setup routine reads `SPANDEX_PRIVATE_KEY ...[truncated 644 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Split setup into separate public and signing initialization functions. - Accept a public wallet address for `quote`, `balance`, and `orders`. - Do not read the private key or construct a wallet client for read-only commands. - Load signing material only immediately before an operation that requires a signature. - Remove key material from environment variables where practical and use a hardware wallet, external signer, or narrowly scoped signing service. - Minimize key lifetime in memory and avoid including signer objects in broadly shared configuration. ]]>

T08 · Insecure Dependencies

Warning
Location
SKILL.md:20
Finding
Unpinned Runtime Dependency Installation Creates Supply-Chain Exposure<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:20-23` **Vulnerability Type**: Mutable and unverified dependency installation **Risk Level**: Medium ### Vulnerable Code ```bash # Install dependencies (run once in skill directory) cd <skill-dir>/scripts && npm init -y && npm i viem @spandex/core ``` ### Technical Analysis The setup instructions initialize a new package dynamically and install the latest versions of `viem` and `@spandex/core`. The project does not provide a reviewed manifest and lockfile in the audited directory. As a result, the dependency graph can change between installations. npm packages may also execute lifecycle scripts during installation. This is especially sensitive because the resulting modules execute in a process that may load a wallet private key and construct or sign asset-transfer transactions. No malicious package was identified in the audited files; the issue is the unsafe, mutable installation mechanism. ### Attack Path 1. An attacker compromises a dependency publisher, npm account, package release process, or transitive dependency. 2. A malicious version is published before a user follows the setup instructions. 3. `npm i viem @spandex/core` resolves and installs the affected version. 4. Malicious lifecycle or runtime code executes in the Skill environment. 5. The code can access environment variables, key files readable by the process, RPC configuration, or transaction data. 6. It may exfiltrate credentials or alter transaction destinations and approval parameters. ### Impact Assessment A successful supply-chain compromise would execute with the permissions of the user running the Skill. Because the process handles wallet signing credentials, the potential impact includes private-key theft, arbitrary local file access within user permissions, transaction manipulation, and wallet asset loss. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Commit a reviewed `package.json` and package lockfile. - Pin exact dependency versions instead of resolving mutable latest versions. - Use `npm ci` so installation fails when the lockfile and manifest differ. - Review lockfile integrity hashes and transitive dependency changes. - Run dependency vulnerability and provenance checks in CI. - Disable npm lifecycle scripts with `--ignore-scripts` where compatible. - Perform dependency installation in a restricted environment without wallet credentials. - Separate installation from transaction execution and use reproducible build artifacts. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/spandex_trade.mjs:158
Finding
User-Supplied Slippage Is Accepted Without Safety Bounds<![CDATA[ ## Vulnerability Details **File Location**: `scripts/spandex_trade.mjs:158-164`, used by the swap flow at `scripts/spandex_trade.mjs:294-295` **Vulnerability Type**: Missing numeric and economic safety validation **Risk Level**: Medium ### Vulnerable Code ```js function getSlippageBps(args, sellAddress, buyAddress) { if (args.slippage) return parseInt(args.slippage); const majorTokens = Object.values(TOKEN_ALIASES).map(t => t.address.toLowerCase()); const isMajorSell = majorTokens.includes(sellAddress.toLowerCase()); const isMajorBuy = majorTokens.includes(buyAddress.toLowerCase()); if (!isMajorSell && !isMajorBuy) return 500; // 5% microcap↔microcap if (!isMajorSell || !isMajorBuy) return 300; // 3% major↔microcap return 50; // 0.5% major↔major } ``` The returned value is placed into swap parameters: ```js const slippageBps = getSlippageBps(args, sellInfo.address, buyInfo.address); const strategy = args.strategy || DEFAULT_STRATEGY; ``` ### Technical Analysis The `--slippage` argument is parsed with `parseInt()` but is not checked for: - A finite integer result - Non-negative value - Basis-point range - A conservative maximum - Trailing invalid characters A very large slippage value weakens minimum-output protections and can permit execution at a substantially worse price than the user reasonably expects. Depending on downstream validation, malformed values may also cause provider failures or inconsistent behavior. ### Attack Path 1. A user, automation layer, or untrusted command generator supplies an excessive value such as a very large number of basis points. 2. `parseInt()` accepts the value without enforcing an upper bound. 3. The value is included in quote and swap parameters. 4. The transaction is built with weak price protection if accepted by the provider. 5. Market movement, low liquidity, price manipulation, or sandwich activity causes execution at an unfavorable rate. 6. T ...[truncated 315 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Require the slippage argument to match a strict decimal-integer pattern. - Reject `NaN`, negative values, fractional text, trailing characters, and values outside the valid basis-point range. - Enforce a conservative default maximum, such as a project-defined limit appropriate for supported assets. - Require explicit confirmation for any value above a lower warning threshold. - Include the effective slippage prominently in dry-run and pre-signing output. - Add tests for negative, malformed, extremely large, empty, hexadecimal-like, and mixed-character inputs. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (15)

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Ae1

High
Category
analysis-evasion
Content
node scripts/spandex_trade.mjs quote --sell USDC --buy 0xTOKEN --amount 50
Confidence
100% confidence
Finding
Referenced artifact was not completely inspected

Missing User Warnings

High
Confidence
97% confidence
Finding
The skill describes execution features like automatic fallback, quote racing, and transaction submission but does not prominently warn that swaps and limit-order actions are irreversible, may incur gas costs, and can result in loss from slippage or wrong token selection. In the context of an on-chain trading skill handling private keys, missing such warnings increases the likelihood of unsafe user authorization and accidental financial loss.

Credential Access

High
Category
Privilege Escalation
Content
try {
      return fs.readFileSync(KEY_PATH, 'utf8').trim();
    } catch (e) {
      die(`Cannot read private key from ${KEY_PATH}: ${e.message}`);
    }
  }
  die('Set SPANDEX_PRIVATE_KEY (hex) or SPANDEX_KEY_PATH (file) env var');
Confidence
80% confidence
Finding
Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Lp3

Medium
Category
MCP Least Privilege
Confidence
95% confidence
Finding
The skill requires access to environment variables and networked execution to install dependencies, read a private key, query quotes, and submit transactions, but it declares no explicit tool scope or permissions. In an agent setting, this can lead to the skill being invoked with broader-than-intended capabilities, increasing the chance of secret exposure or unauthorized on-chain actions.

Vague Triggers

Medium
Confidence
94% confidence
Finding
The trigger list includes very broad terms such as "buy," "sell," "swap," and "trade," which can match many unrelated conversations and cause unintended activation of a skill capable of executing blockchain transactions. Because this skill can place orders and spend wallet funds, accidental routing is materially more dangerous than for a read-only skill.

Missing User Warnings

Medium
Confidence
81% confidence
Finding
This function loads a raw private key from `SPANDEX_PRIVATE_KEY` or from a file path in `SPANDEX_KEY_PATH`, which is a safety-sensitive credential operation. While the code comments describe precedence, there is no user-facing warning in the CLI usage or output about the sensitivity of these inputs or the need to protect them.

Missing User Warnings

Medium
Confidence
94% confidence
Finding
The swap path explicitly builds calls with `allowanceMode: 'unlimited'`, which can leave a standing ERC-20 approval after the immediate trade completes. If the approved spender or routing contract is later compromised, upgraded maliciously, or misused, it may drain all approved tokens from the wallet without further user consent. In a trading skill that executes live on-chain transactions, this is more dangerous because approvals are likely to be exercised against real user funds.