File size: 9,007 Bytes
b4143a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDrivesWin = getDrivesWin;
exports.listDirectory = listDirectory;
exports.computeFolderSize = computeFolderSize;
exports.findLargeFiles = findLargeFiles;
exports.getProcessesWin = getProcessesWin;
exports.getServicesWin = getServicesWin;
exports.getInstalledPrograms = getInstalledPrograms;
exports.getSystemSnapshot = getSystemSnapshot;
exports.getNetworkInterfaces = getNetworkInterfaces;
exports.getEnvSnapshot = getEnvSnapshot;
exports.getStartupFolders = getStartupFolders;
exports.getTempAudit = getTempAudit;
exports.getScheduledTasksSummary = getScheduledTasksSummary;
exports.openPathInExplorer = openPathInExplorer;
exports.killProcess = killProcess;
exports.getWindowsFeaturesSnippet = getWindowsFeaturesSnippet;
/**
 * Audit logic: hot paths (filesystem, processes, drives, system, network, env) → Python FastAPI.
 * Windows-specific shell/registry work stays in Node.
 */
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
const node_child_process_1 = require("node:child_process");
const node_util_1 = require("node:util");
const pythonBackend_1 = require("./pythonBackend");
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
function resolveSafePath(input) {
    const normalized = path.normalize(input);
    return path.resolve(normalized);
}
async function getDrivesWin() {
    return (0, pythonBackend_1.pyGet)('/api/drives');
}
async function listDirectory(dirPath, options = {}) {
    const root = resolveSafePath(dirPath);
    return (0, pythonBackend_1.pyPost)('/api/list_dir', {
        path: root,
        max_entries: options.maxEntries ?? 800,
    });
}
async function computeFolderSize(dirPath) {
    return (0, pythonBackend_1.pyPost)('/api/folder_size', {
        path: resolveSafePath(dirPath),
    });
}
async function findLargeFiles(rootPath, minBytes, maxResults) {
    return (0, pythonBackend_1.pyPost)('/api/large_files', {
        path: resolveSafePath(rootPath),
        min_bytes: minBytes,
        max_results: maxResults,
    });
}
async function getProcessesWin() {
    return (0, pythonBackend_1.pyGet)('/api/processes');
}
async function getServicesWin() {
    const script = `

    Get-CimInstance Win32_Service | Select-Object Name,DisplayName,State,StartMode | ConvertTo-Json -Compress

  `;
    try {
        const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, maxBuffer: 20 * 1024 * 1024, timeout: 120_000 });
        const raw = JSON.parse(stdout.trim() || '[]');
        const arr = Array.isArray(raw) ? raw : [raw];
        return arr.map((s) => ({
            name: String(s.Name ?? ''),
            displayName: String(s.DisplayName ?? ''),
            state: String(s.State ?? ''),
            startType: String(s.StartMode ?? ''),
        }));
    }
    catch {
        return [];
    }
}
function getInstalledPrograms() {
    const script = `

    $paths = @(

      'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*',

      'HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*',

      'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'

    )

    Get-ItemProperty $paths -ErrorAction SilentlyContinue |

      Where-Object { $_.DisplayName } |

      Select-Object DisplayName, DisplayVersion, Publisher, InstallLocation, UninstallString, EstimatedSize |

      ConvertTo-Json -Compress -Depth 4

  `;
    try {
        const stdout = (0, node_child_process_1.execFileSync)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true, maxBuffer: 50 * 1024 * 1024 });
        const raw = JSON.parse(stdout.trim() || '[]');
        const arr = Array.isArray(raw) ? raw : [raw];
        const apps = arr.map((r) => ({
            name: String(r.DisplayName ?? ''),
            version: String(r.DisplayVersion ?? ''),
            publisher: String(r.Publisher ?? ''),
            installLocation: String(r.InstallLocation ?? ''),
            uninstallString: String(r.UninstallString ?? ''),
            estimatedSizeKb: Number(r.EstimatedSize) || 0,
        }));
        const seen = new Set();
        return apps
            .filter((a) => {
            const k = a.name.toLowerCase();
            if (!k || seen.has(k))
                return false;
            seen.add(k);
            return true;
        })
            .sort((a, b) => a.name.localeCompare(b.name));
    }
    catch {
        return [];
    }
}
async function getSystemSnapshot() {
    return (0, pythonBackend_1.pyGet)('/api/system');
}
async function getNetworkInterfaces() {
    return (0, pythonBackend_1.pyGet)('/api/network');
}
async function getEnvSnapshot(keys) {
    const all = await (0, pythonBackend_1.pyGet)('/api/env');
    if (!keys?.length)
        return all;
    const out = {};
    for (const k of keys) {
        const v = all[k];
        if (v !== undefined)
            out[k] = v;
    }
    return out;
}
async function getStartupFolders() {
    const appData = process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming');
    const programData = process.env.PROGRAMDATA ?? 'C:\\ProgramData';
    const folders = [
        path.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup'),
        path.join(programData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'StartUp'),
    ];
    const result = [];
    for (const f of folders) {
        const entries = await listDirectory(f, { maxEntries: 200 });
        result.push({ path: f, entries });
    }
    return result;
}
async function getTempAudit() {
    const dirs = [os.tmpdir(), path.join(os.tmpdir(), '..', 'Temp')].map((p) => path.normalize(p));
    const uniq = [...new Set(dirs)];
    const out = [];
    for (const d of uniq) {
        try {
            const r = await computeFolderSize(d);
            out.push({ path: d, ...r });
        }
        catch {
            out.push({ path: d, bytes: 0, files: 0, truncated: false });
        }
    }
    return out;
}
async function getScheduledTasksSummary() {
    const script = `

    Get-ScheduledTask | Select-Object TaskName,State | ConvertTo-Json -Compress

  `;
    try {
        const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, maxBuffer: 20 * 1024 * 1024, timeout: 120_000 });
        const raw = JSON.parse(stdout.trim() || '[]');
        const arr = Array.isArray(raw) ? raw : [raw];
        return arr.map((t) => ({
            name: String(t.TaskName ?? ''),
            state: String(t.State ?? ''),
        }));
    }
    catch {
        return [];
    }
}
async function openPathInExplorer(p) {
    const resolved = resolveSafePath(p);
    await execFileAsync('explorer.exe', [resolved], { windowsHide: true });
}
function killProcess(pid) {
    return new Promise((resolve, reject) => {
        const proc = (0, node_child_process_1.spawn)('taskkill', ['/PID', String(pid), '/F'], { windowsHide: true });
        proc.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`taskkill exit ${code}`))));
        proc.on('error', reject);
    });
}
async function getWindowsFeaturesSnippet() {
    try {
        const { stdout } = await execFileAsync('dism.exe', ['/Online', '/Get-Features', '/Format:Table'], { windowsHide: true, maxBuffer: 5 * 1024 * 1024, timeout: 60_000 });
        return stdout.slice(0, 120_000);
    }
    catch (e) {
        return String(e.message);
    }
}