defense-mcp-server 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/CHANGELOG.md +471 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/build/core/auto-installer.d.ts +102 -0
  5. package/build/core/auto-installer.d.ts.map +1 -0
  6. package/build/core/auto-installer.js +833 -0
  7. package/build/core/backup-manager.d.ts +63 -0
  8. package/build/core/backup-manager.d.ts.map +1 -0
  9. package/build/core/backup-manager.js +189 -0
  10. package/build/core/changelog.d.ts +75 -0
  11. package/build/core/changelog.d.ts.map +1 -0
  12. package/build/core/changelog.js +123 -0
  13. package/build/core/command-allowlist.d.ts +129 -0
  14. package/build/core/command-allowlist.d.ts.map +1 -0
  15. package/build/core/command-allowlist.js +849 -0
  16. package/build/core/config.d.ts +79 -0
  17. package/build/core/config.d.ts.map +1 -0
  18. package/build/core/config.js +193 -0
  19. package/build/core/dependency-validator.d.ts +106 -0
  20. package/build/core/dependency-validator.d.ts.map +1 -0
  21. package/build/core/dependency-validator.js +405 -0
  22. package/build/core/distro-adapter.d.ts +177 -0
  23. package/build/core/distro-adapter.d.ts.map +1 -0
  24. package/build/core/distro-adapter.js +481 -0
  25. package/build/core/distro.d.ts +68 -0
  26. package/build/core/distro.d.ts.map +1 -0
  27. package/build/core/distro.js +457 -0
  28. package/build/core/encrypted-state.d.ts +76 -0
  29. package/build/core/encrypted-state.d.ts.map +1 -0
  30. package/build/core/encrypted-state.js +209 -0
  31. package/build/core/executor.d.ts +56 -0
  32. package/build/core/executor.d.ts.map +1 -0
  33. package/build/core/executor.js +350 -0
  34. package/build/core/installer.d.ts +92 -0
  35. package/build/core/installer.d.ts.map +1 -0
  36. package/build/core/installer.js +1072 -0
  37. package/build/core/logger.d.ts +102 -0
  38. package/build/core/logger.d.ts.map +1 -0
  39. package/build/core/logger.js +132 -0
  40. package/build/core/parsers.d.ts +151 -0
  41. package/build/core/parsers.d.ts.map +1 -0
  42. package/build/core/parsers.js +479 -0
  43. package/build/core/policy-engine.d.ts +170 -0
  44. package/build/core/policy-engine.d.ts.map +1 -0
  45. package/build/core/policy-engine.js +656 -0
  46. package/build/core/preflight.d.ts +157 -0
  47. package/build/core/preflight.d.ts.map +1 -0
  48. package/build/core/preflight.js +638 -0
  49. package/build/core/privilege-manager.d.ts +108 -0
  50. package/build/core/privilege-manager.d.ts.map +1 -0
  51. package/build/core/privilege-manager.js +363 -0
  52. package/build/core/rate-limiter.d.ts +67 -0
  53. package/build/core/rate-limiter.d.ts.map +1 -0
  54. package/build/core/rate-limiter.js +129 -0
  55. package/build/core/rollback.d.ts +73 -0
  56. package/build/core/rollback.d.ts.map +1 -0
  57. package/build/core/rollback.js +278 -0
  58. package/build/core/safeguards.d.ts +58 -0
  59. package/build/core/safeguards.d.ts.map +1 -0
  60. package/build/core/safeguards.js +448 -0
  61. package/build/core/sanitizer.d.ts +118 -0
  62. package/build/core/sanitizer.d.ts.map +1 -0
  63. package/build/core/sanitizer.js +459 -0
  64. package/build/core/secure-fs.d.ts +67 -0
  65. package/build/core/secure-fs.d.ts.map +1 -0
  66. package/build/core/secure-fs.js +143 -0
  67. package/build/core/spawn-safe.d.ts +55 -0
  68. package/build/core/spawn-safe.d.ts.map +1 -0
  69. package/build/core/spawn-safe.js +146 -0
  70. package/build/core/sudo-guard.d.ts +145 -0
  71. package/build/core/sudo-guard.d.ts.map +1 -0
  72. package/build/core/sudo-guard.js +349 -0
  73. package/build/core/sudo-session.d.ts +100 -0
  74. package/build/core/sudo-session.d.ts.map +1 -0
  75. package/build/core/sudo-session.js +319 -0
  76. package/build/core/tool-dependencies.d.ts +61 -0
  77. package/build/core/tool-dependencies.d.ts.map +1 -0
  78. package/build/core/tool-dependencies.js +571 -0
  79. package/build/core/tool-registry.d.ts +111 -0
  80. package/build/core/tool-registry.d.ts.map +1 -0
  81. package/build/core/tool-registry.js +656 -0
  82. package/build/core/tool-wrapper.d.ts +73 -0
  83. package/build/core/tool-wrapper.d.ts.map +1 -0
  84. package/build/core/tool-wrapper.js +296 -0
  85. package/build/index.d.ts +3 -0
  86. package/build/index.d.ts.map +1 -0
  87. package/build/index.js +247 -0
  88. package/build/tools/access-control.d.ts +9 -0
  89. package/build/tools/access-control.d.ts.map +1 -0
  90. package/build/tools/access-control.js +1818 -0
  91. package/build/tools/api-security.d.ts +12 -0
  92. package/build/tools/api-security.d.ts.map +1 -0
  93. package/build/tools/api-security.js +901 -0
  94. package/build/tools/app-hardening.d.ts +11 -0
  95. package/build/tools/app-hardening.d.ts.map +1 -0
  96. package/build/tools/app-hardening.js +768 -0
  97. package/build/tools/backup.d.ts +8 -0
  98. package/build/tools/backup.d.ts.map +1 -0
  99. package/build/tools/backup.js +381 -0
  100. package/build/tools/cloud-security.d.ts +17 -0
  101. package/build/tools/cloud-security.d.ts.map +1 -0
  102. package/build/tools/cloud-security.js +739 -0
  103. package/build/tools/compliance.d.ts +10 -0
  104. package/build/tools/compliance.d.ts.map +1 -0
  105. package/build/tools/compliance.js +1225 -0
  106. package/build/tools/container-security.d.ts +14 -0
  107. package/build/tools/container-security.d.ts.map +1 -0
  108. package/build/tools/container-security.js +788 -0
  109. package/build/tools/deception.d.ts +13 -0
  110. package/build/tools/deception.d.ts.map +1 -0
  111. package/build/tools/deception.js +763 -0
  112. package/build/tools/dns-security.d.ts +93 -0
  113. package/build/tools/dns-security.d.ts.map +1 -0
  114. package/build/tools/dns-security.js +745 -0
  115. package/build/tools/drift-detection.d.ts +8 -0
  116. package/build/tools/drift-detection.d.ts.map +1 -0
  117. package/build/tools/drift-detection.js +326 -0
  118. package/build/tools/ebpf-security.d.ts +15 -0
  119. package/build/tools/ebpf-security.d.ts.map +1 -0
  120. package/build/tools/ebpf-security.js +294 -0
  121. package/build/tools/encryption.d.ts +9 -0
  122. package/build/tools/encryption.d.ts.map +1 -0
  123. package/build/tools/encryption.js +1667 -0
  124. package/build/tools/firewall.d.ts +9 -0
  125. package/build/tools/firewall.d.ts.map +1 -0
  126. package/build/tools/firewall.js +1398 -0
  127. package/build/tools/hardening.d.ts +10 -0
  128. package/build/tools/hardening.d.ts.map +1 -0
  129. package/build/tools/hardening.js +2654 -0
  130. package/build/tools/ids.d.ts +9 -0
  131. package/build/tools/ids.d.ts.map +1 -0
  132. package/build/tools/ids.js +624 -0
  133. package/build/tools/incident-response.d.ts +10 -0
  134. package/build/tools/incident-response.d.ts.map +1 -0
  135. package/build/tools/incident-response.js +1180 -0
  136. package/build/tools/logging.d.ts +12 -0
  137. package/build/tools/logging.d.ts.map +1 -0
  138. package/build/tools/logging.js +454 -0
  139. package/build/tools/malware.d.ts +10 -0
  140. package/build/tools/malware.d.ts.map +1 -0
  141. package/build/tools/malware.js +532 -0
  142. package/build/tools/meta.d.ts +11 -0
  143. package/build/tools/meta.d.ts.map +1 -0
  144. package/build/tools/meta.js +2278 -0
  145. package/build/tools/network-defense.d.ts +12 -0
  146. package/build/tools/network-defense.d.ts.map +1 -0
  147. package/build/tools/network-defense.js +760 -0
  148. package/build/tools/patch-management.d.ts +3 -0
  149. package/build/tools/patch-management.d.ts.map +1 -0
  150. package/build/tools/patch-management.js +708 -0
  151. package/build/tools/process-security.d.ts +12 -0
  152. package/build/tools/process-security.d.ts.map +1 -0
  153. package/build/tools/process-security.js +784 -0
  154. package/build/tools/reporting.d.ts +11 -0
  155. package/build/tools/reporting.d.ts.map +1 -0
  156. package/build/tools/reporting.js +559 -0
  157. package/build/tools/secrets.d.ts +9 -0
  158. package/build/tools/secrets.d.ts.map +1 -0
  159. package/build/tools/secrets.js +596 -0
  160. package/build/tools/siem-integration.d.ts +18 -0
  161. package/build/tools/siem-integration.d.ts.map +1 -0
  162. package/build/tools/siem-integration.js +754 -0
  163. package/build/tools/sudo-management.d.ts +18 -0
  164. package/build/tools/sudo-management.d.ts.map +1 -0
  165. package/build/tools/sudo-management.js +737 -0
  166. package/build/tools/supply-chain-security.d.ts +8 -0
  167. package/build/tools/supply-chain-security.d.ts.map +1 -0
  168. package/build/tools/supply-chain-security.js +256 -0
  169. package/build/tools/threat-intel.d.ts +22 -0
  170. package/build/tools/threat-intel.d.ts.map +1 -0
  171. package/build/tools/threat-intel.js +749 -0
  172. package/build/tools/vulnerability-management.d.ts +11 -0
  173. package/build/tools/vulnerability-management.d.ts.map +1 -0
  174. package/build/tools/vulnerability-management.js +667 -0
  175. package/build/tools/waf.d.ts +12 -0
  176. package/build/tools/waf.d.ts.map +1 -0
  177. package/build/tools/waf.js +843 -0
  178. package/build/tools/wireless-security.d.ts +19 -0
  179. package/build/tools/wireless-security.d.ts.map +1 -0
  180. package/build/tools/wireless-security.js +826 -0
  181. package/build/tools/zero-trust-network.d.ts +8 -0
  182. package/build/tools/zero-trust-network.d.ts.map +1 -0
  183. package/build/tools/zero-trust-network.js +367 -0
  184. package/docs/SAFEGUARDS.md +518 -0
  185. package/docs/TOOLS-REFERENCE.md +665 -0
  186. package/package.json +87 -0
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Dependency Validator for Kali Defense MCP Server.
3
+ *
4
+ * Provides three key capabilities:
5
+ * 1. **Startup validation** — checks all tool dependencies when the server starts
6
+ * and auto-installs missing ones if KALI_DEFENSE_AUTO_INSTALL=true
7
+ * 2. **Runtime dependency check** — `ensureDependencies()` can be called before
8
+ * any tool execution to verify (and optionally install) required binaries
9
+ * 3. **Dependency status cache** — avoids redundant `which` calls by caching
10
+ * binary availability results with a configurable TTL
11
+ */
12
+ import { executeCommand } from "./executor.js";
13
+ import { getConfig } from "./config.js";
14
+ import { checkTool, installTool, } from "./installer.js";
15
+ import { TOOL_DEPENDENCIES, getDependenciesForTool, getToolRequirementForBinary, getCriticalDependencies, } from "./tool-dependencies.js";
16
+ // ── Cache ────────────────────────────────────────────────────────────────────
17
+ /** Cache TTL in milliseconds (5 minutes) */
18
+ const CACHE_TTL_MS = 5 * 60 * 1000;
19
+ /** Binary availability cache */
20
+ const binaryCache = new Map();
21
+ /**
22
+ * Checks if a binary is available, using cache when possible.
23
+ */
24
+ async function isBinaryAvailable(binary) {
25
+ const cached = binaryCache.get(binary);
26
+ if (cached && Date.now() - cached.checkedAt < CACHE_TTL_MS) {
27
+ return cached;
28
+ }
29
+ const result = await checkTool(binary);
30
+ const status = {
31
+ available: result.installed,
32
+ path: result.path,
33
+ version: result.version,
34
+ checkedAt: Date.now(),
35
+ };
36
+ binaryCache.set(binary, status);
37
+ return status;
38
+ }
39
+ /**
40
+ * Invalidates the cache for a specific binary (e.g. after installation).
41
+ */
42
+ function invalidateCache(binary) {
43
+ binaryCache.delete(binary);
44
+ }
45
+ /**
46
+ * Clears the entire binary cache.
47
+ */
48
+ export function clearDependencyCache() {
49
+ binaryCache.clear();
50
+ }
51
+ // ── Auto-install logic ───────────────────────────────────────────────────────
52
+ /**
53
+ * Attempts to install a binary by finding its ToolRequirement in DEFENSIVE_TOOLS.
54
+ * Returns the install result or null if no matching package is known.
55
+ */
56
+ async function autoInstallBinary(binary) {
57
+ // First check the DEFENSIVE_TOOLS registry
58
+ const toolReq = getToolRequirementForBinary(binary);
59
+ if (toolReq) {
60
+ console.error(`[dep-validator] Auto-installing ${toolReq.name} (provides: ${binary})`);
61
+ const result = await installTool(toolReq);
62
+ if (result.success) {
63
+ invalidateCache(binary);
64
+ }
65
+ return result;
66
+ }
67
+ // For binaries not in DEFENSIVE_TOOLS, try a direct package install
68
+ // Many system utilities have the same package name as the binary
69
+ const directInstallReq = {
70
+ name: binary,
71
+ binary,
72
+ packages: {
73
+ debian: binary,
74
+ rhel: binary,
75
+ arch: binary,
76
+ alpine: binary,
77
+ suse: binary,
78
+ fallback: binary,
79
+ },
80
+ category: "hardening",
81
+ required: false,
82
+ };
83
+ console.error(`[dep-validator] Attempting direct install of '${binary}' (no known package mapping)`);
84
+ const result = await installTool(directInstallReq);
85
+ if (result.success) {
86
+ invalidateCache(binary);
87
+ }
88
+ return result;
89
+ }
90
+ // ── Startup Validation ───────────────────────────────────────────────────────
91
+ /**
92
+ * Validates all tool dependencies at server startup.
93
+ *
94
+ * This function:
95
+ * 1. Collects all unique binaries required across all tools
96
+ * 2. Checks each binary's availability
97
+ * 3. If autoInstall is enabled, installs missing binaries
98
+ * 4. Reports critical tools with missing dependencies
99
+ *
100
+ * @returns A detailed validation report
101
+ */
102
+ export async function validateAllDependencies() {
103
+ const startTime = Date.now();
104
+ const config = getConfig();
105
+ console.error("[dep-validator] Starting dependency validation...");
106
+ // Collect all unique binaries (required only — optional are checked lazily)
107
+ const allBinaries = new Set();
108
+ for (const dep of TOOL_DEPENDENCIES) {
109
+ for (const bin of dep.requiredBinaries) {
110
+ // Skip trivially-available system utilities
111
+ if (!TRIVIAL_BINARIES.has(bin)) {
112
+ allBinaries.add(bin);
113
+ }
114
+ }
115
+ }
116
+ const available = [];
117
+ const missing = [];
118
+ const installed = [];
119
+ const installFailed = [];
120
+ // Check all binaries in parallel (batched to avoid overwhelming the system)
121
+ const binaryList = Array.from(allBinaries);
122
+ const BATCH_SIZE = 10;
123
+ for (let i = 0; i < binaryList.length; i += BATCH_SIZE) {
124
+ const batch = binaryList.slice(i, i + BATCH_SIZE);
125
+ const results = await Promise.all(batch.map(async (bin) => ({
126
+ binary: bin,
127
+ status: await isBinaryAvailable(bin),
128
+ })));
129
+ for (const { binary, status } of results) {
130
+ if (status.available) {
131
+ available.push(binary);
132
+ }
133
+ else {
134
+ missing.push(binary);
135
+ }
136
+ }
137
+ }
138
+ // Auto-install missing binaries if enabled
139
+ if (config.autoInstall && missing.length > 0) {
140
+ console.error(`[dep-validator] Auto-install enabled. Installing ${missing.length} missing binaries...`);
141
+ // Update package lists once before installing
142
+ const { detectDistro, getPackageManager } = await import("./distro.js");
143
+ const distro = await detectDistro();
144
+ const pkgMgr = getPackageManager(distro.packageManager);
145
+ const updateCmd = pkgMgr.updateCmd();
146
+ console.error(`[dep-validator] Updating package lists via ${distro.packageManager}...`);
147
+ await executeCommand({
148
+ command: "sudo",
149
+ args: updateCmd,
150
+ timeout: 120_000,
151
+ });
152
+ // Install each missing binary
153
+ const toInstall = [...missing];
154
+ missing.length = 0; // Reset — we'll re-populate with truly-missing ones
155
+ for (const binary of toInstall) {
156
+ const result = await autoInstallBinary(binary);
157
+ if (result?.success) {
158
+ // Verify the binary is now available
159
+ invalidateCache(binary);
160
+ const recheck = await isBinaryAvailable(binary);
161
+ if (recheck.available) {
162
+ installed.push(binary);
163
+ available.push(binary);
164
+ console.error(`[dep-validator] ✅ Installed: ${binary}`);
165
+ }
166
+ else {
167
+ missing.push(binary);
168
+ installFailed.push({
169
+ binary,
170
+ error: "Package installed but binary not found in PATH",
171
+ });
172
+ console.error(`[dep-validator] ⚠️ Package installed but binary '${binary}' not found`);
173
+ }
174
+ }
175
+ else {
176
+ missing.push(binary);
177
+ installFailed.push({
178
+ binary,
179
+ error: result?.message ?? "No package mapping found",
180
+ });
181
+ console.error(`[dep-validator] ❌ Failed to install: ${binary}`);
182
+ }
183
+ }
184
+ }
185
+ // Check critical tools
186
+ const criticalMissing = [];
187
+ const criticalDeps = getCriticalDependencies();
188
+ for (const dep of criticalDeps) {
189
+ const missingBins = dep.requiredBinaries.filter((bin) => !TRIVIAL_BINARIES.has(bin) && missing.includes(bin));
190
+ if (missingBins.length > 0) {
191
+ criticalMissing.push({
192
+ toolName: dep.toolName,
193
+ missingBinaries: missingBins,
194
+ });
195
+ }
196
+ }
197
+ const durationMs = Date.now() - startTime;
198
+ const report = {
199
+ totalChecked: binaryList.length,
200
+ available,
201
+ missing,
202
+ installed,
203
+ installFailed,
204
+ criticalMissing,
205
+ durationMs,
206
+ autoInstallEnabled: config.autoInstall,
207
+ };
208
+ // Log summary
209
+ console.error(`[dep-validator] Validation complete in ${durationMs}ms: ` +
210
+ `${available.length} available, ${missing.length} missing` +
211
+ (installed.length > 0 ? `, ${installed.length} auto-installed` : "") +
212
+ (installFailed.length > 0 ? `, ${installFailed.length} install failures` : ""));
213
+ if (criticalMissing.length > 0) {
214
+ console.error(`[dep-validator] ⚠️ CRITICAL: ${criticalMissing.length} critical tools have missing dependencies:`);
215
+ for (const cm of criticalMissing) {
216
+ console.error(`[dep-validator] - ${cm.toolName}: needs ${cm.missingBinaries.join(", ")}`);
217
+ }
218
+ console.error(`[dep-validator] Set KALI_DEFENSE_AUTO_INSTALL=true to auto-install missing tools`);
219
+ }
220
+ return report;
221
+ }
222
+ // ── Runtime Dependency Check ─────────────────────────────────────────────────
223
+ /**
224
+ * Ensures all dependencies for a specific MCP tool are satisfied.
225
+ *
226
+ * Call this at the start of any tool handler to verify its binaries are present.
227
+ * If autoInstall is enabled, missing binaries will be installed on-the-fly.
228
+ *
229
+ * @param toolName The MCP tool name (e.g. "ids_rkhunter_scan")
230
+ * @returns EnsureResult with satisfaction status and details
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * const deps = await ensureDependencies("ids_rkhunter_scan");
235
+ * if (!deps.satisfied) {
236
+ * return {
237
+ * content: [createErrorContent(
238
+ * `Missing required tools: ${deps.missingRequired.join(", ")}. ` +
239
+ * `Install with: sudo apt install ${deps.missingRequired.join(" ")}`
240
+ * )],
241
+ * isError: true,
242
+ * };
243
+ * }
244
+ * ```
245
+ */
246
+ export async function ensureDependencies(toolName) {
247
+ const dep = getDependenciesForTool(toolName);
248
+ // If no dependency info registered, assume satisfied
249
+ if (!dep) {
250
+ return {
251
+ satisfied: true,
252
+ missingRequired: [],
253
+ missingOptional: [],
254
+ autoInstalled: [],
255
+ installErrors: [],
256
+ };
257
+ }
258
+ const config = getConfig();
259
+ const missingRequired = [];
260
+ const missingOptional = [];
261
+ const autoInstalled = [];
262
+ const installErrors = [];
263
+ // Check required binaries
264
+ for (const bin of dep.requiredBinaries) {
265
+ if (TRIVIAL_BINARIES.has(bin))
266
+ continue;
267
+ const status = await isBinaryAvailable(bin);
268
+ if (!status.available) {
269
+ if (config.autoInstall) {
270
+ const result = await autoInstallBinary(bin);
271
+ if (result?.success) {
272
+ invalidateCache(bin);
273
+ const recheck = await isBinaryAvailable(bin);
274
+ if (recheck.available) {
275
+ autoInstalled.push(bin);
276
+ continue;
277
+ }
278
+ }
279
+ installErrors.push({
280
+ binary: bin,
281
+ error: result?.message ?? "Installation failed",
282
+ });
283
+ }
284
+ missingRequired.push(bin);
285
+ }
286
+ }
287
+ // Check optional binaries (never block on these)
288
+ for (const bin of dep.optionalBinaries ?? []) {
289
+ if (TRIVIAL_BINARIES.has(bin))
290
+ continue;
291
+ const status = await isBinaryAvailable(bin);
292
+ if (!status.available) {
293
+ // Try auto-install for optional deps too, but don't fail
294
+ if (config.autoInstall) {
295
+ const result = await autoInstallBinary(bin);
296
+ if (result?.success) {
297
+ invalidateCache(bin);
298
+ const recheck = await isBinaryAvailable(bin);
299
+ if (recheck.available) {
300
+ autoInstalled.push(bin);
301
+ continue;
302
+ }
303
+ }
304
+ }
305
+ missingOptional.push(bin);
306
+ }
307
+ }
308
+ return {
309
+ satisfied: missingRequired.length === 0,
310
+ missingRequired,
311
+ missingOptional,
312
+ autoInstalled,
313
+ installErrors,
314
+ };
315
+ }
316
+ /**
317
+ * Quick check if a single binary is available (cached).
318
+ * Does NOT auto-install. Use for lightweight pre-flight checks.
319
+ */
320
+ export async function isBinaryInstalled(binary) {
321
+ if (TRIVIAL_BINARIES.has(binary))
322
+ return true;
323
+ const status = await isBinaryAvailable(binary);
324
+ return status.available;
325
+ }
326
+ // ── Format helpers ───────────────────────────────────────────────────────────
327
+ /**
328
+ * Formats a ValidationReport into a human-readable string for logging.
329
+ */
330
+ export function formatValidationReport(report) {
331
+ const lines = [];
332
+ lines.push("╔══════════════════════════════════════════════════════════╗");
333
+ lines.push("║ Kali Defense MCP — Dependency Validation ║");
334
+ lines.push("╚══════════════════════════════════════════════════════════╝");
335
+ lines.push("");
336
+ lines.push(` Binaries checked: ${report.totalChecked}`);
337
+ lines.push(` Available: ${report.available.length}`);
338
+ lines.push(` Missing: ${report.missing.length}`);
339
+ if (report.installed.length > 0) {
340
+ lines.push(` Auto-installed: ${report.installed.length}`);
341
+ for (const bin of report.installed) {
342
+ lines.push(` ✅ ${bin}`);
343
+ }
344
+ }
345
+ if (report.installFailed.length > 0) {
346
+ lines.push(` Install failures: ${report.installFailed.length}`);
347
+ for (const fail of report.installFailed) {
348
+ lines.push(` ❌ ${fail.binary}: ${fail.error}`);
349
+ }
350
+ }
351
+ if (report.missing.length > 0) {
352
+ lines.push("");
353
+ lines.push(" Missing binaries:");
354
+ for (const bin of report.missing) {
355
+ const toolReq = getToolRequirementForBinary(bin);
356
+ const pkg = toolReq ? ` (package: ${toolReq.packages.debian ?? toolReq.packages.fallback})` : "";
357
+ lines.push(` • ${bin}${pkg}`);
358
+ }
359
+ }
360
+ if (report.criticalMissing.length > 0) {
361
+ lines.push("");
362
+ lines.push(" ⚠️ CRITICAL tools with missing dependencies:");
363
+ for (const cm of report.criticalMissing) {
364
+ lines.push(` ⛔ ${cm.toolName}: needs ${cm.missingBinaries.join(", ")}`);
365
+ }
366
+ }
367
+ lines.push("");
368
+ lines.push(` Auto-install: ${report.autoInstallEnabled ? "ENABLED" : "DISABLED"}`);
369
+ if (!report.autoInstallEnabled && report.missing.length > 0) {
370
+ lines.push(" 💡 Set KALI_DEFENSE_AUTO_INSTALL=true to auto-install missing tools");
371
+ }
372
+ lines.push(` Duration: ${report.durationMs}ms`);
373
+ return lines.join("\n");
374
+ }
375
+ // ── Trivial binaries ─────────────────────────────────────────────────────────
376
+ /**
377
+ * System utilities that are virtually always present on any Linux system.
378
+ * We skip checking these to avoid unnecessary overhead.
379
+ */
380
+ const TRIVIAL_BINARIES = new Set([
381
+ "cat",
382
+ "cp",
383
+ "ls",
384
+ "mv",
385
+ "rm",
386
+ "tee",
387
+ "find",
388
+ "grep",
389
+ "awk",
390
+ "sed",
391
+ "stat",
392
+ "chmod",
393
+ "chown",
394
+ "chgrp",
395
+ "mount",
396
+ "umount",
397
+ "uname",
398
+ "ps",
399
+ "ip",
400
+ "lsmod",
401
+ "modprobe",
402
+ "sha256sum",
403
+ "usermod",
404
+ "crontab",
405
+ ]);
@@ -0,0 +1,177 @@
1
+ /**
2
+ * DistroAdapter — unified cross-distribution API for the Kali Defense MCP Server.
3
+ *
4
+ * This module provides a single, cached adapter instance that abstracts away
5
+ * distribution-specific differences in:
6
+ * - Package management (apt / dnf / yum / zypper / pacman / apk)
7
+ * - Service management (systemd / openrc / sysvinit / launchd)
8
+ * - Firewall backends (iptables / nftables / ufw / firewalld)
9
+ * - File system paths (logs, PAM configs, syslog, package tools)
10
+ * - Package integrity checking (debsums / rpm -V)
11
+ * - Automatic updates configuration
12
+ *
13
+ * Supported distributions:
14
+ * Debian, Ubuntu, Kali, Linux Mint, Pop!_OS → debian family
15
+ * RHEL, CentOS, Fedora, Rocky, AlmaLinux → rhel family
16
+ * openSUSE, SLES → suse family
17
+ * Arch, Manjaro → arch family
18
+ * Alpine → alpine family
19
+ *
20
+ * Usage:
21
+ * import { getDistroAdapter } from "../core/distro-adapter.js";
22
+ * const da = await getDistroAdapter();
23
+ * const cmd = da.pkg.installCmd("nginx"); // distro-correct install
24
+ * const logPath = da.paths.syslog; // "/var/log/syslog" or "/var/log/messages"
25
+ */
26
+ import { type DistroInfo, type PackageManagerCommands, type ServiceManagerCommands, type FirewallBackendCommands } from "./distro.js";
27
+ /** System paths that vary across distributions. */
28
+ export interface DistroPaths {
29
+ /** Primary syslog file */
30
+ syslog: string;
31
+ /** Authentication log */
32
+ authLog: string;
33
+ /** PAM common-auth or system-auth equivalent */
34
+ pamAuth: string;
35
+ /** PAM common-password or password-auth equivalent */
36
+ pamPassword: string;
37
+ /** PAM common-session equivalent */
38
+ pamSession: string;
39
+ /** PAM common-account equivalent */
40
+ pamAccount: string;
41
+ /** All PAM config files to audit */
42
+ pamAllConfigs: string[];
43
+ /** Auto-update config dir (apt.conf.d, dnf automatic, etc.) */
44
+ autoUpdateConfig: string;
45
+ /** Auto-update package name */
46
+ autoUpdatePackage: string;
47
+ /** Auto-update service name */
48
+ autoUpdateService: string;
49
+ /** Firewall persistence config path */
50
+ firewallPersistenceConfig: string;
51
+ /** Package manager lock file */
52
+ packageLockFile: string;
53
+ /** Network interface config dir */
54
+ networkConfigDir: string;
55
+ /** Kernel modules blacklist config */
56
+ modprobeDir: string;
57
+ /** GRUB config file */
58
+ grubConfig: string;
59
+ /** GRUB defaults file */
60
+ grubDefaults: string;
61
+ /** GRUB update command */
62
+ grubUpdateCmd: string[];
63
+ }
64
+ /** Package integrity check configuration. */
65
+ export interface IntegrityCheckConfig {
66
+ /** Whether integrity checking is supported */
67
+ supported: boolean;
68
+ /** The command to check package integrity */
69
+ checkCmd: string[];
70
+ /** The command to check a specific package */
71
+ checkPackageCmd: (pkg: string) => string[];
72
+ /** Name of the integrity tool */
73
+ toolName: string;
74
+ /** How to install the integrity tool */
75
+ installHint: string;
76
+ }
77
+ /** Auto-update audit configuration. */
78
+ export interface AutoUpdateConfig {
79
+ /** Whether auto-updates are supported on this distro */
80
+ supported: boolean;
81
+ /** Package name for auto-updates */
82
+ packageName: string;
83
+ /** How to check if auto-update is installed */
84
+ checkInstalledCmd: string[];
85
+ /** Service name to check */
86
+ serviceName: string;
87
+ /** Config files to audit */
88
+ configFiles: string[];
89
+ /** How to install auto-updates */
90
+ installHint: string;
91
+ }
92
+ /** Package listing/querying commands. */
93
+ export interface PackageQueryCommands {
94
+ /** List all installed packages */
95
+ listInstalledCmd: string[];
96
+ /** Query a specific package (returns version info) */
97
+ queryPackageCmd: (pkg: string) => string[];
98
+ /** List available upgrades */
99
+ listUpgradableCmd: string[];
100
+ /** Show held/locked packages */
101
+ showHeldCmd: string[];
102
+ /** Simulate upgrade (dry-run) */
103
+ simulateUpgradeCmd: string[];
104
+ /** Show package changelog */
105
+ changelogCmd: (pkg: string) => string[];
106
+ /** Show package policy/info */
107
+ policyCmd: (pkg: string) => string[];
108
+ /** Check if a specific package is installed */
109
+ isInstalledCmd: (pkg: string) => string[];
110
+ /** List installed kernel packages */
111
+ listKernelsCmd: string[];
112
+ /** Check for auto-removable packages */
113
+ autoRemoveCmd: string[];
114
+ }
115
+ /** Firewall persistence commands. */
116
+ export interface FirewallPersistenceConfig {
117
+ /** Package name for firewall persistence */
118
+ packageName: string;
119
+ /** How to check if persistence is installed */
120
+ checkInstalledCmd: string[];
121
+ /** Install command (already includes sudo) */
122
+ installCmd: string[];
123
+ /** Service name for persistence */
124
+ serviceName: string;
125
+ /** Enable persistence service */
126
+ enableCmd: string[];
127
+ /** Save rules command */
128
+ saveCmd: string[];
129
+ /** Rollback/uninstall hint */
130
+ uninstallHint: string;
131
+ }
132
+ export declare class DistroAdapter {
133
+ readonly distro: DistroInfo;
134
+ readonly pkg: PackageManagerCommands;
135
+ readonly svc: ServiceManagerCommands;
136
+ readonly fw: FirewallBackendCommands;
137
+ readonly paths: DistroPaths;
138
+ readonly integrity: IntegrityCheckConfig;
139
+ readonly autoUpdate: AutoUpdateConfig;
140
+ readonly pkgQuery: PackageQueryCommands;
141
+ readonly fwPersistence: FirewallPersistenceConfig;
142
+ constructor(distro: DistroInfo, pkg: PackageManagerCommands, svc: ServiceManagerCommands, fw: FirewallBackendCommands);
143
+ /** Human-readable summary of the detected environment. */
144
+ get summary(): string;
145
+ /** Whether the distro family is Debian-based. */
146
+ get isDebian(): boolean;
147
+ /** Whether the distro family is RHEL-based. */
148
+ get isRhel(): boolean;
149
+ /** Whether the distro family is SUSE-based. */
150
+ get isSuse(): boolean;
151
+ /** Whether the distro family is Arch-based. */
152
+ get isArch(): boolean;
153
+ /** Whether the distro family is Alpine. */
154
+ get isAlpine(): boolean;
155
+ /** Install a package using the distro's package manager (returns command array). */
156
+ installPkg(pkg: string): {
157
+ command: string;
158
+ args: string[];
159
+ };
160
+ /** Remove a package using the distro's package manager (returns command array). */
161
+ removePkg(pkg: string): {
162
+ command: string;
163
+ args: string[];
164
+ };
165
+ }
166
+ /**
167
+ * Returns the singleton DistroAdapter.
168
+ * On first call it detects the distribution and builds all adapters.
169
+ * Subsequent calls return the cached instance.
170
+ */
171
+ export declare function getDistroAdapter(): Promise<DistroAdapter>;
172
+ /**
173
+ * Returns the cached adapter if already initialized, or null.
174
+ * Use when you can't await (synchronous contexts).
175
+ */
176
+ export declare function getDistroAdapterSync(): DistroAdapter | null;
177
+ //# sourceMappingURL=distro-adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"distro-adapter.d.ts","sourceRoot":"","sources":["../../src/core/distro-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAKL,KAAK,UAAU,EAGf,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAE7B,MAAM,aAAa,CAAC;AAIrB,mDAAmD;AACnD,MAAM,WAAW,WAAW;IAC1B,0BAA0B;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,yBAAyB;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,OAAO,EAAE,MAAM,CAAC;IAChB,sDAAsD;IACtD,WAAW,EAAE,MAAM,CAAC;IACpB,oCAAoC;IACpC,UAAU,EAAE,MAAM,CAAC;IACnB,oCAAoC;IACpC,UAAU,EAAE,MAAM,CAAC;IACnB,oCAAoC;IACpC,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,+DAA+D;IAC/D,gBAAgB,EAAE,MAAM,CAAC;IACzB,+BAA+B;IAC/B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,+BAA+B;IAC/B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uCAAuC;IACvC,yBAAyB,EAAE,MAAM,CAAC;IAClC,gCAAgC;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,mCAAmC;IACnC,gBAAgB,EAAE,MAAM,CAAC;IACzB,sCAAsC;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,uBAAuB;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,yBAAyB;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,0BAA0B;IAC1B,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB;AAED,6CAA6C;AAC7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