csvlod-ai-mcp-server
Version:
CSVLOD-AI MCP Server v3.0 with Quantum Context Intelligence - Revolutionary Context Intelligence Engine and Multimodal Processor for sovereign AI development
535 lines (526 loc) • 18.3 kB
JavaScript
import { z } from 'zod';
import { execSync } from 'child_process';
import * as fs from 'fs/promises';
export const sovereigntyGuardTool = {
name: 'sis_guard',
description: 'Sovereignty protection system - enforce user control and data privacy',
parameters: z.object({
action: z.enum(['scan', 'block', 'report', 'enforce', 'audit']).default('scan'),
policy: z.string().optional(),
auto_fix: z.boolean().default(false),
depth: z.enum(['surface', 'deep', 'paranoid']).default('deep')
}),
execute: async (args) => {
switch (args.action) {
case 'scan':
return await performSovereigntyScan(args.depth, args.auto_fix);
case 'block':
return await setupSovereigntyBlocking(args.policy);
case 'report':
return await generateSovereigntyReport();
case 'enforce':
return await enforceSovereignty(args.auto_fix);
case 'audit':
return await performSovereigntyAudit();
default:
return { error: 'Unknown action' };
}
}
};
async function performSovereigntyScan(depth, autoFix) {
// Run SIS sovereignty scan
const scanResult = execSync('./.sis/bin/sis guard scan', { encoding: 'utf-8' });
const violations = {
permissions: [],
external_calls: [],
telemetry: [],
credentials: [],
total: 0
};
// Parse scan results
const lines = scanResult.split('\n');
let currentCategory = '';
for (const line of lines) {
if (line.includes('Permissions:'))
currentCategory = 'permissions';
else if (line.includes('External calls:'))
currentCategory = 'external_calls';
else if (line.includes('Telemetry:'))
currentCategory = 'telemetry';
else if (line.includes('Credentials:'))
currentCategory = 'credentials';
else if (line.includes('WARN:') || line.includes('CRIT:')) {
const violation = {
severity: line.includes('CRIT:') ? 'critical' : 'warning',
details: line.trim(),
category: currentCategory
};
violations[currentCategory].push(violation);
violations.total++;
}
}
// Deep scan additions
if (depth === 'deep' || depth === 'paranoid') {
// Check for hidden tracking
const hiddenTracking = await scanForHiddenTracking();
violations.external_calls.push(...hiddenTracking);
violations.total += hiddenTracking.length;
// Check for data exfiltration risks
const exfilRisks = await scanForExfiltrationRisks();
violations.external_calls.push(...exfilRisks);
violations.total += exfilRisks.length;
}
// Paranoid mode
if (depth === 'paranoid') {
// Check all network capable code
const networkRisks = await scanNetworkCapableCode();
violations.external_calls.push(...networkRisks);
violations.total += networkRisks.length;
}
// Auto-fix if requested
if (autoFix && violations.total > 0) {
const fixes = await attemptAutoFixes(violations);
return {
violations,
fixes_applied: fixes,
status: fixes.length > 0 ? 'partially_fixed' : 'violations_remain'
};
}
return {
violations,
status: violations.total === 0 ? 'sovereign' : 'compromised',
recommendation: violations.total > 0 ? 'Run with auto_fix=true or manually address violations' : 'System is sovereign'
};
}
async function setupSovereigntyBlocking(policy) {
// Create or update blocking rules
const blockingRules = policy ? JSON.parse(policy) : getDefaultBlockingRules();
// Update .sovignore
const sovIgnorePath = './.sis/sovereignty/.sovignore';
await fs.mkdir('./.sis/sovereignty', { recursive: true });
const sovIgnoreContent = generateSovIgnore(blockingRules);
await fs.writeFile(sovIgnorePath, sovIgnoreContent);
// Create git hook
const hookContent = generateGitHook(blockingRules);
await fs.writeFile('./.sis/sovereignty/pre-commit-hook.sh', hookContent);
execSync('chmod +x ./.sis/sovereignty/pre-commit-hook.sh');
// Update .gitignore
await updateGitignore(blockingRules);
return {
rules_applied: Object.keys(blockingRules).length,
sovignore_path: sovIgnorePath,
git_hook_path: './.sis/sovereignty/pre-commit-hook.sh',
install_command: 'ln -sf ./.sis/sovereignty/pre-commit-hook.sh .git/hooks/pre-commit'
};
}
async function generateSovereigntyReport() {
const report = {
timestamp: new Date().toISOString(),
sovereignty_score: 100,
violations: [],
history: [],
recommendations: []
};
// Get current scan
const scanResult = await performSovereigntyScan('deep', false);
report.violations = scanResult.violations;
// Calculate score
report.sovereignty_score = Math.max(0, 100 - (scanResult.violations.total * 10));
// Load history
try {
const historyFiles = await fs.readdir('./.sis/sovereignty/history');
report.history = historyFiles.slice(-10).map(f => ({
date: f.replace('.json', ''),
file: f
}));
}
catch {
// No history yet
}
// Generate recommendations
if (scanResult.violations.credentials.length > 0) {
report.recommendations.push('Rotate all exposed credentials immediately');
report.recommendations.push('Use environment variables or secure vaults');
}
if (scanResult.violations.telemetry.length > 0) {
report.recommendations.push('Remove or disable all telemetry packages');
report.recommendations.push('Implement local-only analytics if needed');
}
if (scanResult.violations.external_calls.length > 0) {
report.recommendations.push('Review all external API calls');
report.recommendations.push('Implement local alternatives where possible');
}
// Save report
const reportPath = `./.sis/sovereignty/report-${Date.now()}.json`;
await fs.writeFile(reportPath, JSON.stringify(report, null, 2));
return report;
}
async function enforceSovereignty(autoFix) {
const actions = [];
// 1. Remove telemetry packages
try {
const packageJson = await fs.readFile('./package.json', 'utf-8');
const pkg = JSON.parse(packageJson);
const telemetryPackages = [
'@sentry/node', 'sentry', 'analytics-node', 'mixpanel',
'amplitude', 'segment', 'datadog', 'newrelic'
];
let modified = false;
for (const dep of telemetryPackages) {
if (pkg.dependencies?.[dep]) {
delete pkg.dependencies[dep];
modified = true;
actions.push(`Removed dependency: ${dep}`);
}
if (pkg.devDependencies?.[dep]) {
delete pkg.devDependencies[dep];
modified = true;
actions.push(`Removed devDependency: ${dep}`);
}
}
if (modified && autoFix) {
await fs.writeFile('./package.json', JSON.stringify(pkg, null, 2));
execSync('npm install');
}
}
catch {
// Not a Node project
}
// 2. Fix file permissions
const badPerms = execSync('find . -type f -perm /go+w -not -path "./.git/*"', {
encoding: 'utf-8'
}).split('\n').filter(Boolean);
for (const file of badPerms) {
if (autoFix) {
execSync(`chmod 644 "${file}"`);
actions.push(`Fixed permissions: ${file}`);
}
else {
actions.push(`Would fix permissions: ${file}`);
}
}
// 3. Remove external tracking code
const trackingPatterns = [
'google-analytics.com',
'googletagmanager.com',
'facebook.com/tr',
'analytics.amplitude.com'
];
const filesToCheck = execSync('find . -name "*.html" -o -name "*.js" -o -name "*.ts"', {
encoding: 'utf-8'
}).split('\n').filter(Boolean);
for (const file of filesToCheck.slice(0, 100)) { // Limit to 100 files
try {
let content = await fs.readFile(file, 'utf-8');
let modified = false;
for (const pattern of trackingPatterns) {
if (content.includes(pattern)) {
if (autoFix) {
content = content.replace(new RegExp(`[^\\n]*${pattern}[^\\n]*\\n`, 'g'), '');
modified = true;
actions.push(`Removed tracking from: ${file}`);
}
else {
actions.push(`Would remove tracking from: ${file}`);
}
}
}
if (modified && autoFix) {
await fs.writeFile(file, content);
}
}
catch {
// Skip unreadable files
}
}
return {
actions_taken: actions.filter(a => !a.startsWith('Would')),
actions_planned: actions.filter(a => a.startsWith('Would')),
enforcement_level: autoFix ? 'active' : 'dry_run',
sovereignty_improved: actions.length > 0
};
}
async function performSovereigntyAudit() {
const audit = {
timestamp: new Date().toISOString(),
checks_performed: [],
compliance: {},
score: 0
};
// Network isolation check
const networkCheck = await checkNetworkIsolation();
audit.checks_performed.push('network_isolation');
audit.compliance.network_isolation = networkCheck;
// Data locality check
const dataCheck = await checkDataLocality();
audit.checks_performed.push('data_locality');
audit.compliance.data_locality = dataCheck;
// Dependency audit
const depCheck = await auditDependencies();
audit.checks_performed.push('dependency_sovereignty');
audit.compliance.dependency_sovereignty = depCheck;
// Calculate overall score
const scores = Object.values(audit.compliance).map((c) => c.score || 0);
audit.score = scores.reduce((a, b) => a + b, 0) / scores.length;
return audit;
}
// Helper functions
async function scanForHiddenTracking() {
const violations = [];
// Check for base64 encoded URLs
const files = execSync('find . -name "*.js" -o -name "*.ts" | head -50', {
encoding: 'utf-8'
}).split('\n').filter(Boolean);
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf-8');
// Look for base64 that might decode to tracking URLs
const base64Pattern = /[A-Za-z0-9+/]{20,}={0,2}/g;
const matches = content.match(base64Pattern) || [];
for (const match of matches) {
try {
const decoded = Buffer.from(match, 'base64').toString();
if (decoded.includes('http') && decoded.includes('track')) {
violations.push({
severity: 'warning',
details: `Hidden tracking in ${file}`,
category: 'external_calls'
});
}
}
catch {
// Not valid base64
}
}
}
catch {
// Skip file
}
}
return violations;
}
async function scanForExfiltrationRisks() {
const violations = [];
// Check for fetch/axios calls with user data
const patterns = [
/fetch\s*\([^)]*\).*body\s*:/,
/axios\.(post|put)\s*\(/,
/XMLHttpRequest/
];
const files = execSync('find . -name "*.js" -o -name "*.ts" | head -50', {
encoding: 'utf-8'
}).split('\n').filter(Boolean);
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf-8');
for (const pattern of patterns) {
if (pattern.test(content)) {
violations.push({
severity: 'warning',
details: `Potential data exfiltration risk in ${file}`,
category: 'external_calls'
});
break;
}
}
}
catch {
// Skip file
}
}
return violations;
}
async function scanNetworkCapableCode() {
const violations = [];
// Any code that could make network requests
const patterns = [
'require("http")',
'require("https")',
'import.*http',
'WebSocket',
'EventSource'
];
const files = execSync('find . -name "*.js" -o -name "*.ts" | head -30', {
encoding: 'utf-8'
}).split('\n').filter(Boolean);
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf-8');
for (const pattern of patterns) {
if (content.includes(pattern)) {
violations.push({
severity: 'info',
details: `Network capable code in ${file}`,
category: 'external_calls'
});
break;
}
}
}
catch {
// Skip file
}
}
return violations;
}
async function attemptAutoFixes(violations) {
const fixes = [];
// Fix permissions
if (violations.permissions.length > 0) {
for (const violation of violations.permissions) {
const match = violation.details.match(/WARN: (.+) \((\d+)\)/);
if (match) {
const file = match[1];
try {
execSync(`chmod 644 "${file}"`);
fixes.push(`Fixed permissions for ${file}`);
}
catch {
// Skip if can't fix
}
}
}
}
return fixes;
}
function getDefaultBlockingRules() {
return {
file_patterns: [
'*.key', '*.pem', '*.pfx', '*.p12',
'.env*', 'secrets.*', 'credentials.*'
],
content_patterns: [
'analytics', 'telemetry', 'tracking',
'sentry', 'datadog', 'mixpanel'
],
network_patterns: [
'https?://(?!localhost|127.0.0.1)',
'wss?://(?!localhost|127.0.0.1)'
]
};
}
function generateSovIgnore(rules) {
return `# SIS Sovereignty Ignore Rules
# Generated: ${new Date().toISOString()}
# File patterns to block
${rules.file_patterns.join('\n')}
# Content that should not exist
${rules.content_patterns.map((p) => `*${p}*`).join('\n')}
# Binary and compiled files
*.exe
*.dll
*.so
*.dylib
*.wasm
# Temporary files
*.tmp
*.temp
*.bak
*.swp
*~
`;
}
function generateGitHook(rules) {
return `#!/bin/bash
# SIS Sovereignty Git Hook
# Generated: ${new Date().toISOString()}
set -euo pipefail
echo "🛡️ SIS Sovereignty Check..."
# Run sovereignty scan
if ! ./.sis/bin/sis guard scan; then
echo "❌ Sovereignty violations detected"
echo "Run './.sis/bin/sis guard report' for details"
exit 1
fi
# Check staged files against patterns
for pattern in ${rules.file_patterns.join(' ')}; do
if git diff --cached --name-only | grep -q "$pattern"; then
echo "❌ Blocked by sovereignty rule: $pattern"
exit 1
fi
done
echo "✅ Sovereignty check passed"
`;
}
async function updateGitignore(rules) {
try {
let gitignore = await fs.readFile('.gitignore', 'utf-8');
// Add sovereignty section if not exists
if (!gitignore.includes('# SIS Sovereignty')) {
gitignore += `
# SIS Sovereignty
${rules.file_patterns.join('\n')}
`;
await fs.writeFile('.gitignore', gitignore);
}
}
catch {
// Create new .gitignore
const content = `# SIS Sovereignty
${rules.file_patterns.join('\n')}
`;
await fs.writeFile('.gitignore', content);
}
}
async function checkNetworkIsolation() {
const check = {
passed: true,
score: 100,
findings: []
};
// Check for external API calls
const externalAPIs = execSync('grep -r "https://" --include="*.js" --include="*.ts" . | grep -v localhost | wc -l', { encoding: 'utf-8' }).trim();
if (parseInt(externalAPIs) > 0) {
check.passed = false;
check.score -= 20;
check.findings.push(`Found ${externalAPIs} external API references`);
}
return check;
}
async function checkDataLocality() {
const check = {
passed: true,
score: 100,
findings: []
};
// Check for cloud storage references
const cloudPatterns = ['s3.amazonaws.com', 'storage.googleapis.com', 'blob.core.windows.net'];
for (const pattern of cloudPatterns) {
const found = execSync(`grep -r "${pattern}" --include="*.js" --include="*.ts" . | wc -l`, { encoding: 'utf-8' }).trim();
if (parseInt(found) > 0) {
check.passed = false;
check.score -= 10;
check.findings.push(`Found ${found} references to ${pattern}`);
}
}
return check;
}
async function auditDependencies() {
const check = {
passed: true,
score: 100,
findings: []
};
try {
const packageJson = await fs.readFile('./package.json', 'utf-8');
const pkg = JSON.parse(packageJson);
const suspiciousPackages = [
'electron-updater', // Auto-updates
'node-machine-id', // Device fingerprinting
'public-ip', // IP detection
'geoip-lite' // Location tracking
];
for (const suspicious of suspiciousPackages) {
if (pkg.dependencies?.[suspicious] || pkg.devDependencies?.[suspicious]) {
check.passed = false;
check.score -= 15;
check.findings.push(`Suspicious package: ${suspicious}`);
}
}
}
catch {
// Not a Node project
}
return check;
}
//# sourceMappingURL=sovereignty-guard.js.map