Compare commits
1 Commits
fix/880
...
burn/1423-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e98ce44ee1 |
6
app.js
6
app.js
@@ -2140,9 +2140,9 @@ function setupControls() {
|
||||
}
|
||||
|
||||
function sendChatMessage(overrideText = null) {
|
||||
// Mine chat message to MemPalace
|
||||
if (overrideText) {
|
||||
window.electronAPI.execPython(`mempalace add_drawer "${this.wing}" "chat" "${overrideText}"`);
|
||||
// Mine chat message to MemPalace — use safe addDrawer method
|
||||
if (overrideText && typeof mempalace !== 'undefined' && mempalace.addDrawer) {
|
||||
mempalace.addDrawer(this.wing, 'chat', overrideText);
|
||||
}
|
||||
const input = document.getElementById('chat-input');
|
||||
const text = overrideText || input.value.trim();
|
||||
|
||||
@@ -1,10 +1,69 @@
|
||||
const { app, BrowserWindow, ipcMain } = require('electron')
|
||||
const { exec } = require('child_process')
|
||||
const { execFile } = require('child_process')
|
||||
const path = require('path')
|
||||
|
||||
// MemPalace integration
|
||||
ipcMain.handle('exec-python', (event, command) => {
|
||||
// MemPalace command whitelist — only these operations are allowed
|
||||
const MEMPALACE_BIN = path.resolve(__dirname, 'scripts/mempalace-runner.sh')
|
||||
const ALLOWED_MEMPALACE_OPS = new Set([
|
||||
'init', 'mine', 'search', 'status', 'add_drawer', 'list', 'export'
|
||||
])
|
||||
|
||||
// Validate MemPalace arguments — reject shell metacharacters
|
||||
function sanitizeArg(arg) {
|
||||
if (typeof arg !== 'string') throw new Error('Argument must be a string')
|
||||
// Block shell metacharacters that could enable injection
|
||||
if (/[;&|`$(){}\\n\\r]/.test(arg)) {
|
||||
throw new Error('Invalid characters in argument')
|
||||
}
|
||||
return arg
|
||||
}
|
||||
|
||||
// MemPalace integration — safe IPC bridge
|
||||
// Uses execFile (no shell) with argument arrays to prevent command injection
|
||||
ipcMain.handle('mempalace-exec', (event, { op, args }) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(command, (error, stdout, stderr) => {
|
||||
// Validate operation
|
||||
if (!ALLOWED_MEMPALACE_OPS.has(op)) {
|
||||
return reject(new Error(`MemPalace operation '${op}' not allowed`))
|
||||
}
|
||||
|
||||
// Sanitize all arguments
|
||||
const safeArgs = [op]
|
||||
if (Array.isArray(args)) {
|
||||
for (const arg of args) {
|
||||
safeArgs.push(sanitizeArg(String(arg)))
|
||||
}
|
||||
}
|
||||
|
||||
// Execute with execFile — no shell interpolation
|
||||
execFile('mempalace', safeArgs, { timeout: 30000 }, (error, stdout, stderr) => {
|
||||
if (error) return reject(error)
|
||||
resolve({ stdout, stderr })
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Legacy bridge — DEPRECATED, kept for backward compat but restricted
|
||||
// Only allows predefined commands, no arbitrary execution
|
||||
ipcMain.handle('exec-python', (event, command) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Reject anything that looks like arbitrary shell execution
|
||||
if (typeof command !== 'string') return reject(new Error('Command must be a string'))
|
||||
if (/[;&|`$(){}\\n\\r]/.test(command)) {
|
||||
return reject(new Error('Shell metacharacters not allowed'))
|
||||
}
|
||||
// Only allow mempalace commands
|
||||
if (!command.startsWith('mempalace ')) {
|
||||
return reject(new Error('Only mempalace commands are allowed'))
|
||||
}
|
||||
// Parse into safe argument array
|
||||
const parts = command.split(/\s+/)
|
||||
const op = parts[1]
|
||||
if (!ALLOWED_MEMPALACE_OPS.has(op)) {
|
||||
return reject(new Error(`Operation '${op}' not in whitelist`))
|
||||
}
|
||||
const safeArgs = parts.slice(1).map(sanitizeArg)
|
||||
execFile('mempalace', safeArgs, { timeout: 30000 }, (error, stdout, stderr) => {
|
||||
if (error) return reject(error)
|
||||
resolve({ stdout, stderr })
|
||||
})
|
||||
|
||||
51
mempalace.js
51
mempalace.js
@@ -1,4 +1,4 @@
|
||||
// MemPalace integration
|
||||
// MemPalace integration — uses safe IPC bridge (mempalace-exec)
|
||||
class MemPalace {
|
||||
constructor() {
|
||||
this.palacePath = '~/.mempalace/palace';
|
||||
@@ -6,6 +6,16 @@ class MemPalace {
|
||||
this.init();
|
||||
}
|
||||
|
||||
// Safe IPC call — no shell interpolation, uses argument arrays
|
||||
async _exec(op, ...args) {
|
||||
if (window.electronAPI?.mempalaceExec) {
|
||||
return window.electronAPI.mempalaceExec({ op, args })
|
||||
}
|
||||
// Fallback for non-Electron contexts (web-only)
|
||||
console.warn('MemPalace: electronAPI not available, skipping:', op)
|
||||
return { stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.setupWing();
|
||||
@@ -16,29 +26,46 @@ class MemPalace {
|
||||
}
|
||||
|
||||
async setupWing() {
|
||||
await window.electronAPI.execPython(`mempalace init ${this.palacePath}`);
|
||||
await window.electronAPI.execPython(`mempalace mine ~/chats --mode convos --wing ${this.wing}`);
|
||||
await this._exec('init', this.palacePath);
|
||||
await this._exec('mine', '~/chats', '--mode', 'convos', '--wing', this.wing);
|
||||
}
|
||||
|
||||
setupAutoMining() {
|
||||
setInterval(() => {
|
||||
window.electronAPI.execPython(`mempalace mine #chat-container --mode convos --wing ${this.wing}`);
|
||||
this._exec('mine', '#chat-container', '--mode', 'convos', '--wing', this.wing);
|
||||
}, 30000); // Mine every 30 seconds
|
||||
}
|
||||
|
||||
async search(query) {
|
||||
const result = await window.electronAPI.execPython(`mempalace search "${query}" --wing ${this.wing}`);
|
||||
const result = await this._exec('search', query, '--wing', this.wing);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
async addDrawer(wing, drawer, content) {
|
||||
return this._exec('add_drawer', wing, drawer, content);
|
||||
}
|
||||
|
||||
updateStats() {
|
||||
const stats = window.electronAPI.execPython(`mempalace status --wing ${this.wing}`);
|
||||
document.getElementById('compression-ratio').textContent =
|
||||
`${stats.compression_ratio.toFixed(1)}x`;
|
||||
document.getElementById('docs-mined').textContent = stats.total_docs;
|
||||
document.getElementById('aaak-size').textContent = stats.aaak_size;
|
||||
this._exec('status', '--wing', this.wing).then(stats => {
|
||||
// stats comes as JSON string from stdout
|
||||
try {
|
||||
const data = typeof stats.stdout === 'string' ? JSON.parse(stats.stdout) : stats
|
||||
const crEl = document.getElementById('compression-ratio');
|
||||
const dmEl = document.getElementById('docs-mined');
|
||||
const akEl = document.getElementById('aaak-size');
|
||||
if (crEl) crEl.textContent = `${(data.compression_ratio || 0).toFixed(1)}x`;
|
||||
if (dmEl) dmEl.textContent = data.total_docs || 0;
|
||||
if (akEl) akEl.textContent = data.aaak_size || 0;
|
||||
} catch (e) {
|
||||
console.error('MemPalace stats parse error:', e);
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error('MemPalace stats error:', err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize MemPalace
|
||||
const mempalace = new MemPalace();
|
||||
// Initialize MemPalace only in Electron context
|
||||
if (typeof window !== 'undefined' && window.electronAPI) {
|
||||
const mempalace = new MemPalace();
|
||||
}
|
||||
|
||||
11
preload.js
Normal file
11
preload.js
Normal file
@@ -0,0 +1,11 @@
|
||||
// preload.js — Electron context bridge
|
||||
// Safely exposes IPC methods to the renderer process
|
||||
const { contextBridge, ipcRenderer } = require('electron')
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
// Safe MemPalace execution — uses argument arrays, no shell strings
|
||||
mempalaceExec: (opts) => ipcRenderer.invoke('mempalace-exec', opts),
|
||||
|
||||
// Legacy bridge — restricted to whitelisted mempalace commands only
|
||||
execPython: (command) => ipcRenderer.invoke('exec-python', command),
|
||||
})
|
||||
68
tests/test_electron_security.py
Normal file
68
tests/test_electron_security.py
Normal file
@@ -0,0 +1,68 @@
|
||||
"""Test that electron-main.js security fix prevents command injection."""
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
def test_no_raw_exec():
|
||||
"""electron-main.js should not use child_process.exec (only execFile)."""
|
||||
content = open('electron-main.js').read()
|
||||
# Should use execFile, not exec
|
||||
assert 'execFile' in content, "Should use execFile for safe subprocess execution"
|
||||
# Should NOT have raw exec import (allow execFile which contains 'exec')
|
||||
lines = content.split('\n')
|
||||
for line in lines:
|
||||
if 'require' in line and 'exec' in line:
|
||||
assert 'execFile' in line, f"Should import execFile, not exec: {line}"
|
||||
|
||||
def test_command_whitelist():
|
||||
"""electron-main.js should have a whitelist of allowed operations."""
|
||||
content = open('electron-main.js').read()
|
||||
assert 'ALLOWED_MEMPALACE_OPS' in content, "Should have operation whitelist"
|
||||
assert 'search' in content, "Whitelist should include 'search'"
|
||||
assert 'init' in content, "Whitelist should include 'init'"
|
||||
|
||||
def test_shell_metacharacter_rejection():
|
||||
"""electron-main.js should reject shell metacharacters in arguments."""
|
||||
content = open('electron-main.js').read()
|
||||
assert 'sanitizeArg' in content, "Should have argument sanitizer"
|
||||
assert 'metacharacter' in content.lower() or 'metacharacters' in content.lower() or '[;&|`$()' in content, \
|
||||
"Should check for shell metacharacters"
|
||||
|
||||
def test_mempalace_no_template_interpolation():
|
||||
"""mempalace.js should not use template literals with shell commands."""
|
||||
content = open('mempalace.js').read()
|
||||
# Should NOT have backtick strings with shell commands
|
||||
dangerous_patterns = re.findall(r'`mempalace\s', content)
|
||||
assert len(dangerous_patterns) == 0, \
|
||||
f"mempalace.js should not have template-interpolated shell commands, found: {dangerous_patterns}"
|
||||
|
||||
def test_mempalace_uses_safe_ipc():
|
||||
"""mempalace.js should use the safe mempalace-exec IPC."""
|
||||
content = open('mempalace.js').read()
|
||||
assert 'mempalaceExec' in content or '_exec' in content, \
|
||||
"mempalace.js should use safe IPC method"
|
||||
assert 'execPython' not in content, \
|
||||
"mempalace.js should not reference the legacy execPython"
|
||||
|
||||
def test_app_no_template_interpolation():
|
||||
"""app.js should not have template-interpolated shell commands."""
|
||||
content = open('app.js').read()
|
||||
dangerous = re.findall(r'`mempalace\s', content)
|
||||
assert len(dangerous) == 0, \
|
||||
f"app.js should not have template-interpolated mempalace commands, found: {dangerous}"
|
||||
|
||||
def test_preload_exposes_safe_api():
|
||||
"""preload.js should expose mempalaceExec through context bridge."""
|
||||
content = open('preload.js').read()
|
||||
assert 'mempalaceExec' in content, "preload.js should expose mempalaceExec"
|
||||
assert 'contextBridge' in content, "preload.js should use contextBridge"
|
||||
assert 'exec-python' in content, "preload.js should still expose legacy exec-python bridge"
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_no_raw_exec()
|
||||
test_command_whitelist()
|
||||
test_shell_metacharacter_rejection()
|
||||
test_mempalace_no_template_interpolation()
|
||||
test_mempalace_uses_safe_ipc()
|
||||
test_app_no_template_interpolation()
|
||||
test_preload_exposes_safe_api()
|
||||
print("All security tests passed")
|
||||
Reference in New Issue
Block a user