# CloddsBot Security Hardening: Credential Encryption and Sandboxing Implementation

> Secure your CloddsBot with AES-256-GCM credential encryption and sandboxing. Learn how to disable dynamic code execution and prevent arbitrary code execution risks.

- Repository: [AL/CloddsBot](https://github.com/alsk1992/CloddsBot)
- Tags: how-to-guide
- Published: 2026-09-11

---

**CloddsBot implements AES-256-GCM credential encryption with scrypt key derivation and disables dynamic code execution by default, requiring explicit opt-in via environment variables to mitigate arbitrary code execution risks.**

CloddsBot is an open-source trading automation framework that handles sensitive financial API credentials and supports dynamic code execution, necessitating rigorous security hardening measures to protect user assets. The repository implements defense-in-depth strategies combining modern cryptographic standards for data-at-rest protection with runtime sandboxing controls. This analysis examines the specific security implementations in [`src/trading/secrets.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/secrets.ts) and [`src/security/index.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/security/index.ts) that safeguard credentials and constrain potentially unsafe operations.

## AES-256-GCM Credential Encryption Architecture

The bot protects trading credentials at rest using **AES-256-GCM authenticated encryption**. All secrets are stored in an SQLite database as JSON-encoded blobs containing the initialization vector (`iv`), authentication tag (`authTag`), salt, and ciphertext, ensuring both confidentiality and integrity of sensitive data.

### Key Derivation and Storage

In [`src/trading/secrets.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/secrets.ts), the `createSecretStore` function derives encryption keys using **scrypt**, a memory-hard password hashing algorithm resistant to hardware brute-force attacks. The master key is provided via the `CLODDS_CREDENTIAL_KEY` environment variable and is never persisted to disk; only the derived key material exists transiently in memory during cryptographic operations.

```typescript
import { createSecretStore } from '../../trading/secrets';

const secretStore = await createSecretStore(db, process.env.CLODDS_CREDENTIAL_KEY!);
await secretStore.set('polymarket_creds', JSON.stringify({ api_key: 'ABCD1234', api_secret: 's3cr3t' }));

```

The `deriveKey` function internally uses scrypt parameters to generate a per-secret encryption key, while the `encrypt` method produces the GCM-encrypted blob stored in the database.

### Decryption and Verification

Retrieving credentials involves the `decrypt` function, which reconstructs the key using the stored salt and verifies the `authTag` before returning plaintext. This authentication step prevents tampering with encrypted values.

```typescript
const encryptedBlob = await secretStore.get('polymarket_creds');
const plaintext = await secretStore.decrypt(encryptedBlob);
const credentials = JSON.parse(plaintext);

```

### Key Rotation Without Exposure

The `rotateKey` function in [`src/trading/secrets.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/secrets.ts) enables cryptographic key rotation without temporarily exposing secrets. It decrypts every entry using the old master key, re-encrypts with a new master key, and updates rows atomically:

```typescript
await secretStore.rotateKey('new-strong-master-key-1234');

```

## Default-Disable Sandboxing for Dynamic Execution

CloddsBot addresses code injection risks through a **default-disabled sandbox** for dynamic evaluation. The `createSandbox` function in [`src/security/index.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/security/index.ts) implements a secure-by-default posture where `eval` and `new Function` execution are explicitly blocked unless the operator opts into unsafe behavior.

### Runtime Sandbox Controls

The sandbox checks for the `ALLOW_UNSAFE_SANDBOX` environment variable. When undefined or set to `false`, `createSandbox` returns an object whose `eval` method immediately throws a security error, preventing arbitrary code execution:

```typescript
import { createSandbox } from '../../security/index';

const sandbox = createSandbox();
// Throws: Sandbox eval is disabled for security.
sandbox.eval('2 + 2');

```

Even when `ALLOW_UNSAFE_SANDBOX=true` is set—a configuration strongly discouraged for production—the sandbox restricts module access through the `allowedModules` option and logs explicit security warnings to stderr.

### Module Restrictions

When operating in unsafe mode (development environments only), the sandbox still enforces import controls:

```typescript
// ALLOW_UNSAFE_SANDBOX=true must be set in environment
const sandbox = createSandbox({ allowedModules: ['lodash'] });
// Only lodash can be required; other modules throw

```

## Runtime Configuration and Validation

The bot enforces secure configuration through mandatory environment variables. The credential management layer refuses to initialize if `CLODDS_CREDENTIAL_KEY` is missing or shorter than eight characters, preventing accidental plaintext storage.

In [`src/skills/bundled/credentials/index.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/skills/bundled/credentials/index.ts), the credential skill surfaces encryption status through CLI commands:

```bash
/creds status

# Warns if CLODDS_CREDENTIAL_KEY is not set

# Confirms AES-256-GCM encryption is active

```

All credential commands (`/creds set`, `/creds list`, `/creds delete`) transparently use the encrypted secret store via `createCredentialsManager`, ensuring no plaintext credentials persist to disk.

## Audit Logging and Forensics

Every cryptographic operation on secrets is recorded in the `secrets_audit` table for forensic traceability. The `logAudit` function in [`src/trading/secrets.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/secrets.ts) inserts rows capturing the action type, credential key, success status, timestamp, and optional error messages:

- **Read operations**: Logged when `getCredentials` retrieves decrypted values
- **Write operations**: Logged when `setCredentials` creates or updates entries  
- **Delete operations**: Logged when credentials are removed
- **Rotation events**: Logged during master key rotation

This audit trail aids in detecting credential misuse and supports compliance requirements for financial trading systems.

## Operational Security Documentation

Beyond code-level protections, the repository provides comprehensive hardening guidance in [`docs/VPS_SECURITY.md`](https://github.com/alsk1992/CloddsBot/blob/main/docs/VPS_SECURITY.md) and [`SECURITY.md`](https://github.com/alsk1992/CloddsBot/blob/main/SECURITY.md). These documents outline:

- OS-level hardening (unattended upgrades, UFW firewall, fail2ban)
- SSH security (root login disable, key-based authentication)
- Runtime environment controls (sandbox environment variables)
- Incident response procedures for credential compromise

The documentation explicitly warns against enabling `ALLOW_UNSAFE_SANDBOX` in production environments and recommends regular key rotation using the built-in rotation utilities.

## Summary

- **CloddsBot encrypts all credentials** using AES-256-GCM with scrypt-derived keys, storing only authenticated ciphertext in SQLite
- **Dynamic code execution is disabled by default** and requires explicit `ALLOW_UNSAFE_SANDBOX=true` opt-in with security warnings
- **Master keys never persist** to disk; they exist only as environment variables validated at startup
- **Atomic key rotation** allows changing encryption keys without exposing plaintext secrets
- **Comprehensive audit logging** tracks every credential access, modification, and deletion
- **Operational documentation** provides VPS hardening checklists for production deployments

## Frequently Asked Questions

### How does CloddsBot prevent credentials from being stored in plain text?

The `createSecretStore` function in [`src/trading/secrets.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/secrets.ts) refuses to initialize without a valid `CLODDS_CREDENTIAL_KEY` environment variable. When present, all values are encrypted using AES-256-GCM before storage, with the plaintext existing only transiently in memory during active operations.

### What encryption algorithms does CloddsBot use for credential protection?

CloddsBot uses **AES-256-GCM** for symmetric encryption and **scrypt** for key derivation. The GCM mode provides authenticated encryption, ensuring both confidentiality and integrity, while scrypt provides memory-hard resistance against brute-force attacks on the master password.

### Can I enable dynamic code execution in CloddsBot for custom strategies?

The sandbox in [`src/security/index.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/security/index.ts) supports dynamic evaluation only when the `ALLOW_UNSAFE_SANDBOX` environment variable is explicitly set to `true`. By default, calling `sandbox.eval()` throws a security error. Enabling this mode logs warnings and should be restricted to isolated development environments.

### How do I rotate the master encryption key without losing access to stored credentials?

Use the `rotateKey` method from [`src/trading/secrets.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/secrets.ts), which decrypts all entries using the current master key and re-encrypts them with the new key atomically. The secrets remain encrypted in memory during the process and are never exposed as plaintext outside the secure enclave.

### Does CloddsBot log credential access for security monitoring?

Yes. Every read, write, delete, and rotation operation is recorded in the `secrets_audit` SQLite table via the `logAudit` function. These logs include timestamps, action types, and success indicators, providing forensic traceability for compliance and security incident investigation.