Skip to content

Commit 3eaddbf

Browse files
Hylouis233lidge-jun
authored andcommitted
fix(cli): harden MiniMax wrapper isolation
1 parent 1c84515 commit 3eaddbf

2 files changed

Lines changed: 254 additions & 36 deletions

File tree

‎src/cli/minimax.ts‎

Lines changed: 143 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* image/video/speech/music/search/quota endpoints are MiniMax-specific APIs that
88
* OpenCodex does not claim to implement.
99
*/
10-
import { spawn } from "node:child_process";
10+
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
1111
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1212
import { tmpdir } from "node:os";
1313
import { join } from "node:path";
@@ -32,10 +32,47 @@ export interface MmxTextBridge {
3232
}
3333

3434
export interface MmxTextBridgeOptions {
35+
/** Optional outer guard; production delegates timeout policy to `/v1/messages`. */
3536
headerTimeoutMs?: number;
3637
}
3738

38-
const MMX_BRIDGE_HEADER_TIMEOUT_MS = 30_000;
39+
export interface MmxTerminationTarget {
40+
pid?: number;
41+
exitCode: number | null;
42+
signalCode: NodeJS.Signals | null;
43+
kill(signal?: NodeJS.Signals | number): boolean;
44+
}
45+
46+
export interface MmxTerminationDeps {
47+
platform?: NodeJS.Platform;
48+
killWindowsTree?: (pid: number) => void;
49+
}
50+
51+
export interface MmxSignalHost {
52+
on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
53+
off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
54+
}
55+
56+
export interface MmxTerminationHandlersOptions {
57+
getChild: () => MmxTerminationTarget | null;
58+
cleanup: () => Promise<void>;
59+
host?: MmxSignalHost;
60+
now?: () => number;
61+
terminationDeps?: MmxTerminationDeps;
62+
onCleanupError?: (error: unknown) => void;
63+
}
64+
65+
const MMX_TERMINATION_DUPLICATE_WINDOW_MS = 500;
66+
67+
const MMX_CHILD_OWNED_ENV_KEYS = new Set([
68+
"MMX_CONFIG_DIR",
69+
"MINIMAX_BASE_URL",
70+
"MINIMAX_REGION",
71+
"MINIMAX_API_KEY",
72+
"HTTP_PROXY",
73+
"HTTPS_PROXY",
74+
"ALL_PROXY",
75+
]);
3976

