Markdown Viewer

SMT Studio โ€” Security Architecture

This document explains how SMT Studio is hardened against the OWASP Top 10 and common Node.js/Express vulnerabilities. Every control is grounded in specific code โ€” file and line references are included so you can verify each claim directly.


1. Command Injection Prevention

OWASP A03 โ€” Injection

Every call to the Salesforce CLI uses execFile() with arguments passed as an array, never as a shell-interpolated string.

// server.js โ€” org list (line ~223)
const { stdout } = await execFilePromise(SF_BIN, ['org', 'list', '--json']);

// server.js โ€” sobject describe (line ~275)
await execFilePromise(SF_BIN, ['sobject', 'describe', '-s', sobject, '-o', username, '--json']);

execFile bypasses the shell entirely. Shell metacharacters in username or sobject (e.g. ; rm -rf /) are treated as literal strings, not operators. This prevents command injection even if a malicious org alias reaches the server.

Windows compatibility is handled without compromising this model:

// server.js โ€” line ~13
const SF_BIN = process.platform === 'win32' ? 'sf.cmd' : 'sf';

Browser auto-open on each platform also uses execFile, never exec:

// server.js โ€” line ~1147
execFile('cmd', ['/c', 'start', '', url]);   // Windows
execFile('open', [url]);                      // macOS
execFile('xdg-open', [url]);                 // Linux

2. Path Traversal Prevention

OWASP A01 โ€” Broken Access Control

The /api/download/:filename endpoint accepts a user-supplied filename. path.basename() strips all directory components before the path is joined:

// server.js โ€” line ~852
const filename = path.basename(req.params.filename);
const filepath = path.join(__dirname, filename);

A request for ../../etc/passwd resolves basename to passwd and then joins it to __dirname โ€” the attacker never escapes the working directory.


3. Access Token Encryption at Rest

OWASP A02 โ€” Cryptographic Failures

Salesforce access tokens are encrypted before writing to ~/.migrationrc and decrypted transparently on read. The implementation uses AES-256-GCM โ€” an authenticated encryption mode that provides both confidentiality and integrity.

// src/config.js โ€” line ~17
const ALGO = 'aes-256-gcm';
const KEY  = _deriveKey();

Key derivation โ€” the 256-bit key is machine-bound, derived at runtime:

// src/config.js โ€” line ~13
const material = `smt-studio:${os.hostname()}:${os.userInfo().username}`;
return crypto.createHash('sha256').update(material).digest(); // 32 bytes

No secret is stored anywhere โ€” the key is re-derived from the machine's hostname and OS username each time the process starts. A file copied to another machine cannot be decrypted.

Encryption โ€” a fresh 12-byte IV is generated per encryption, making ciphertexts non-deterministic:

// src/config.js โ€” line ~20
const iv        = crypto.randomBytes(12);
const cipher    = crypto.createCipheriv(ALGO, KEY, iv);
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const authTag   = cipher.getAuthTag();
// Stored as:  ivHex:authTagHex:ciphertextHex

Authentication tag โ€” GCM's 16-byte auth tag is stored alongside the ciphertext. Decryption calls setAuthTag() before final(), so any tampering with the stored token is detected and rejected.

File permissions โ€” after every write, the config file is locked to owner-only access:

// src/config.js โ€” line ~86
await fs.chmod(CONFIG_FILE, 0o600);  // -rw------- ; skipped on Windows (uses ACLs)

4. API Authentication (Bearer Token)

OWASP A07 โ€” Identification and Authentication Failures

