Files
vpn-proxy/src/server/windowsHelper.js

55 lines
1.6 KiB
JavaScript

import { spawn } from "node:child_process";
import { settings } from "./config.js";
function defaultRunner(command, args, options = {}) {
return new Promise((resolve) => {
const child = spawn(command, args, {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk) => {
stderr += chunk.toString("utf8");
});
child.on("error", (error) => {
resolve({ status: 1, stdout, stderr: error.message });
});
child.on("close", (status) => {
resolve({ status, stdout, stderr });
});
child.stdin.end(options.input || "");
});
}
export function createWindowsHelper(options = {}) {
const helperPath = options.helperPath || settings.windowsHelperPath;
const command = options.command || "pwsh";
const runner = options.runner || defaultRunner;
return {
async run(action, payload = {}) {
const input = JSON.stringify({ action, payload });
const result = await runner(
command,
["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", helperPath],
{ input },
);
if (result.status !== 0) {
throw new Error(
`Windows helper failed: ${(result.stderr || result.stdout || "helper exited without stderr").trim()}`,
);
}
try {
return JSON.parse(result.stdout);
} catch {
throw new Error(`Windows helper returned invalid JSON: ${result.stdout}`);
}
},
};
}
export const windowsHelper = createWindowsHelper();