Compare commits
1 Commits
fix/1470
...
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),
|
||||
})
|
||||
@@ -1,24 +0,0 @@
|
||||
# PR Backlog Report — Timmy_Foundation/timmy-config
|
||||
|
||||
Generated: 2026-04-14 23:23:33
|
||||
|
||||
## Summary
|
||||
|
||||
- **Total Open PRs**: 50
|
||||
- **Stale (>30 days)**: 0
|
||||
- **Recent (<7 days)**: 50
|
||||
|
||||
## Recommendations
|
||||
|
||||
### Immediate Actions
|
||||
1. **Review stale PRs**: 0 PRs are >30 days old
|
||||
2. **Close duplicates**: Check for duplicate PRs on same issues
|
||||
3. **Assign reviewers**: Ensure each PR has a reviewer
|
||||
|
||||
### Process Improvements
|
||||
1. **Set SLAs**: Review within 48 hours, merge within 7 days
|
||||
2. **Weekly cleanup**: Run this analyzer weekly
|
||||
3. **Automate**: Add CI checks to prevent backlog
|
||||
|
||||
## Stale PRs (>30 days)
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
PR Backlog Analyzer for timmy-config
|
||||
|
||||
Analyzes open PRs and provides recommendations for cleanup.
|
||||
Issue: #1470
|
||||
"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def get_open_prs(repo: str, token: str) -> list:
|
||||
"""Get all open PRs from a repository."""
|
||||
result = subprocess.run([
|
||||
"curl", "-s", "-H", f"Authorization: token {token}",
|
||||
f"https://forge.alexanderwhitestone.com/api/v1/repos/{repo}/pulls?state=open&limit=100"
|
||||
], capture_output=True, text=True)
|
||||
|
||||
if result.returncode != 0:
|
||||
print(f"Error fetching PRs: {result.stderr}")
|
||||
return []
|
||||
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def analyze_pr(pr: dict) -> dict:
|
||||
"""Analyze a single PR."""
|
||||
created = datetime.fromisoformat(pr['created_at'].replace('Z', '+00:00'))
|
||||
age_days = (datetime.now(created.tzinfo) - created).days
|
||||
|
||||
labels = [l['name'] for l in pr.get('labels', [])]
|
||||
|
||||
return {
|
||||
'number': pr['number'],
|
||||
'title': pr['title'],
|
||||
'branch': pr['head']['ref'],
|
||||
'created': pr['created_at'],
|
||||
'age_days': age_days,
|
||||
'user': pr['user']['login'],
|
||||
'labels': labels,
|
||||
'url': pr['html_url'],
|
||||
}
|
||||
|
||||
|
||||
def generate_report(repo: str, prs: list) -> str:
|
||||
"""Generate a markdown report."""
|
||||
stale = [p for p in prs if p['age_days'] > 30]
|
||||
recent = [p for p in prs if p['age_days'] <= 7]
|
||||
|
||||
report = f"""# PR Backlog Report — {repo}
|
||||
|
||||
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
## Summary
|
||||
|
||||
- **Total Open PRs**: {len(prs)}
|
||||
- **Stale (>30 days)**: {len(stale)}
|
||||
- **Recent (<7 days)**: {len(recent)}
|
||||
|
||||
## Recommendations
|
||||
|
||||
### Immediate Actions
|
||||
1. **Review stale PRs**: {len(stale)} PRs are >30 days old
|
||||
2. **Close duplicates**: Check for duplicate PRs on same issues
|
||||
3. **Assign reviewers**: Ensure each PR has a reviewer
|
||||
|
||||
### Process Improvements
|
||||
1. **Set SLAs**: Review within 48 hours, merge within 7 days
|
||||
2. **Weekly cleanup**: Run this analyzer weekly
|
||||
3. **Automate**: Add CI checks to prevent backlog
|
||||
|
||||
## Stale PRs (>30 days)
|
||||
|
||||
"""
|
||||
|
||||
for pr in sorted(stale, key=lambda x: x['age_days'], reverse=True):
|
||||
report += f"- **#{pr['number']}**: {pr['title']}\n"
|
||||
report += f" - Age: {pr['age_days']} days\n"
|
||||
report += f" - Author: {pr['user']}\n"
|
||||
report += f" - URL: {pr['url']}\n\n"
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function."""
|
||||
token_path = Path.home() / '.config' / 'gitea' / 'token'
|
||||
if not token_path.exists():
|
||||
print("Error: Gitea token not found")
|
||||
sys.exit(1)
|
||||
|
||||
token = token_path.read_text().strip()
|
||||
repo = "Timmy_Foundation/timmy-config"
|
||||
|
||||
print(f"Fetching PRs for {repo}...")
|
||||
prs = get_open_prs(repo, token)
|
||||
|
||||
if not prs:
|
||||
print("No open PRs found")
|
||||
return
|
||||
|
||||
print(f"Found {len(prs)} open PRs")
|
||||
|
||||
analyzed = [analyze_pr(pr) for pr in prs]
|
||||
report = generate_report(repo, analyzed)
|
||||
|
||||
output_dir = Path("reports")
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
|
||||
report_file = output_dir / f"pr-backlog-{datetime.now().strftime('%Y%m%d')}.md"
|
||||
report_file.write_text(report)
|
||||
|
||||
print(f"Report saved to: {report_file}")
|
||||
print(f"Total PRs: {len(prs)}")
|
||||
print(f"Stale (>30 days): {len([p for p in analyzed if p['age_days'] > 30])}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
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