All /api/* routes can be protected with a Bearer token by setting the SMT_SECRET environment variable:

// server.js โ€” line ~164
const SMT_SECRET = process.env.SMT_SECRET;
if (SMT_SECRET) {
  app.use('/api', (req, res, next) => {
    const auth = req.headers.authorization || '';
    if (auth !== `Bearer ${SMT_SECRET}`) {
      return res.status(401).json({ success: false, error: 'Unauthorized' });
    }
    next();
  });
}

A single middleware registered on the /api prefix guards every route uniformly โ€” there is no per-route opt-in that could be forgotten. The guard is zero-friction for local use (no SMT_SECRET required by default) but becomes mandatory the moment the env var is set.


5. WebSocket Authentication

OWASP A07 โ€” Identification and Authentication Failures

Socket.IO connections are authenticated at the connection level using the same SMT_SECRET:

// server.js โ€” line ~865
io.use((socket, next) => {
  if (SMT_SECRET && socket.handshake.auth?.token !== SMT_SECRET) {
    return next(new Error('Unauthorized'));
  }
  next();
});

io.use() intercepts every connection before the connection event fires. Unauthorized sockets are rejected with no partial state established. The frontend passes the token in socket.handshake.auth at connection time.


6. Bulk-Delete CSRF Protection

OWASP A01 โ€” Broken Access Control

The destructive POST /api/bulk-delete endpoint is protected by a one-time session token issued at migration start:

// server.js โ€” line ~577  (issued)
deleteSessionToken = crypto.randomBytes(16).toString('hex');
// ...
io.emit('migration-complete', { success: true, deleteSessionToken });
// server.js โ€” line ~1079  (consumed)
if (!deleteSessionToken || req.body.sessionToken !== deleteSessionToken) {
  return res.status(403).json({ success: false, error: 'Invalid or expired delete session token.' });
}
deleteSessionToken = null; // one-time use โ€” invalidated immediately after first valid use

Properties of this design:


7. SSRF Prevention

OWASP A10 โ€” Server-Side Request Forgery

The Ollama proxy endpoint accepts a base URL parameter. Without validation, an attacker could supply an internal IP to probe the server's network. The fix validates the hostname against an explicit allowlist before making any outbound request:

// server.js โ€” line ~898
const allowedHosts = ['localhost', '127.0.0.1'];
const parsedBase = new URL(base);
if (!allowedHosts.includes(parsedBase.hostname)) {
  return res.status(400).json({ success: false, error: 'Only localhost Ollama endpoints are allowed', models: [] });
}

new URL() performs full RFC-3986 parsing โ€” it cannot be tricked by URL encoding or embedded credentials (http://attacker@localhost.evil.com), because parsedBase.hostname returns only the host component.


8. Explicit Opt-in for Destructive Operations

Defence in Depth

The bulk-delete API is disabled by default. It must be explicitly enabled at server startup:

smt-studio --allow-delete
// server.js โ€” line ~1074
if (!ALLOW_DELETE) {
  return res.status(403).json({ success: false, error: 'Bulk delete is disabled. Restart the server with --allow-delete to enable it.' });
}

Three independent controls must all pass before a delete executes:

  1. Server started with --allow-delete
  2. Valid SMT_SECRET Bearer token on the HTTP request (if SMT_SECRET is set)
  3. Valid one-time deleteSessionToken in the request body

9. AI Sidekick Rate Limiting

OWASP A04 โ€” Insecure Design

The AI chat proxy is limited to 30 requests per 60 seconds per IP using an in-process sliding-window counter โ€” no external dependency required:

// server.js โ€” line ~914
const _aiRatemap = new Map();
function _aiRateLimit(req, res, next) {
  const ip  = req.ip || req.socket.remoteAddress || 'unknown';
  const now = Date.now();
  const win = 60_000;
  const max = 30;
  const entry = _aiRatemap.get(ip) || { count: 0, start: now };
  if (now - entry.start > win) { entry.count = 0; entry.start = now; }
  entry.count++;
  _aiRatemap.set(ip, entry);
  if (entry.count > max) {
    return res.status(429).json({ success: false, error: 'Too many requests. Please wait before sending more AI messages.' });
  }
  next();
}

app.post('/api/ai/chat', _aiRateLimit, async (req, res) => { ... });

This prevents a rogue client from proxying thousands of requests to a paid AI provider (Claude, OpenAI, Grok, Gemini) through the server.


10. AI Provider Keys Never Leave the Browser

OWASP A02 โ€” Cryptographic Failures / Sensitive Data Exposure

AI provider API keys (Anthropic, OpenAI, xAI, Google) are held in browser memory only โ€” they travel in the request body to the proxy and are forwarded immediately to the provider. They are never:

// server.js โ€” line ~978
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },

apiKey comes directly from req.body.apiKey and is used in-flight only.


11. Default Localhost Binding

Defence in Depth

The server binds to localhost by default:

// server.js โ€” line ~29
.option('--host <address>', 'host address to bind to', 'localhost')

External network exposure requires an explicit opt-in (--host 0.0.0.0). Combined with SMT_SECRET, this means the server is unreachable from other machines unless the operator consciously configures both.


Summary

Control OWASP Category Location
execFile + array args A03 Injection server.js ~L223, L275; SF_BIN constant
path.basename() on download A01 Broken Access Control server.js ~L852
AES-256-GCM token encryption A02 Cryptographic Failures src/config.js L17โ€“L26
chmod 600 on ~/.migrationrc A02 Cryptographic Failures src/config.js ~L86
Machine-bound key derivation A02 Cryptographic Failures src/config.js ~L13
Bearer token on all /api/* A07 Auth Failures server.js ~L164
Socket.IO io.use() auth A07 Auth Failures server.js ~L865
One-time CSRF token for bulk-delete A01 Broken Access Control server.js ~L577, L1079
--allow-delete explicit flag Defence in Depth server.js ~L1074
SSRF hostname allowlist A10 SSRF server.js ~L900
AI rate limiter (30 req/60 s) A04 Insecure Design server.js ~L914
AI keys in-flight only A02 Sensitive Data Exposure server.js ~L978
Default localhost binding Defence in Depth server.js ~L29