4077
const MMX_GLOBAL_BOOLEAN_FLAGS = new Set([
4178
"--quiet",
@@ -89,23 +126,20 @@ export function buildMmxEnv(
89126
configDir: string,
90127
base: MinimaxLaunchEnv = process.env,
91128
): MinimaxLaunchEnv {
92-
const env: MinimaxLaunchEnv = {
93-
...base,
94-
MMX_CONFIG_DIR: configDir,
95-
MINIMAX_BASE_URL: `http://${probeHostname(live.hostname)}:${live.port}`,
96-
// Prevent a parent-shell region from triggering key detection against the
97-
// official MiniMax hosts. The base URL above remains authoritative.
98-
MINIMAX_REGION: "global",
99-
};
129+
const env: MinimaxLaunchEnv = { ...base };
100130
// The official MMX client installs one ProxyAgent whenever any proxy variable
101131
// is present and does not apply NO_PROXY. Its OpenCodex destination is always
102132
// loopback, so carrying these variables could send the request off-machine.
103-
for (const key of [
104-
"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy",
105-
// The isolated config already supplies the public loopback placeholder.
106-
// Do not expose a user's real MiniMax environment credential to the child.
107-
"MINIMAX_API_KEY",
108-
]) delete env[key];
133+
// Windows environment names are case-insensitive; strip every inherited
134+
// spelling before installing the wrapper-owned values below.
135+
for (const key of Object.keys(env)) {
136+
if (MMX_CHILD_OWNED_ENV_KEYS.has(key.toUpperCase())) delete env[key];
137+
}
138+
env.MMX_CONFIG_DIR = configDir;
139+
env.MINIMAX_BASE_URL = `http://${probeHostname(live.hostname)}:${live.port}`;
140+
// Prevent a parent-shell region from triggering key detection against the
141+
// official MiniMax hosts. The base URL above remains authoritative.
142+
env.MINIMAX_REGION = "global";
109143
return env;
110144
}
111145

@@ -119,7 +153,6 @@ export function startMmxTextBridge(
119153
live: Pick<LiveProxy, "hostname" | "port">,
120154
options: MmxTextBridgeOptions = {},
121155
): MmxTextBridge {
122-
const headerTimeoutMs = options.headerTimeoutMs ?? MMX_BRIDGE_HEADER_TIMEOUT_MS;
123156
const upstreamOrigin = `http://${probeHostname(live.hostname)}:${live.port}`;
124157
const server = Bun.serve({
125158
hostname: "127.0.0.1",
@@ -149,13 +182,18 @@ export function startMmxTextBridge(
149182
headers.set("x-api-key", LOOPBACK_API_KEY_PLACEHOLDER);
150183
headers.delete("host");
151184
headers.delete("content-length");
152-
const headerDeadline = clearableDeadline(headerTimeoutMs, req.signal);
185+
// The canonical data plane owns its configured response-header, retry,
186+
// and stream-stall budgets. An extra default here would cut off valid
187+
// non-streaming or failover completions before their real response.
188+
const headerDeadline = options.headerTimeoutMs === undefined
189+
? null
190+
: clearableDeadline(options.headerTimeoutMs, req.signal);
153191
try {
154192
return await fetch(new Request(target, {
155193
method: "POST",
156194
headers,
157195
body: req.body,
158-
signal: headerDeadline.signal,
196+
signal: headerDeadline?.signal ?? req.signal,
159197
}));
160198
} catch {
161199
return Response.json({
@@ -165,7 +203,7 @@ export function startMmxTextBridge(
165203
} finally {
166204
// Once response headers arrive, streaming body cancellation remains
167205
// linked to the client while this response-header timer is disarmed.
168-
headerDeadline.clear();
206+
headerDeadline?.clear();
169207
}
170208
},
171209
});
@@ -252,15 +290,91 @@ export function isStandaloneInformationalInvocation(
252290
return client === "mmx" ? arg === "-v" : arg === "-v" || arg === "-V";
253291
}
254292

293+
/** Forward wrapper termination only while the MMX child is still live. */
294+
export function forwardMmxTerminationSignal(
295+
child: MmxTerminationTarget,
296+
signal: "SIGINT" | "SIGTERM",
297+
deps: MmxTerminationDeps = {},
298+
): boolean {
299+
if (child.exitCode !== null || child.signalCode !== null) return false;
300+
try {
301+
if ((deps.platform ?? process.platform) === "win32") {
302+
if (!Number.isInteger(child.pid) || child.pid === undefined || child.pid <= 0) return false;
303+
const killWindowsTree = deps.killWindowsTree ?? (pid => {
304+
const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
305+
execFileSync(taskkill, ["/PID", String(pid), "/T", "/F"], {
306+
stdio: "ignore",
307+
windowsHide: true,
308+
});
309+
});
310+
killWindowsTree(child.pid);
311+
return true;
312+
}
313+
return child.kill(signal);
314+
} catch {
315+
return false;
316+
}
317+
}
318+
319+
/** Install persistent, duplicate-aware wrapper signal handlers. */
320+
export function installMmxTerminationHandlers(
321+
options: MmxTerminationHandlersOptions,
322+
): () => void {
323+
const host = options.host ?? process;
324+
const now = options.now ?? Date.now;
325+
let lastTerminationSignalAt: number | null = null;
326+
const onTerminationSignal = (signal: "SIGINT" | "SIGTERM") => {
327+
const receivedAt = now();
328+
// Ctrl-C reaches the foreground Bun process directly and is also
329+
// forwarded by bin/ocx.mjs. Keep the listener installed and coalesce the
330+
// near-simultaneous duplicate so async cleanup cannot be interrupted by
331+
// the default signal action after a once-listener disappears.
332+
if (
333+
lastTerminationSignalAt !== null
334+
&& receivedAt - lastTerminationSignalAt < MMX_TERMINATION_DUPLICATE_WINDOW_MS
335+
) return;
336+
lastTerminationSignalAt = receivedAt;
337+
const child = options.getChild();
338+
if (child) forwardMmxTerminationSignal(child, signal, options.terminationDeps);
339+
try {
340+
void options.cleanup().catch(error => { options.onCleanupError?.(error); });
341+
} catch (error) {
342+
options.onCleanupError?.(error);
343+
}
344+
};
345+
const onSigint = () => onTerminationSignal("SIGINT");
346+
const onSigterm = () => onTerminationSignal("SIGTERM");
347+
host.on("SIGINT", onSigint);
348+
host.on("SIGTERM", onSigterm);
349+
return () => {
350+
host.off("SIGINT", onSigint);
351+
host.off("SIGTERM", onSigterm);
352+
};
353+
}
354+
355+
/** Keep signal handlers active until asynchronous bridge cleanup has settled. */
356+
export async function finishMmxClientCleanup(
357+
cleanup: () => Promise<void>,
358+
removeTerminationHandlers: () => void,
359+
): Promise<void> {
360+
try {
361+
await cleanup();
362+
} finally {
363+
removeTerminationHandlers();
364+
}
365+
}
366+
255367
function spawnClient(
256368
command: "mcode" | "mmx",
257369
args: readonly string[],
258370
env: NodeJS.ProcessEnv,
259371
installHint: string,
372+
onSpawn?: (child: ChildProcess) => void,
260373
): Promise<number> {
261374
return new Promise(resolve => {
262375
const inv = commandInvocation(command, [...args]);
263376
const child = spawn(inv.file, inv.args, { stdio: "inherit", env, ...inv.options });
377+
onSpawn?.(child);
264378
child.on("error", (error: NodeJS.ErrnoException) => {
265379
console.error(error.code === "ENOENT" ? installHint : `❌ Failed to launch ${command}: ${error.message}`);
266380
resolve(1);
@@ -336,6 +450,7 @@ export async function cmdMmx(args: string[]): Promise<number> {
336450

337451
const configDir = mkdtempSync(join(tmpdir(), "opencodex-mmx-"));
338452
let bridge: MmxTextBridge | null = null;
453+
let mmxChild: ChildProcess | null = null;
339454
let cleanupPromise: Promise<void> | null = null;
340455
let removeTerminationHandlers = () => {};
341456
const cleanup = (): Promise<void> => {
@@ -361,20 +476,15 @@ export async function cmdMmx(args: string[]): Promise<number> {
361476
bridge = startMmxTextBridge(live);
362477
const env = buildMmxEnv({ hostname: "127.0.0.1", port: bridge.port }, configDir, process.env) as NodeJS.ProcessEnv;
363478
console.error(`✅ MiniMax CLI text bridged to http://${probeHostname(live.hostname)}:${live.port}/v1/messages.`);
364-
const onTerminationSignal = () => {
365-
void cleanup().catch(error => {
479+
removeTerminationHandlers = installMmxTerminationHandlers({
480+
getChild: () => mmxChild,
481+
cleanup,
482+
onCleanupError: error => {
366483
console.error(`❌ Failed to clean up the MMX bridge after a termination signal: ${String(error)}`);
367-
});
368-
};
369-
process.once("SIGINT", onTerminationSignal);
370-
process.once("SIGTERM", onTerminationSignal);
371-
removeTerminationHandlers = () => {
372-
process.off("SIGINT", onTerminationSignal);
373-
process.off("SIGTERM", onTerminationSignal);
374-
};
375-
return await spawnClient("mmx", args, env, MMX_INSTALL_HINT);
484+
},
485+
});
486+
return await spawnClient("mmx", args, env, MMX_INSTALL_HINT, child => { mmxChild = child; });
376487
} finally {
377-
removeTerminationHandlers();
378-
await cleanup();
488+
await finishMmxClientCleanup(cleanup, removeTerminationHandlers);
379489
}
380490
}

0 commit comments

Comments
 (0)