Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

dedupe

x0615d66a1592
diff --git a/backend/src/lib/gateway-v2/adcs-rpc.ts b/backend/src/lib/gateway-v2/adcs-rpc.ts
index 4b6c8200c4..cbd5973e30 100644
--- a/backend/src/lib/gateway-v2/adcs-rpc.ts
+++ b/backend/src/lib/gateway-v2/adcs-rpc.ts
@@ -1,6 +1,4 @@
-import http from "node:http";
-
-import { logger } from "@app/lib/logger";
+import { postGatewayRpc } from "./gateway-rpc";
export type AdcsRpcEndpoint = "/v1/test" | "/v1/discover-ca" | "/v1/templates" | "/v1/enroll" | "/v1/revoke";
@@ -91,64 +89,30 @@ export const callAdcsEndpoint = async <T>(args: {
endpoint: AdcsRpcEndpoint;
body: AdcsRpcRequestBody;
}): Promise<AdcsRpcResponse<T>> => {
- const payload = JSON.stringify(args.body);
- return new Promise<AdcsRpcResponse<T>>((resolve, reject) => {
- const req = http.request(
- {
- host: "127.0.0.1",
- port: args.port,
- path: args.endpoint,
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Content-Length": Buffer.byteLength(payload).toString(),
- Connection: "close"
- },
- timeout: ADCS_RPC_TIMEOUT_MS
- },
- (res) => {
- const chunks: Buffer[] = [];
- res.on("data", (chunk: Buffer) => chunks.push(chunk));
- res.on("end", () => {
- const text = Buffer.concat(chunks).toString("utf8");
- const status = res.statusCode ?? 0;
- if (!text) {
- resolve({ ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` });
- return;
- }
- let parsed: unknown;
- try {
- parsed = JSON.parse(text);
- } catch {
- resolve({ ok: false, status, errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}` });
- return;
- }
- if (status >= 200 && status < 300) {
- const { result } = parsed as { result?: T };
- if (result === undefined) {
- resolve({ ok: false, status, errorMessage: "Gateway response missing `result` field" });
- return;
- }
- resolve({ ok: true, status, result });
- return;
- }
- const errEnv = (parsed as { error?: { message?: string } }).error;
- resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });
- });
- res.on("error", (err) => {
- logger.warn({ err }, `ADCS RPC response stream error [port=${args.port}]`);
- reject(err);
- });
- }
- );
- req.on("timeout", () => {
- req.destroy(new Error(`ADCS RPC timed out after ${ADCS_RPC_TIMEOUT_MS}ms`));
- });
- req.on("error", (err) => {
- logger.warn({ err }, `ADCS RPC request error [port=${args.port}]`);
- reject(err);
- });
- req.write(payload);
- req.end();
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: args.endpoint,
+ payload: JSON.stringify(args.body),
+ timeoutMs: ADCS_RPC_TIMEOUT_MS,
+ label: "ADCS"
});
+
+ if (!text) {
+ return { ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` };
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return { ok: false, status, errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}` };
+ }
+ if (status >= 200 && status < 300) {
+ const { result } = parsed as { result?: T };
+ if (result === undefined) {
+ return { ok: false, status, errorMessage: "Gateway response missing `result` field" };
+ }
+ return { ok: true, status, result };
+ }
+ const errEnv = (parsed as { error?: { message?: string } }).error;
+ return { ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` };
};
diff --git a/backend/src/lib/gateway-v2/gateway-rpc.ts b/backend/src/lib/gateway-v2/gateway-rpc.ts
new file mode 100644
index 0000000000..1c20f1b9a6
--- /dev/null
+++ b/backend/src/lib/gateway-v2/gateway-rpc.ts
@@ -0,0 +1,80 @@
+import http from "node:http";
+
+import { logger } from "@app/lib/logger";
+
+export type GatewayRpcRawResponse = { status: number; text: string };
+
+// shared transport for the gateway RPCs sent over the local relay proxy
+export const postGatewayRpc = (args: {
+ port: number;
+ path: string;
+ payload: string;
+ timeoutMs: number;
+ deadlineMs?: number;
+ maxResponseBytes?: number;
+ signal?: AbortSignal;
+ label: string;
+}): Promise<GatewayRpcRawResponse> => {
+ const { port, path, payload, timeoutMs, deadlineMs, maxResponseBytes, signal, label } = args;
+ return new Promise<GatewayRpcRawResponse>((resolve, reject) => {
+ let settled = false;
+ let deadlineTimer: NodeJS.Timeout | undefined;
+ const finish = (run: () => void) => {
+ if (settled) return;
+ settled = true;
+ if (deadlineTimer) clearTimeout(deadlineTimer);
+ run();
+ };
+
+ const req = http.request(
+ {
+ host: "127.0.0.1",
+ port,
+ path,
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Content-Length": Buffer.byteLength(payload).toString(),
+ Connection: "close"
+ },
+ timeout: timeoutMs,
+ signal
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ let received = 0;
+ res.on("data", (chunk: Buffer) => {
+ received += chunk.length;
+ if (maxResponseBytes !== undefined && received > maxResponseBytes) {
+ req.destroy();
+ finish(() => reject(new Error(`${label} RPC response exceeded ${maxResponseBytes} bytes`)));
+ return;
+ }
+ chunks.push(chunk);
+ });
+ res.on("end", () =>
+ finish(() => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString("utf8") }))
+ );
+ res.on("error", (err) => {
+ logger.warn({ err }, `${label} RPC response stream error [port=${port}]`);
+ finish(() => reject(err));
+ });
+ }
+ );
+
+ if (deadlineMs !== undefined) {
+ deadlineTimer = setTimeout(() => {
+ req.destroy(new Error(`${label} RPC exceeded the ${deadlineMs}ms deadline`));
+ }, deadlineMs);
+ }
+ req.on("timeout", () => {
+ req.destroy(new Error(`${label} RPC timed out after ${timeoutMs}ms`));
+ });
+ req.on("error", (err) => {
+ logger.warn({ err }, `${label} RPC request error [port=${port}]`);
+ finish(() => reject(err));
+ });
+ req.write(payload);
+ req.end();
+ });
+};
diff --git a/backend/src/lib/gateway-v2/pkcs11-rpc.ts b/backend/src/lib/gateway-v2/pkcs11-rpc.ts
index 998d794eb8..c60ad5f22e 100644
--- a/backend/src/lib/gateway-v2/pkcs11-rpc.ts
+++ b/backend/src/lib/gateway-v2/pkcs11-rpc.ts
@@ -1,6 +1,4 @@
-import http from "node:http";
-
-import { logger } from "@app/lib/logger";
+import { postGatewayRpc } from "./gateway-rpc";
export type Pkcs11RpcEndpoint = "/v1/test" | "/v1/generate-key-pair" | "/v1/sign" | "/v1/get-public-key";
@@ -27,86 +25,47 @@ export const callPkcs11Endpoint = async <T>(args: {
body: Pkcs11RpcRequestBody;
timeoutMs?: number;
}): Promise<Pkcs11RpcResponse<T>> => {
- const payload = JSON.stringify(args.body);
- return new Promise<Pkcs11RpcResponse<T>>((resolve, reject) => {
- const req = http.request(
- {
- host: "127.0.0.1",
- port: args.port,
- path: args.endpoint,
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Content-Length": Buffer.byteLength(payload).toString(),
- Connection: "close"
- },
- timeout: args.timeoutMs ?? PKCS11_RPC_TIMEOUT_MS
- },
- (res) => {
- const chunks: Buffer[] = [];
- res.on("data", (chunk: Buffer) => chunks.push(chunk));
- res.on("end", () => {
- const text = Buffer.concat(chunks).toString("utf8");
- const status = res.statusCode ?? 0;
- if (!text) {
- resolve({
- ok: false,
- status,
- errorCode: "internal",
- errorMessage: `Empty response body from Gateway (status ${status})`
- });
- return;
- }
- let parsed: unknown;
- try {
- parsed = JSON.parse(text);
- } catch {
- resolve({
- ok: false,
- status,
- errorCode: "internal",
- errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}`
- });
- return;
- }
- if (status >= 200 && status < 300) {
- const { result } = parsed as { result?: T };
- if (result === undefined) {
- resolve({
- ok: false,
- status,
- errorCode: "internal",
- errorMessage: "Gateway response missing `result` field"
- });
- return;
- }
- resolve({ ok: true, status, result });
- return;
- }
- const errEnv = (parsed as { error?: { code?: string; message?: string } }).error;
- resolve({
- ok: false,
- status,
- errorCode: errEnv?.code ?? "internal",
- errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}`
- });
- });
- res.on("error", (err) => {
- logger.warn({ err }, `PKCS#11 RPC response stream error [port=${args.port}]`);
- reject(err);
- });
- }
- );
- req.on("timeout", () => {
- req.destroy(new Error(`PKCS#11 RPC timed out after ${args.timeoutMs ?? PKCS11_RPC_TIMEOUT_MS}ms`));
- });
- req.on("error", (err) => {
- logger.warn({ err }, `PKCS#11 RPC request error [port=${args.port}]`);
- reject(err);
- });
- req.write(payload);
- req.end();
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: args.endpoint,
+ payload: JSON.stringify(args.body),
+ timeoutMs: args.timeoutMs ?? PKCS11_RPC_TIMEOUT_MS,
+ label: "PKCS#11"
});
+
+ if (!text) {
+ return {
+ ok: false,
+ status,
+ errorCode: "internal",
+ errorMessage: `Empty response body from Gateway (status ${status})`
+ };
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return {
+ ok: false,
+ status,
+ errorCode: "internal",
+ errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}`
+ };
+ }
+ if (status >= 200 && status < 300) {
+ const { result } = parsed as { result?: T };
+ if (result === undefined) {
+ return { ok: false, status, errorCode: "internal", errorMessage: "Gateway response missing `result` field" };
+ }
+ return { ok: true, status, result };
+ }
+ const errEnv = (parsed as { error?: { code?: string; message?: string } }).error;
+ return {
+ ok: false,
+ status,
+ errorCode: errEnv?.code ?? "internal",
+ errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}`
+ };
};
export const isRetryablePkcs11RpcError = (failure: Pkcs11RpcFailure): boolean => {
diff --git a/backend/src/lib/gateway-v2/ssh-rpc.ts b/backend/src/lib/gateway-v2/ssh-rpc.ts
index 04ed7b6155..c91c8cd7b9 100644
--- a/backend/src/lib/gateway-v2/ssh-rpc.ts
+++ b/backend/src/lib/gateway-v2/ssh-rpc.ts
@@ -1,6 +1,4 @@
-import http from "node:http";
-
-import { logger } from "@app/lib/logger";
+import { postGatewayRpc } from "./gateway-rpc";
export type SshExecCredentials = {
authMethod: string;
@@ -22,149 +20,72 @@ const MAX_RPC_RESPONSE_BYTES = 16 * 1024 * 1024;
// calls the gateway's ssh-exec handler over the local relay proxy; the gateway performs the ssh login (any auth
// method, including certificates the node client can't present) and returns the command output
-export const callSshExec = (args: {
+export const callSshExec = async (args: {
port: number;
command: string;
credentials: SshExecCredentials;
timeoutMs: number;
signal?: AbortSignal;
}): Promise<SshExecResponse> => {
- const payload = JSON.stringify({ command: args.command, ...args.credentials, timeoutMs: args.timeoutMs });
- return new Promise<SshExecResponse>((resolve, reject) => {
- const req = http.request(
- {
- host: "127.0.0.1",
- port: args.port,
- path: "/v1/exec",
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Content-Length": Buffer.byteLength(payload).toString(),
- Connection: "close"
- },
- timeout: SSH_EXEC_RPC_TIMEOUT_MS,
- signal: args.signal
- },
- (res) => {
- const chunks: Buffer[] = [];
- let received = 0;
- res.on("data", (chunk: Buffer) => {
- received += chunk.length;
- if (received > MAX_RPC_RESPONSE_BYTES) {
- res.destroy(new Error(`SSH exec response exceeded ${MAX_RPC_RESPONSE_BYTES} bytes`));
- return;
- }
- chunks.push(chunk);
- });
- res.on("end", () => {
- const text = Buffer.concat(chunks).toString("utf8");
- const status = res.statusCode ?? 0;
- if (!text) {
- resolve({ ok: false, status, errorMessage: `Empty response from gateway (status ${status})` });
- return;
- }
- let parsed: unknown;
- try {
- parsed = JSON.parse(text);
- } catch {
- resolve({ ok: false, status, errorMessage: `Malformed response from gateway: ${text.slice(0, 256)}` });
- return;
- }
- if (status >= 200 && status < 300) {
- const { result } = parsed as { result?: SshExecResult };
- if (!result) {
- resolve({ ok: false, status, errorMessage: "Gateway response missing `result` field" });
- return;
- }
- resolve({ ok: true, status, result });
- return;
- }
- const errEnv = (parsed as { error?: { message?: string } }).error;
- resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });
- });
- res.on("error", (err) => {
- logger.warn({ err }, `SSH exec RPC response stream error [port=${args.port}]`);
- reject(err);
- });
- }
- );
- req.on("timeout", () => {
- req.destroy(new Error(`SSH exec RPC timed out after ${SSH_EXEC_RPC_TIMEOUT_MS}ms`));
- });
- req.on("error", (err) => {
- logger.warn({ err }, `SSH exec RPC request error [port=${args.port}]`);
- reject(err);
- });
- req.write(payload);
- req.end();
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: "/v1/exec",
+ payload: JSON.stringify({ command: args.command, ...args.credentials, timeoutMs: args.timeoutMs }),
+ timeoutMs: SSH_EXEC_RPC_TIMEOUT_MS,
+ maxResponseBytes: MAX_RPC_RESPONSE_BYTES,
+ signal: args.signal,
+ label: "SSH exec"
});
+
+ if (!text) return { ok: false, status, errorMessage: `Empty response from gateway (status ${status})` };
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return { ok: false, status, errorMessage: `Malformed response from gateway: ${text.slice(0, 256)}` };
+ }
+ if (status >= 200 && status < 300) {
+ const { result } = parsed as { result?: SshExecResult };
+ if (!result) return { ok: false, status, errorMessage: "Gateway response missing `result` field" };
+ return { ok: true, status, result };
+ }
+ const errEnv = (parsed as { error?: { message?: string } }).error;
+ return { ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` };
};
// calls the gateway's port-sweep handler over the local relay proxy; the gateway TCP-probes every target
// in-network and returns the reachable "host:port" set, so a scan can filter a whole CIDR to live hosts
-export const callPortSweep = (args: {
+export const callPortSweep = async (args: {
port: number;
targets: string[];
dialTimeoutMs: number;
responseTimeoutMs: number;
signal?: AbortSignal;
}): Promise<Set<string>> => {
- const payload = JSON.stringify({ targets: args.targets, timeoutMs: args.dialTimeoutMs });
- return new Promise<Set<string>>((resolve, reject) => {
- const req = http.request(
- {
- host: "127.0.0.1",
- port: args.port,
- path: "/v1/sweep",
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Content-Length": Buffer.byteLength(payload).toString(),
- Connection: "close"
- },
- timeout: args.responseTimeoutMs,
- signal: args.signal
- },
- (res) => {
- const chunks: Buffer[] = [];
- let received = 0;
- res.on("data", (chunk: Buffer) => {
- received += chunk.length;
- if (received > MAX_RPC_RESPONSE_BYTES) {
- res.destroy(new Error(`Port sweep response exceeded ${MAX_RPC_RESPONSE_BYTES} bytes`));
- return;
- }
- chunks.push(chunk);
- });
- res.on("end", () => {
- const status = res.statusCode ?? 0;
- const text = Buffer.concat(chunks).toString("utf8");
- if (status < 200 || status >= 300) {
- const errEnv = (() => {
- try {
- return (JSON.parse(text) as { error?: { message?: string } }).error;
- } catch {
- return undefined;
- }
- })();
- reject(new Error(errEnv?.message ?? `Port sweep returned HTTP ${status}`));
- return;
- }
- try {
- const parsed = JSON.parse(text) as { open?: string[] };
- resolve(new Set(parsed.open ?? []));
- } catch {
- reject(new Error("Invalid port sweep response"));
- }
- });
- res.on("error", reject);
- }
- );
- req.on("timeout", () => {
- req.destroy(new Error(`Port sweep timed out after ${args.responseTimeoutMs}ms`));
- });
- req.on("error", reject);
- req.write(payload);
- req.end();
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: "/v1/sweep",
+ payload: JSON.stringify({ targets: args.targets, timeoutMs: args.dialTimeoutMs }),
+ timeoutMs: args.responseTimeoutMs,
+ maxResponseBytes: MAX_RPC_RESPONSE_BYTES,
+ signal: args.signal,
+ label: "Port sweep"
});
+
+ if (status < 200 || status >= 300) {
+ const errEnv = (() => {
+ try {
+ return (JSON.parse(text) as { error?: { message?: string } }).error;
+ } catch {
+ return undefined;
+ }
+ })();
+ throw new Error(errEnv?.message ?? `Port sweep returned HTTP ${status}`);
+ }
+ try {
+ const parsed = JSON.parse(text) as { open?: string[] };
+ return new Set(parsed.open ?? []);
+ } catch {
+ throw new Error("Invalid port sweep response");
+ }
};
diff --git a/backend/src/lib/gateway-v2/test-connection-rpc.ts b/backend/src/lib/gateway-v2/test-connection-rpc.ts
index 585ffe406e..943538ef84 100644
--- a/backend/src/lib/gateway-v2/test-connection-rpc.ts
+++ b/backend/src/lib/gateway-v2/test-connection-rpc.ts
@@ -1,6 +1,4 @@
-import http from "node:http";
-
-import { logger } from "@app/lib/logger";
+import { postGatewayRpc } from "./gateway-rpc";
export type TestConnectionResponse = { ok: true; status: number } | { ok: false; status: number; errorMessage: string };
@@ -8,70 +6,31 @@ export const TEST_CONNECTION_RPC_TIMEOUT_MS = 60_000;
const MAX_RPC_RESPONSE_BYTES = 1024 * 1024;
-// calls the gateway's /v1/test-connection handler over the local relay proxy with an opaque request body
-export const callTestConnection = (args: {
+// calls the gateway's /v1/test-connection handler with an opaque request body
+export const callTestConnection = async (args: {
port: number;
body: Record<string, unknown>;
timeoutMs: number;
signal?: AbortSignal;
}): Promise<TestConnectionResponse> => {
- const payload = JSON.stringify({ ...args.body, timeoutMs: args.timeoutMs });
- return new Promise<TestConnectionResponse>((resolve, reject) => {
- const req = http.request(
- {
- host: "127.0.0.1",
- port: args.port,
- path: "/v1/test-connection",
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Content-Length": Buffer.byteLength(payload).toString(),
- Connection: "close"
- },
- timeout: TEST_CONNECTION_RPC_TIMEOUT_MS,
- signal: args.signal
- },
- (res) => {
- const chunks: Buffer[] = [];
- let received = 0;
- res.on("data", (chunk: Buffer) => {
- received += chunk.length;
- if (received > MAX_RPC_RESPONSE_BYTES) {
- res.destroy(new Error(`Test connection response exceeded ${MAX_RPC_RESPONSE_BYTES} bytes`));
- return;
- }
- chunks.push(chunk);
- });
- res.on("end", () => {
- const text = Buffer.concat(chunks).toString("utf8");
- const status = res.statusCode ?? 0;
- const errEnv = (() => {
- try {
- return (JSON.parse(text) as { error?: { message?: string } }).error;
- } catch {
- return undefined;
- }
- })();
- if (status >= 200 && status < 300) {
- resolve({ ok: true, status });
- return;
- }
- resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });
- });
- res.on("error", (err) => {
- logger.warn({ err }, `Test connection RPC response stream error [port=${args.port}]`);
- reject(err);
- });
- }
- );
- req.on("timeout", () => {
- req.destroy(new Error(`Test connection RPC timed out after ${TEST_CONNECTION_RPC_TIMEOUT_MS}ms`));
- });
- req.on("error", (err) => {
- logger.warn({ err }, `Test connection RPC request error [port=${args.port}]`);
- reject(err);
- });
- req.write(payload);
- req.end();
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: "/v1/test-connection",
+ payload: JSON.stringify({ ...args.body, timeoutMs: args.timeoutMs }),
+ timeoutMs: TEST_CONNECTION_RPC_TIMEOUT_MS,
+ maxResponseBytes: MAX_RPC_RESPONSE_BYTES,
+ signal: args.signal,
+ label: "Test connection"
});
+
+ if (status >= 200 && status < 300) return { ok: true, status };
+
+ const errEnv = (() => {
+ try {
+ return (JSON.parse(text) as { error?: { message?: string } }).error;
+ } catch {
+ return undefined;
+ }
+ })();
+ return { ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` };
};
diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.ts
index f1d73df130..abb91ede5f 100644
--- a/backend/src/lib/gateway-v2/winrm-rpc.ts
+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts
@@ -1,6 +1,4 @@
-import http from "node:http";
-
-import { logger } from "@app/lib/logger";
+import { postGatewayRpc } from "./gateway-rpc";
export enum WinRmRpcEndpoint {
Test = "/v1/test-connection",
@@ -46,103 +44,32 @@ export const callWinRmEndpoint = async <T>(args: {
endpoint: WinRmRpcEndpoint;
body: WinRmRpcRequestBody;
}): Promise<WinRmRpcResponse<T>> => {
- const payload = JSON.stringify(args.body);
- return new Promise<WinRmRpcResponse<T>>((resolve, reject) => {
- let settled = false;
- let deadlineTimer: NodeJS.Timeout;
- const finish = (run: () => void) => {
- if (settled) return;
- settled = true;
- clearTimeout(deadlineTimer);
- run();
- };
-
- const req = http.request(
- {
- host: "127.0.0.1",
- port: args.port,
- path: args.endpoint,
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Content-Length": Buffer.byteLength(payload).toString(),
- Connection: "close"
- },
- timeout: WINRM_RPC_TIMEOUT_MS
- },
- (res) => {
- const chunks: Buffer[] = [];
- let received = 0;
- res.on("data", (chunk: Buffer) => {
- received += chunk.length;
- if (received > MAX_WINRM_RPC_RESPONSE_BYTES) {
- req.destroy();
- finish(() =>
- resolve({
- ok: false,
- status: res.statusCode ?? 0,
- errorMessage: `Gateway response exceeded ${MAX_WINRM_RPC_RESPONSE_BYTES} bytes`
- })
- );
- return;
- }
- chunks.push(chunk);
- });
- res.on("end", () => {
- const text = Buffer.concat(chunks).toString("utf8");
- const status = res.statusCode ?? 0;
- if (!text) {
- finish(() =>
- resolve({ ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` })
- );
- return;
- }
- let parsed: unknown;
- try {
- parsed = JSON.parse(text);
- } catch {
- finish(() =>
- resolve({
- ok: false,
- status,
- errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}`
- })
- );
- return;
- }
- if (status >= 200 && status < 300) {
- const { result } = parsed as { result?: T };
- if (result === undefined) {
- finish(() => resolve({ ok: false, status, errorMessage: "Gateway response missing `result` field" }));
- return;
- }
- finish(() => resolve({ ok: true, status, result }));
- return;
- }
- const errEnv = (parsed as { error?: { message?: string } }).error;
- finish(() =>
- resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` })
- );
- });
- res.on("error", (err) => {
- logger.warn({ err }, `WinRM RPC response stream error [port=${args.port}]`);
- finish(() => reject(err));
- });
- }
- );
- // The socket `timeout` above resets on every byte, so a slow but steady stream never trips it.
- // This timer caps total wall-clock regardless of activity.
- deadlineTimer = setTimeout(() => {
- req.destroy(new Error(`WinRM RPC exceeded the ${WINRM_RPC_TIMEOUT_MS}ms deadline`));
- }, WINRM_RPC_TIMEOUT_MS);
- req.on("timeout", () => {
- req.destroy(new Error(`WinRM RPC timed out after ${WINRM_RPC_TIMEOUT_MS}ms`));
- });
- req.on("error", (err) => {
- logger.warn({ err }, `WinRM RPC request error [port=${args.port}]`);
- finish(() => reject(err));
- });
- req.write(payload);
- req.end();
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: args.endpoint,
+ payload: JSON.stringify(args.body),
+ timeoutMs: WINRM_RPC_TIMEOUT_MS,
+ deadlineMs: WINRM_RPC_TIMEOUT_MS,
+ maxResponseBytes: MAX_WINRM_RPC_RESPONSE_BYTES,
+ label: "WinRM"
});
+
+ if (!text) {
+ return { ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` };
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return { ok: false, status, errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}` };
+ }
+ if (status >= 200 && status < 300) {
+ const { result } = parsed as { result?: T };
+ if (result === undefined) {
+ return { ok: false, status, errorMessage: "Gateway response missing `result` field" };
+ }
+ return { ok: true, status, result };
+ }
+ const errEnv = (parsed as { error?: { message?: string } }).error;
+ return { ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` };
};