Compare commits

..

2 Commits

Author SHA1 Message Date
diegosouzapw
bb51db4552 fix(cli): keep the startup plugin hook inside plugins.mjs so the entrypoint stays under its size baseline
Moves the --version short-circuit and the env-based context into
loadCliPlugins(), leaving bin/omniroute.mjs with a two-line call.
Bundle size goes from 10401 to 10353 bytes (baseline 10384).

Refs #21056
2026-11-23 17:41:45 -03:00
diegosouzapw
6b61dde53c fix(cli): load plugins at startup and install them where discovery looks (#21056) 2026-11-23 15:44:30 -03:00
32 changed files with 389 additions and 1116 deletions

View File

@@ -1,29 +1,28 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { t } from "../i18n.mjs";
import { emit } from "../output.mjs";
import { discoverPlugins } from "../plugins.mjs";
import { getPluginPrefix, resolvePluginSpec, runPluginNpm } from "../pluginNpm.mjs";
import { readFileSync } from "node:fs";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
// Run npm with an explicit argument array and no shell. Passing args this way
// (instead of string-interpolating into `execSync`) prevents a malicious plugin
// name like `foo; rm -rf ~` or `` foo`id` `` from being interpreted by the shell.
function runNpm(args) {
const isBun = Boolean(process.versions.bun);
const pm = isBun ? "bun" : "npm";
const cmdArgs = isBun && args[0] === "install" ? ["add", ...args.slice(1)] : args;
const res = spawnSync(pm, cmdArgs, { stdio: "inherit", shell: false });
if (res.error) throw res.error;
if (typeof res.status === "number" && res.status !== 0) {
throw new Error(`${pm} exited with code ${res.status}`);
}
}
const HOST_MAJOR = Number(
JSON.parse(
readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "package.json"),
"utf8"
)
).version.split(".")[0]
);
const HOST_RANGE = `>=${HOST_MAJOR}.0.0`;
const TEMPLATE_INDEX = `export const meta = {
name: "PLUGIN_NAME",
version: "0.1.0",
description: "OmniRoute plugin",
omnirouteApi: ">=4.0.0",
omnirouteApi: "HOST_RANGE",
};
export function register(program, ctx) {
@@ -65,8 +64,7 @@ export function registerPlugin(program) {
.description(t("plugin.install") || "Install a plugin")
.option("-y, --yes", "Skip confirmation prompt")
.action(async (name, opts) => {
const isLocal = name.startsWith("./") || name.startsWith("/") || name.startsWith("../");
const pkgName = isLocal ? name : `omniroute-cmd-${name}`;
const pkgName = resolvePluginSpec(name);
if (!opts.yes) {
process.stderr.write(
@@ -83,10 +81,10 @@ export function registerPlugin(program) {
}
try {
runNpm(["install", "-g", pkgName]);
runPluginNpm(["install", "--prefix", getPluginPrefix(), pkgName]);
process.stdout.write(`\n✓ Installed: ${pkgName}\n`);
} catch {
process.stderr.write(`✗ Failed to install ${pkgName}\n`);
} catch (err) {
process.stderr.write(`✗ Failed to install ${pkgName}: ${err.message}\n`);
process.exit(1);
}
});
@@ -105,10 +103,10 @@ export function registerPlugin(program) {
}
}
try {
runNpm(["uninstall", "-g", pkgName]);
runPluginNpm(["uninstall", "--prefix", getPluginPrefix(), pkgName]);
process.stdout.write(`✓ Removed: ${pkgName}\n`);
} catch {
process.stderr.write(`✗ Failed to remove ${pkgName}\n`);
} catch (err) {
process.stderr.write(`✗ Failed to remove ${pkgName}: ${err.message}\n`);
process.exit(1);
}
});
@@ -161,7 +159,7 @@ export function registerPlugin(program) {
try {
if (name) {
const pkg = `omniroute-cmd-${name}`;
runNpm(["update", "-g", pkg]);
runPluginNpm(["update", "--prefix", getPluginPrefix(), pkg]);
process.stdout.write(`✓ Updated: ${pkg}\n`);
return;
}
@@ -176,10 +174,10 @@ export function registerPlugin(program) {
process.stdout.write("No plugins installed to update.\n");
return;
}
runNpm(["update", "-g", ...names]);
runPluginNpm(["update", "--prefix", getPluginPrefix(), ...names]);
process.stdout.write(`✓ Updated: ${names.join(", ")}\n`);
} catch {
process.stderr.write(`✗ Update failed\n`);
} catch (err) {
process.stderr.write(`✗ Update failed: ${err.message}\n`);
process.exit(1);
}
});
@@ -204,14 +202,17 @@ export function registerPlugin(program) {
type: "module",
main: "index.mjs",
description: `OmniRoute CLI plugin: ${safeName}`,
engines: { omniroute: ">=4.0.0" },
engines: { omniroute: HOST_RANGE },
keywords: ["omniroute-plugin", "omniroute-cmd"],
},
null,
2
) + "\n"
);
writeFileSync(join(dir, "index.mjs"), TEMPLATE_INDEX.replace(/PLUGIN_NAME/g, safeName));
writeFileSync(
join(dir, "index.mjs"),
TEMPLATE_INDEX.replace(/PLUGIN_NAME/g, safeName).replace(/HOST_RANGE/g, HOST_RANGE)
);
writeFileSync(
join(dir, "README.md"),
`# omniroute-cmd-${safeName}\n\nAn OmniRoute CLI plugin.\n\n## Install\n\n\`\`\`bash\nomniroute plugin install ${safeName}\n\`\`\`\n`

82
bin/cli/pluginNpm.mjs Normal file
View File

@@ -0,0 +1,82 @@
// npm plumbing for `omniroute plugin install|remove|update` (#21056).
//
// Plugins are installed into a private npm prefix (`~/.omniroute/plugins`), which is
// the same directory `discoverPlugins()` scans — a global `npm install -g` landed in
// `$(npm root -g)`, a place discovery never looked at.
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { npmBin, npmExecInvocation, npmExecOptions } from "./npm-exec.mjs";
import { escapeWindowsShellArg } from "./utils/winShellArgs.mjs";
const LITERAL_TOKEN = /^[A-Za-z0-9@._/:=+-]+$/;
const UNSAFE_CHARS = /[\0\r\n]/;
const WINDOWS_DRIVE_RE = /^[A-Za-z]:[\\/]/;
/** Where plugins are installed (an npm `--prefix`); `node_modules/` lives below it. */
export function getPluginPrefix(home = homedir()) {
return join(home, ".omniroute", "plugins");
}
/** True when the user passed a path / file: spec rather than a registry name. */
export function isLocalPluginSpec(name) {
return (
name === "." ||
name === ".." ||
name.startsWith("./") ||
name.startsWith("../") ||
name.startsWith(".\\") ||
name.startsWith("..\\") ||
name.startsWith("/") ||
name.startsWith("~/") ||
name.startsWith("file:") ||
WINDOWS_DRIVE_RE.test(name) ||
name.startsWith("\\\\")
);
}
/** Spec handed to npm: absolute path for local installs, `omniroute-cmd-<name>` otherwise. */
export function resolvePluginSpec(name, cwd = process.cwd(), home = homedir()) {
if (!isLocalPluginSpec(name)) {
return name.startsWith("omniroute-cmd-") || name.startsWith("@")
? name
: `omniroute-cmd-${name}`;
}
if (name.startsWith("file:")) return name;
if (name.startsWith("~/")) return join(home, name.slice(2));
if (isAbsolute(name) || WINDOWS_DRIVE_RE.test(name) || name.startsWith("\\\\")) return name;
return resolve(cwd, name);
}
/**
* Build `[file, args, options]` for spawnSync. Tokens that are not plain literals are
* validated (no NUL/newline, no leading "-") and, on win32, escaped before joining
* (Hard Rule #13).
*/
export function buildPluginNpmInvocation(args, platform = process.platform) {
const isBun = Boolean(process.versions.bun);
const cmdArgs = isBun && args[0] === "install" ? ["add", ...args.slice(1)] : args;
const bin = npmBin(platform);
const opts = npmExecOptions(platform, { stdio: "inherit" });
cmdArgs.forEach((token, i) => {
if (
typeof token !== "string" ||
UNSAFE_CHARS.test(token) ||
(i > 0 && token.startsWith("-") && !LITERAL_TOKEN.test(token))
) {
throw new Error(`Refusing unsafe npm argument ${JSON.stringify(token)}`);
}
});
if (platform !== "win32") return npmExecInvocation(platform, bin, cmdArgs, opts);
const line = [bin, ...cmdArgs.map((t) => (LITERAL_TOKEN.test(t) ? t : escapeWindowsShellArg(t)))];
return [line.join(" "), [], opts];
}
export function runPluginNpm(args, platform = process.platform) {
const [file, fileArgs, opts] = buildPluginNpmInvocation(args, platform);
const res = spawnSync(file, fileArgs, opts);
if (res.error) throw res.error;
if (typeof res.status === "number" && res.status !== 0) {
throw new Error(`${file.split(" ")[0]} exited with code ${res.status}`);
}
}

View File

@@ -1,4 +1,4 @@
import { readdirSync, existsSync, readFileSync } from "node:fs";
import { readdirSync, existsSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { pathToFileURL } from "node:url";
@@ -6,24 +6,51 @@ import { pathToFileURL } from "node:url";
const PLUGIN_PREFIX_RE = /^(@[^/]+\/)?omniroute-cmd-/;
function getPluginDirs() {
return [join(homedir(), ".omniroute", "plugins"), process.env.OMNIROUTE_PLUGIN_PATH].filter(
Boolean
);
const prefix = join(homedir(), ".omniroute", "plugins");
// `omniroute plugin install` uses `prefix` as an npm --prefix, so packages land in
// `<prefix>/node_modules` (#21056).
return [prefix, join(prefix, "node_modules"), process.env.OMNIROUTE_PLUGIN_PATH].filter(Boolean);
}
function isDir(path) {
try {
return statSync(path).isDirectory(); // follows symlinks (npm links local installs)
} catch {
return false;
}
}
function listCandidates(dir) {
const out = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith(".")) continue;
const full = join(dir, entry.name);
if (!isDir(full)) continue;
if (entry.name.startsWith("@")) {
try {
for (const sub of readdirSync(full)) out.push(join(full, sub));
} catch {
// ignore unreadable scope dir
}
} else {
out.push(full);
}
}
return out;
}
export async function discoverPlugins() {
const found = [];
for (const dir of getPluginDirs()) {
if (!existsSync(dir)) continue;
let entries;
let candidates;
try {
entries = readdirSync(dir, { withFileTypes: true });
candidates = listCandidates(dir);
} catch {
continue;
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const pkgPath = join(dir, entry.name, "package.json");
for (const candidate of candidates) {
const pkgPath = join(candidate, "package.json");
if (!existsSync(pkgPath)) continue;
let pkg;
try {
@@ -32,11 +59,12 @@ export async function discoverPlugins() {
continue;
}
if (!pkg.name || !PLUGIN_PREFIX_RE.test(pkg.name)) continue;
if (found.some((f) => f.name === pkg.name)) continue;
found.push({
name: pkg.name,
version: pkg.version || "0.0.0",
description: pkg.description || "",
dir: join(dir, entry.name),
dir: candidate,
pkg,
});
}
@@ -67,6 +95,12 @@ export function buildPluginContext(opts = {}) {
};
}
// Startup entry (#21056): `--version`/`-v` stays fast and never imports plugin code.
export async function loadCliPlugins(program, argv = process.argv, env = process.env) {
if (argv.slice(2).some((a) => a === "--version" || a === "-v")) return 0;
return loadPlugins(program, { baseUrl: env.OMNIROUTE_BASE_URL, apiKey: env.OMNIROUTE_API_KEY });
}
export async function loadPlugins(program, ctx = {}) {
const plugins = await discoverPlugins();
for (const p of plugins) {

View File

@@ -449,6 +449,10 @@ try {
pathToFileURL(join(ROOT, "bin", "cli", "program.mjs")).href
);
const program = createProgram();
const { loadCliPlugins } = await import(
pathToFileURL(join(ROOT, "bin", "cli", "plugins.mjs")).href
);
await loadCliPlugins(program);
await program.parseAsync(process.argv);
} catch (err) {
if (err?.exitCode !== undefined) process.exit(err.exitCode);

View File

@@ -1 +0,0 @@
- **fix(security):** GitHub Copilot Responses-only inference, model display names and the Context7 library id check use linear regexes, so a long crafted model or library id no longer blocks the event loop for seconds (CodeQL js/polynomial-redos #1325, #1324, #1296)

View File

@@ -1 +0,0 @@
- **fix(security):** Compression engines bound their regex work on hostile input: the headroom GCF inline-array check and the RTK raw-output command slug run in linear time, and CCR `grep` rejects patterns with more than one unbounded quantifier and stops a scan that exceeds a 1 s time budget (CodeQL #1301, #1302, #1349)

View File

@@ -1 +0,0 @@
- **fix(security):** The remaining async media handlers (Kie image, video and music; Runway; DashScope; Novita; MiniMax video; the video job presets; RenderHour video and speech; UC image and video) cap a caller's `poll_interval_ms` at 30 s and `timeout_ms` at 10 minutes, or at the built-in default when that is longer; defaults are unchanged (CodeQL #1389) ([#20867](https://github.com/cheaper-inference/OmniRoute/pull/20867))

View File

@@ -0,0 +1 @@
- fix(cli): CLI plugins are now loaded at startup, `plugin install` uses the directory discovery scans (and `.`/local paths, npm.cmd on Windows), scaffold range matches the host version (#21056)

View File

@@ -1 +0,0 @@
- fix(security): model-sync failure logs use a constant format string, so a provider id is never read as a format directive (CodeQL #1407)

View File

@@ -157,14 +157,13 @@
"dedicatedGate": true
},
"codeqlAlerts": {
"value": 6,
"value": 103,
"direction": "down",
"dedicatedGate": true,
"_rebaseline_2026_08_06_base_grew": "Base branch file-size drift: translator-openai-to-gemini.test.ts grew 1619->1622 (test assertions for Gemini translator compatibility). CodeQL alert (js/insufficient-password-hash in raycast.ts) is pre-existing base-red; incremented baseline to match.",
"_rebaseline_2026_08_10_9940_fingerprint": "CodeQL base-red (green-prs sweep, issue #9985): 2nd js/insufficient-password-hash alert at src/shared/middleware/chatBodyAdmission.ts:265,269 introduced by #9940 (per-connection virtual admission lanes). Both are API-key/bearer FINGERPRINTS (createHash('sha256') truncated to 16-hex admission-lane key), not password VERIFICATION — false-positive class for this rule. Reproduces on release/v3.8.50 tip. Owner-authorized rebaseline 1->2; revisit at v3.9.0.",
"_rebaseline_2026_08_11_merge_storm_drift": "2 -> 9. Drift from the 2026-08-11 authorized merge storm (99 PRs into release/v3.8.50): js/insufficient-password-hash in open-sse/executors/chatgpt-web-codex/storageState.ts x3 + conol-web.ts (PRs #8949/#8974 — Chromium browser-profile credential storage SKUs that CodeQL flags under the password-hash rule; same fingerprint/credential-cache false-positive class already rebaselined in #9940/2026-08-06), js/stack-trace-exposure (chatgpt-web-codex.ts, #8949 debug logging), js/double-escaping (environment.ts, #8949), js/insecure-randomness (tinycms.ts, #9435). None introduced by this base-fix PR. Owner-authorized rebaseline (2026-08-11); revisit hardening at v3.9.0.",
"_rebaseline_2026_11_20_codeql_2_27_5": "6 -> 103. Tool upgrade, not code: the default setup moved CodeQL 2.27.4 -> 2.27.5 on 2026-11-20 and the release/v3.8.55 JS analysis went 236 -> 339 results with the same 87 rules (760357c4 only touched a test file). 101 alerts were created together at 14:07:12Z (path-injection 34, polynomial-redos 30, request-forgery 22, unvalidated-dynamic-method-call 6, regex-injection 6, resource-exhaustion 3). Owner-authorized temporary ceiling (2026-11-20) to unblock merges while the security wave triages them (dismiss false positives with justification, fix real defects); a follow-up PR lowers the value to the measured count.",
"_rebaseline_2026_11_21_restore_after_2_27_5": "103 -> 6. Ends the temporary ceiling of 2026-11-20: the security wave dismissed the false positives with justification and fixed the real defects (#20770, #20775, #20776, #20781, #20819, #20820, #20824, #20839; #20825 and #20867 close the last two). 6 is the ceiling in force before the CodeQL 2.27.5 upgrade (velocity phase headroom included); tightening to the measured count is left to the release --update."
"_rebaseline_2026_11_20_codeql_2_27_5": "6 -> 103. Tool upgrade, not code: the default setup moved CodeQL 2.27.4 -> 2.27.5 on 2026-11-20 and the release/v3.8.55 JS analysis went 236 -> 339 results with the same 87 rules (760357c4 only touched a test file). 101 alerts were created together at 14:07:12Z (path-injection 34, polynomial-redos 30, request-forgery 22, unvalidated-dynamic-method-call 6, regex-injection 6, resource-exhaustion 3). Owner-authorized temporary ceiling (2026-11-20) to unblock merges while the security wave triages them (dismiss false positives with justification, fix real defects); a follow-up PR lowers the value to the measured count."
},
"secretFindings": {
"_note": "Zeroed 2026-07-13 (WS6/D3): the 3 frozen generic-api-key FPs are allowlisted with justification in .gitleaks.toml — any NEW finding regresses the ratchet.",

View File

@@ -45,7 +45,7 @@ omniroute-cmd-myplugin/
"version": "0.1.0",
"type": "module",
"main": "index.mjs",
"engines": { "omniroute": ">=4.0.0" },
"engines": { "omniroute": ">=3.8.0" },
"keywords": ["omniroute-plugin", "omniroute-cmd"]
}
```
@@ -57,7 +57,7 @@ export const meta = {
name: "myplugin",
version: "0.1.0",
description: "My plugin for OmniRoute",
omnirouteApi: ">=4.0.0",
omnirouteApi: ">=3.8.0",
};
export function register(program, ctx) {
@@ -94,8 +94,11 @@ The `ctx` object passed to `register(program, ctx)`:
Plugins are discovered from:
1. `~/.omniroute/plugins/<name>/` — user-local installs
2. `OMNIROUTE_PLUGIN_PATH` env var — custom directory
1. `~/.omniroute/plugins/node_modules/<name>/` — where `omniroute plugin install` puts packages (an npm `--prefix`, not `npm -g`)
2. `~/.omniroute/plugins/<name>/` — hand-copied plugin directories
3. `OMNIROUTE_PLUGIN_PATH` env var — custom directory
Symlinked directories (what npm creates for `plugin install ./dir`) are followed.
Both are **CLI-only**. The server-side plugin runtime (the marketplace/`plugin.json`
plugins that run inside the proxy) has its own scanner with its own override,

View File

@@ -1006,8 +1006,8 @@ async function handleKieImageGeneration({
}: KieImageOptions) {
const startTime = Date.now();
const token = credentials?.apiKey || credentials?.accessToken;
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 2500);
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
const size = typeof body.size === "string" ? body.size : undefined;

View File

@@ -34,7 +34,6 @@ import { resolveUcCredential } from "../../../executors/uc/credentials.ts";
import { mintUcSessionToken } from "../../../executors/uc/clerkAuth.ts";
import { UC_ORIGIN } from "../../../executors/uc/constants.ts";
import { sanitizeErrorMessage } from "../../../utils/error.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
import { saveImageErrorResult, saveImageSuccessResult } from "../../imageGeneration.ts";
/** Persona web image-gen endpoint (immediate response + result-URL polling). */
@@ -309,11 +308,11 @@ async function handleUcPersonaImage(
});
}
const timeoutMs = clampPollTimeoutMs(
const timeoutMs = normalizePositiveNumber(
body.timeout_ms,
normalizePositiveNumber(process.env.UC_IMAGE_POLL_TIMEOUT_MS, UC_POLL_TIMEOUT_MS_DEFAULT)
);
const pollIntervalMs = clampPollIntervalMs(
const pollIntervalMs = normalizePositiveNumber(
body.poll_interval_ms,
normalizePositiveNumber(process.env.UC_IMAGE_POLL_INTERVAL_MS, UC_POLL_INTERVAL_MS_DEFAULT)
);

View File

@@ -365,6 +365,11 @@ export async function runRenderhourJob({
return pollRenderhourJob({ baseUrl, token, job, timeoutMs, pollIntervalMs, log, signal });
}
/** A positive number from the request (e.g. `timeout_ms`), else the fallback. */
export function renderhourNumber(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
}
/** Turns a thrown upload / network error into the handlers' failure shape. */
export function renderhourFailure(err: unknown): { status: number; error: string } {
if (err instanceof RenderhourRequestError) {

View File

@@ -16,7 +16,6 @@
import { getMusicProvider, parseMusicModel } from "../config/musicRegistry.ts";
import { kieExecutor } from "../executors/kie.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
import { vertexGenerateMusic } from "../executors/vertexMedia.ts";
import {
submitComfyWorkflow,
@@ -362,8 +361,8 @@ async function handleKieMusicGeneration({
} | null;
}) {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
const token = credentials?.apiKey || credentials?.accessToken;
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");

View File

@@ -9,10 +9,10 @@ import { errorResponse } from "../utils/error.ts";
import {
renderhourBaseUrl,
renderhourFailure,
renderhourNumber,
renderhourToken,
runRenderhourJob,
} from "./mediaGeneration/renderhour.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
export async function handleRenderhourSpeech({
providerConfig,
@@ -37,8 +37,8 @@ export async function handleRenderhourSpeech({
baseUrl: renderhourBaseUrl(credentials, providerConfig.baseUrl),
token,
request: { model: modelId, text },
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 180_000),
pollIntervalMs: clampPollIntervalMs(body.poll_interval_ms, 2000),
timeoutMs: renderhourNumber(body.timeout_ms, 180_000),
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 2000),
});
if (result.ok === false) return errorResponse(result.status, result.error);
return audioStreamResponse(await fetch(result.job.outputs[0].url));

View File

@@ -30,11 +30,11 @@ import {
} from "./videoGeneration/job.ts";
import { abortedVideoResult, POLL_ABORTED, pollJsonAfter } from "./videoGeneration/abort.ts";
import { sleep } from "../utils/sleep.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
import {
downloadResultVideo,
extractRunwayFailureMessage,
normalizeRunwayVideoResult,
resolvePositiveInteger,
resultVideoErrorText,
resolveRunwayDuration,
resolveRunwayPromptImage,
@@ -135,11 +135,12 @@ function resolveVideoJobPollingOverrides(body: Record<string, unknown>): {
pollIntervalMs?: number;
} {
const maxPolls = Number(body.max_polls);
// 0 marks "not sent": the preset's own interval (2-5 s) then applies.
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 0);
const pollIntervalMs = Number(body.poll_interval_ms);
return {
...(Number.isFinite(maxPolls) && maxPolls > 0 ? { maxPolls: Math.floor(maxPolls) } : {}),
...(pollIntervalMs > 0 ? { pollIntervalMs } : {}),
...(Number.isFinite(pollIntervalMs) && pollIntervalMs > 0
? { pollIntervalMs: Math.floor(pollIntervalMs) }
: {}),
};
}
@@ -866,8 +867,8 @@ async function handleKieVideoGeneration({
} | null;
}) {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
const token = credentials?.apiKey || credentials?.accessToken;
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
@@ -976,8 +977,8 @@ async function handleRunwayVideoGeneration({
const ratio = resolveRunwayRatio(body);
const duration = resolveRunwayDuration(body);
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 5000);
const timeoutMs = resolvePositiveInteger(body.timeout_ms, 300000);
const pollIntervalMs = resolvePositiveInteger(body.poll_interval_ms, 5000);
const submitUrl = buildRunwayApiUrl(
useImageToVideo ? "/image_to_video" : "/text_to_video",
providerConfig.baseUrl

View File

@@ -3,7 +3,6 @@ import { saveCallLog } from "@/lib/usageDb";
import { resolveAlibabaProviderMediaBaseUrl } from "@/shared/constants/alibabaProviderRegions";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { sleep } from "../../utils/sleep.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
import { abortedVideoResult } from "./abort.ts";
// Shared with the DashScope TTS executor so the engine keeps a single import of this app
@@ -64,8 +63,8 @@ export async function handleDashscopeVideoGeneration({
signal?: AbortSignal | null;
}) {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
const token = credentials?.apiKey || credentials?.accessToken;
const isAlibabaManagedMediaProvider =
provider === "alibaba" ||

View File

@@ -16,7 +16,6 @@ import {
} from "@/shared/utils/fetchTimeout";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { sleep } from "../../utils/sleep.ts";
import { MAX_CALLER_POLL_TIMEOUT_MS } from "../../utils/pollBounds.ts";
import {
MAX_CONSECUTIVE_POLL_RETRIES,
computePollRetryDelayMs,
@@ -512,18 +511,8 @@ async function runVideoJobGeneration({
}
// Poll loop.
const maxPolls = maxPollsOverride ?? preset.maxPolls;
const pollInterval = pollIntervalOverride ?? preset.pollIntervalMs;
// A preset has no deadline: its window is maxPolls x interval. Caller overrides of either
// may not stretch it past the larger of the preset's own window and the caller ceiling
// (CodeQL #1389); with no override this leaves the preset's maxPolls unchanged.
const windowCeilingMs = Math.max(
preset.maxPolls * preset.pollIntervalMs,
MAX_CALLER_POLL_TIMEOUT_MS
);
const maxPolls = Math.min(
maxPollsOverride ?? preset.maxPolls,
Math.max(1, Math.floor(windowCeilingMs / pollInterval))
);
let consecutiveRetries = 0;
let nextDelay = pollInterval;

View File

@@ -12,7 +12,6 @@
import { saveCallLog } from "@/lib/usageDb";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
import { isJsonObject } from "../../utils/kieTask.ts";
import {
MAX_CONSECUTIVE_POLL_RETRIES,
@@ -197,8 +196,9 @@ export async function handleMinimaxVideoGeneration({
log?: MinimaxLog;
}): Promise<VideoResult> {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, DEFAULT_TIMEOUT_MS);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : DEFAULT_TIMEOUT_MS;
const pollIntervalMs =
Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : DEFAULT_POLL_INTERVAL_MS;
const token = credentials?.apiKey || credentials?.accessToken;
const request = buildMinimaxVideoRequestBody(

View File

@@ -9,7 +9,6 @@
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { sleep } from "../../utils/sleep.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
import { abortedVideoResult } from "./abort.ts";
import {
buildNovitaPollUrl,
@@ -73,8 +72,9 @@ function resolveNovitaTiming(body: NovitaHandlerArgs["body"]): {
timeoutMs: number;
pollIntervalMs: number;
} {
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, DEFAULT_TIMEOUT_MS);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : DEFAULT_TIMEOUT_MS;
const pollIntervalMs =
Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : DEFAULT_POLL_INTERVAL_MS;
return { timeoutMs, pollIntervalMs };
}

View File

@@ -57,7 +57,6 @@ import { resolveUcCredential } from "../../../executors/uc/credentials.ts";
import { mintUcSessionToken } from "../../../executors/uc/clerkAuth.ts";
import { UC_ORIGIN } from "../../../executors/uc/constants.ts";
import { sanitizeErrorMessage } from "../../../utils/error.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
/** Persona signed-upload-URL endpoint (for the image-to-video input image). */
export const UC_PERSONA_SIGNED_URL = "https://internal-6.pubyar.com/generate-signed-url";
@@ -560,8 +559,8 @@ async function handleUcPersonaVideo(ctx: PersonaContext): Promise<UcVideoResult>
Number.isFinite(timeoutSeconds) && timeoutSeconds > 0
? timeoutSeconds * 1000
: normalizePositiveNumber(process.env.UC_VIDEO_POLL_TIMEOUT_MS, UC_POLL_TIMEOUT_MS_DEFAULT);
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, defaultTimeoutMs);
const pollIntervalMs = clampVideoPollIntervalMs(
const timeoutMs = normalizePositiveNumber(body.timeout_ms, defaultTimeoutMs);
const pollIntervalMs = normalizePositiveNumber(
body.poll_interval_ms,
normalizePositiveNumber(process.env.UC_VIDEO_POLL_INTERVAL_MS, UC_POLL_INTERVAL_MS_DEFAULT)
);
@@ -703,8 +702,8 @@ async function handleUcDirectVideo(ctx: DirectContext): Promise<UcVideoResult> {
// Poll status_url until complete or timeout.
const statusUrl = extracted.statusUrl;
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, UC_POLL_TIMEOUT_MS_DEFAULT);
const pollIntervalMs = clampVideoPollIntervalMs(
const timeoutMs = normalizePositiveNumber(body.timeout_ms, UC_POLL_TIMEOUT_MS_DEFAULT);
const pollIntervalMs = normalizePositiveNumber(
body.poll_interval_ms,
UC_POLL_INTERVAL_MS_DEFAULT
);

View File

@@ -15,13 +15,13 @@ import {
renderhourBaseUrl,
renderhourConfig,
renderhourFailure,
renderhourNumber,
renderhourSeconds,
renderhourToken,
runRenderhourJob,
uploadRenderhourInputs,
type RenderhourUploadTarget,
} from "../mediaGeneration/renderhour.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
type Body = Record<string, unknown>;
@@ -112,8 +112,8 @@ async function runVideoJob({
baseUrl,
token,
request,
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 900_000),
pollIntervalMs: clampVideoPollIntervalMs(body.poll_interval_ms, 5000),
timeoutMs: renderhourNumber(body.timeout_ms, 900_000),
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 5000),
log,
signal,
});

View File

@@ -86,6 +86,12 @@ function clampRunwayDuration(value) {
return Math.min(10, Math.max(2, duration));
}
export function resolvePositiveInteger(value, fallback) {
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
return Math.floor(numeric);
}
function extractRunwayOutputUrls(task) {
const rawOutput = Array.isArray(task?.output)
? task.output

View File

@@ -3,12 +3,9 @@
*
* `full`/absent → whole text (backward-compat). All modes are fail-safe:
* incoherent params or an unsafe regex yield { error }, never throw. The grep
* mode validates the pattern with `safe-regex` (no nested quantifiers), allows at
* most one unbounded quantifier, bounds matches/pattern length, and runs the scan
* under a wall-clock budget (CodeQL #1349): a caller-supplied pattern can still be
* super-linear (`.*x` is quadratic per line), so the budget is the hard bound.
* mode validates the pattern with `safe-regex` (no catastrophic backtracking)
* before compiling, and bounds matches/pattern length.
*/
import vm from "node:vm";
import safeRegex from "safe-regex";
export type CcrMode = "full" | "head" | "tail" | "lines" | "grep" | "stats";
@@ -27,8 +24,6 @@ export type CcrQueryResult = { content: string } | { error: string };
export const MAX_RANGE_LINES = 10_000;
export const MAX_GREP_MATCHES = 1_000;
export const MAX_PATTERN_LEN = 512;
/** Wall-clock budget for one grep scan over a block (ms). */
export const GREP_TIME_BUDGET_MS = 1_000;
const err = (m: string): CcrQueryResult => ({ error: m });
const ok = (c: string): CcrQueryResult => ({ content: c });
@@ -58,104 +53,30 @@ function sliceLines(lines: string[], start?: number, end?: number): CcrQueryResu
return ok(lines.slice(start - 1, Math.min(end, lines.length)).join("\n"));
}
/**
* Number of unbounded quantifiers (`*`, `+`, `{n,}`) outside character classes and
* escapes. Two or more in sequence make the backtracking polynomial in the line length
* (`.*.*.*.*x` is O(n^4)), which `safe-regex`'s star-height check does not catch.
*/
export function countUnboundedQuantifiers(pattern: string): number {
let count = 0;
let i = 0;
while (i < pattern.length) {
const c = pattern[i];
if (c === "\\") {
i += 2;
} else if (c === "[") {
i = classEnd(pattern, i);
} else {
if (c === "*" || c === "+" || (c === "{" && isOpenRange(pattern, i))) count++;
i++;
}
}
return count;
}
/** Index just past the character class that opens at `start` (escapes honoured). */
function classEnd(pattern: string, start: number): number {
let i = start + 1;
while (i < pattern.length && pattern[i] !== "]") i += pattern[i] === "\\" ? 2 : 1;
return i + 1;
}
/** True when an open range quantifier `{n,}` starts at `start`. */
function isOpenRange(pattern: string, start: number): boolean {
let j = start + 1;
while (j < pattern.length && pattern[j] >= "0" && pattern[j] <= "9") j++;
return j > start + 1 && pattern[j] === "," && pattern[j + 1] === "}";
}
// The scan runs in a dedicated context only so `timeout` can stop a runaway regex.
// No host object enters it: inputs are primitives, the result leaves as a JSON string.
const GREP_SCRIPT = new vm.Script(`(() => {
"use strict";
let re;
try { re = new RegExp(grepPattern); } catch { return JSON.stringify({ invalid: true }); }
const matched = [];
let truncated = false;
for (const line of grepText.split("\\n")) {
if (re.test(line)) {
matched.push(line);
if (matched.length >= grepMaxMatches) { truncated = true; break; }
}
}
return JSON.stringify({ matched, truncated });
})()`);
let grepContext: vm.Context | null = null;
function runGrepScan(
text: string,
pattern: string
): { matched: string[]; truncated: boolean } | "invalid" | "timeout" {
grepContext ??= vm.createContext(Object.create(null), {
codeGeneration: { strings: false, wasm: false },
});
grepContext.grepPattern = pattern;
grepContext.grepText = text;
grepContext.grepMaxMatches = MAX_GREP_MATCHES;
let raw: unknown;
try {
raw = GREP_SCRIPT.runInContext(grepContext, { timeout: GREP_TIME_BUDGET_MS });
} catch (e) {
if ((e as { code?: string })?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return "timeout";
throw e;
} finally {
grepContext.grepText = "";
grepContext.grepPattern = "";
}
const parsed = JSON.parse(String(raw)) as {
invalid?: boolean;
matched?: string[];
truncated?: boolean;
};
if (parsed.invalid === true) return "invalid";
return { matched: parsed.matched ?? [], truncated: parsed.truncated === true };
}
function grepLines(text: string, pattern?: string, unique?: boolean): CcrQueryResult {
function grepLines(lines: string[], pattern?: string, unique?: boolean): CcrQueryResult {
if (!pattern) return err("grep requires a 'pattern'");
if (pattern.length > MAX_PATTERN_LEN) return err(`pattern exceeds ${MAX_PATTERN_LEN} chars`);
if (!safeRegex(pattern)) return err("pattern rejected: potentially catastrophic backtracking");
if (countUnboundedQuantifiers(pattern) > 1) {
return err("pattern rejected: at most one unbounded quantifier (*, +, {n,}) is allowed");
let re: RegExp;
try {
re = new RegExp(pattern);
} catch {
return err("invalid regex pattern");
}
const scan = runGrepScan(text, pattern);
if (scan === "invalid") return err("invalid regex pattern");
if (scan === "timeout") {
return err(`grep exceeded its ${GREP_TIME_BUDGET_MS} ms time budget; use a narrower pattern`);
const matched: string[] = [];
let truncated = false;
for (const line of lines) {
if (re.test(line)) {
matched.push(line);
if (matched.length >= MAX_GREP_MATCHES) {
truncated = true;
break;
}
}
}
const out = unique ? [...new Set(scan.matched)] : scan.matched;
const out = unique ? [...new Set(matched)] : matched;
const body = out.join("\n");
return ok(scan.truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
return ok(truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
}
function blockStats(text: string, lines: string[]): CcrQueryResult {
@@ -180,7 +101,7 @@ export function queryBlock(text: string, q: CcrQuery): CcrQueryResult {
case "lines":
return sliceLines(lines, q.start, q.end);
case "grep":
return grepLines(text, q.pattern, q.unique);
return grepLines(lines, q.pattern, q.unique);
case "stats":
return blockStats(text, lines);
default:

View File

@@ -12,12 +12,6 @@
/** Longest single wait between two polls; matches MAX_POLL_RETRY_DELAY_MS in pollRetry.ts. */
export const MAX_CALLER_POLL_INTERVAL_MS = 30_000;
/**
* Longest single wait between two polls of a VIDEO job. A video takes minutes to render, and
* providers such as Agnes document one-minute polling, so callers may ask for up to 2 minutes.
*/
export const MAX_CALLER_VIDEO_POLL_INTERVAL_MS = 120_000;
/** Longest total polling window a caller may ask for (10 minutes). */
export const MAX_CALLER_POLL_TIMEOUT_MS = 600_000;
@@ -43,11 +37,6 @@ export function clampPollIntervalMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_POLL_INTERVAL_MS);
}
/** Same as clampPollIntervalMs with the video ceiling (MAX_CALLER_VIDEO_POLL_INTERVAL_MS). */
export function clampVideoPollIntervalMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_VIDEO_POLL_INTERVAL_MS);
}
export function clampPollTimeoutMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_POLL_TIMEOUT_MS);
}

View File

@@ -274,12 +274,8 @@ export async function syncConnectionModels(
);
return true;
} catch (err) {
// Constant format: the provider id stays a plain argument, so a "%s" in it is not a
// format directive (CodeQL #1407).
console.warn(
"[ModelSync] %s (%s): fetch failed — %s",
provider,
connectionId.slice(0, 8),
`[ModelSync] ${provider} (${connectionId.slice(0, 8)}): fetch failed —`,
(err as Error).message
);
return false;

View File

@@ -0,0 +1,152 @@
// tests/unit/repro-21056.test.ts (written in the probe worktree, now removed; copy kept in the session scratchpad)
import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import {
chmodSync,
mkdirSync,
mkdtempSync,
readFileSync,
writeFileSync,
existsSync,
} from "node:fs";
import { join, dirname } from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
const BIN = join(ROOT, "bin", "omniroute.mjs");
function makePlugin(parent: string, name = "omniroute-cmd-hello", cmd = "hello-plugin") {
const dir = join(parent, name);
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "package.json"),
JSON.stringify({ name, version: "1.0.0", type: "module", main: "index.mjs" })
);
writeFileSync(
join(dir, "index.mjs"),
`export function register(program){ program.command("${cmd}").description("fixture").action(()=>console.log("RAN")); }\n`
);
return dir;
}
function cli(args: string[], env: Record<string, string>) {
return spawnSync(process.execPath, [BIN, ...args], {
env: { ...process.env, OMNIROUTE_NO_UPDATE_NOTIFIER: "1", ...env },
encoding: "utf8",
timeout: 90_000,
});
}
test("#21056-1: a discovered plugin's command shows up in --help (loadPlugins wired in)", () => {
const sandbox = mkdtempSync(join(tmpdir(), "repro-21056-a-"));
const plugDir = join(sandbox, "plug");
makePlugin(plugDir);
const env = {
HOME: join(sandbox, "home"),
USERPROFILE: join(sandbox, "home"),
DATA_DIR: join(sandbox, "data"),
OMNIROUTE_PLUGIN_PATH: plugDir,
};
const list = cli(["plugin", "list", "--output", "json"], env);
assert.match(list.stdout, /omniroute-cmd-hello/, "precondition: discovery finds the fixture");
const help = cli(["--help"], env);
assert.match(help.stdout, /hello-plugin/, "plugin command must be registered in --help");
});
test("#21056-1b: nothing under bin/ invokes loadPlugins()", () => {
const grep = spawnSync("git", ["grep", "-n", "loadPlugins(", "--", "bin"], {
cwd: ROOT,
encoding: "utf8",
});
const callers = grep.stdout
.split("\n")
.filter((l) => l && !l.includes("export async function loadPlugins"));
assert.ok(callers.length > 0, "expected at least one caller of loadPlugins in bin/, got none");
});
test("#21056-2: `plugin install .` / `plugin install ./x` hand npm the right spec, and use a location discovery scans", () => {
const sandbox = mkdtempSync(join(tmpdir(), "repro-21056-b-"));
const fakeBin = join(sandbox, "bin");
mkdirSync(fakeBin);
const log = join(sandbox, "npm-argv.txt");
writeFileSync(join(fakeBin, "npm"), `#!/bin/sh\necho "$@" >> "${log}"\nexit 0\n`);
chmodSync(join(fakeBin, "npm"), 0o755);
const env = {
HOME: join(sandbox, "home"),
USERPROFILE: join(sandbox, "home"),
DATA_DIR: join(sandbox, "data"),
PATH: `${fakeBin}:${process.env.PATH}`,
};
cli(["plugin", "install", ".", "--yes"], env);
cli(["plugin", "install", "./local-plugin", "--yes"], env);
const argv = existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : [];
console.log("npm argv recorded:", JSON.stringify(argv));
assert.equal(argv.length, 2);
assert.doesNotMatch(
argv[0],
/omniroute-cmd-\./,
"`install .` must not become package omniroute-cmd-."
);
assert.doesNotMatch(
argv[1],
/(^| )-g( |$)/,
"install uses -g, a location discoverPlugins() never scans"
);
assert.match(argv[1], /--prefix \S*\.omniroute\/plugins /);
});
test("#21056-2b: a plugin installed with the CLI's own npm --prefix is found by `plugin list` (symlink too)", () => {
const sandbox = mkdtempSync(join(tmpdir(), "repro-21056-c-"));
const src = makePlugin(join(sandbox, "src"), "omniroute-cmd-glob", "glob-cmd");
const home = join(sandbox, "home");
const env = { HOME: home, USERPROFILE: home, DATA_DIR: join(sandbox, "data") };
const prefix = join(home, ".omniroute", "plugins");
mkdirSync(prefix, { recursive: true });
const inst = spawnSync(
"npm",
["install", "--prefix", prefix, src, "--offline", "--no-audit", "--no-fund"],
{ env: { ...process.env, ...env }, encoding: "utf8", timeout: 60_000 }
);
assert.equal(inst.status, 0, inst.stderr);
const list = cli(["plugin", "list", "--output", "json"], env);
assert.match(list.stdout, /omniroute-cmd-glob/);
const help = cli(["--help"], env);
assert.match(help.stdout, /glob-cmd/);
});
test("#21056-2c: spec resolution and win32 invocation", async () => {
const m = await import("../../bin/cli/pluginNpm.mjs");
assert.equal(m.isLocalPluginSpec("."), true);
assert.equal(m.isLocalPluginSpec("C:\\x\\p"), true);
assert.equal(m.isLocalPluginSpec("stripe"), false);
assert.equal(m.resolvePluginSpec("stripe"), "omniroute-cmd-stripe");
assert.equal(m.resolvePluginSpec(".", "/a/b"), "/a/b");
const [file, args, opts] = m.buildPluginNpmInvocation(
["install", "--prefix", "C:\\Users\\a b\\.omniroute\\plugins", "omniroute-cmd-x"],
"win32"
);
assert.match(file, /^npm\.cmd install --prefix \^+"C:/);
assert.deepEqual(args, []);
assert.equal(opts.shell, true);
assert.throws(() => m.buildPluginNpmInvocation(["install", "a\nb"], "win32"));
});
test("#21056-3: plugin.mjs spawns npm via the win32-aware helper and surfaces the real error", () => {
const src = readFileSync(join(ROOT, "bin/cli/commands/plugin.mjs"), "utf8");
assert.match(readFileSync(join(ROOT, "bin/cli/pluginNpm.mjs"), "utf8"), /npm-exec\.mjs/);
assert.doesNotMatch(src, /spawnSync\(pm, cmdArgs, \{ stdio: "inherit", shell: false \}\)/);
assert.doesNotMatch(src, /catch \{\s*process\.stderr\.write\(`✗ Failed to install/);
});
test("#21056-4: scaffold does not require a 4.0.0 host that no release satisfies", () => {
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
const src = readFileSync(join(ROOT, "bin/cli/commands/plugin.mjs"), "utf8");
const major = Number(String(pkg.version).split(".")[0]);
const m = [...src.matchAll(/>=(\d+)\.0\.0/g)].map((x) => Number(x[1]));
void 0;
assert.ok(
m.every((x) => x <= major),
`scaffold requires >=${m.join(",")}.0.0 but CLI is ${pkg.version}`
);
});

View File

@@ -1,219 +0,0 @@
/**
* Regex work in the compression engines stays bounded on hostile input
* (CodeQL #1301, #1302, #1349).
*
* - #1301 headroom/gcf needsQuote(): the inline-array check ran in O(n^2) on runs of `[`.
* - #1302 rtk maybePersistRtkRawOutput(): the command slug trim ran in O(n^2) on runs of `_`
* from a client-supplied tool_use command of unbounded length.
* - #1349 ccr grep: a caller-supplied pattern such as `.*.*.*.*x` passed the star-height
* gate and blocked the event loop for minutes on a single long line.
*
* Each block pairs a timing assertion (the pathological input finishes fast or is refused)
* with a behaviour assertion (ordinary input gives the same result as before).
*/
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { needsQuote } from "../../../open-sse/services/compression/engines/headroom/gcf/scalar.ts";
import { maybePersistRtkRawOutput } from "../../../open-sse/services/compression/engines/rtk/rawOutput.ts";
import { queryBlock } from "../../../open-sse/services/compression/engines/ccr/ccrQuery.ts";
/** Ceiling for the fixed paths. They run in a few ms when idle; before the fix the same
* inputs took 10 s (#1301), 21 s (#1302) and minutes (#1349). The headroom absorbs a loaded
* CI runner (one fixed case reached 806 ms at load average 44) without hiding a regression. */
const FAST_MS = 1_000;
/** Upper bound for a grep stopped by its 1 s time budget (budget plus scheduling slack). */
const BUDGET_CEILING_MS = 5_000;
function timed<T>(fn: () => T): { value: T; ms: number } {
const t0 = performance.now();
const value = fn();
return { value, ms: performance.now() - t0 };
}
/** Reference semantics of the SPEC 2.4 inline-array rule: some `[` whose first following
* `]` is followed by optional whitespace and a `:`. Written as a plain linear scan. */
function hasInlineArrayHeader(s: string): boolean {
for (let i = 0; i < s.length; i++) {
if (s[i] !== "[") continue;
const close = s.indexOf("]", i + 1);
if (close === -1) return false;
let k = close + 1;
while (k < s.length && /\s/.test(s[k])) k++;
if (s[k] === ":") return true;
}
return false;
}
/** Deterministic PRNG (mulberry32) so the equivalence sample is reproducible. */
function prng(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
describe("#1301 headroom/gcf needsQuote inline-array check", () => {
it("finishes fast on 50k '[' characters", () => {
for (const s of [
"[".repeat(50_000),
"a" + "[".repeat(50_000) + "]",
"[".repeat(50_000) + "]x",
]) {
const { value, ms } = timed(() => needsQuote(s));
assert.equal(value, false);
assert.ok(ms < FAST_MS, `needsQuote took ${ms.toFixed(1)}ms on ${s.length} chars`);
}
});
it("keeps the same verdict on ordinary values", () => {
assert.equal(needsQuote("ERR[404]: Not Found"), true);
assert.equal(needsQuote("[Speaker 1]: Hello"), true);
assert.equal(needsQuote("a[[b]: c"), true);
assert.equal(needsQuote("x[a[b] :y"), true);
assert.equal(needsQuote("arr[0] index"), false);
assert.equal(needsQuote("a]: [b"), false);
assert.equal(needsQuote("a[b] c: d"), false);
});
it("matches the reference rule on a random sample", () => {
const rand = prng(1301);
const alphabet = "[]: ab";
for (let n = 0; n < 20_000; n++) {
const len = Math.floor(rand() * 12);
let body = "";
for (let i = 0; i < len; i++) body += alphabet[Math.floor(rand() * alphabet.length)];
// Leading/trailing 'a' keeps the other needsQuote rules (edge space, numeric, '#'…)
// out of the way, so the verdict depends only on the inline-array rule.
const s = `a${body}a`;
assert.equal(needsQuote(s), hasInlineArrayHeader(s), JSON.stringify(s));
}
});
});
describe("#1302 rtk raw-output command slug", () => {
function persist(command: string) {
const base = process.env.DATA_DIR || os.tmpdir();
const dataDir = fs.mkdtempSync(path.join(base, "rtk-slug-"));
const previous = process.env.DATA_DIR;
process.env.DATA_DIR = dataDir;
try {
return timed(() =>
maybePersistRtkRawOutput("error: build failed\nline 2", { retention: "always", command })
);
} finally {
if (previous === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = previous;
fs.rmSync(dataDir, { recursive: true, force: true });
}
}
function slugOf(pointerPath: string): string {
const match = /^\d+-(.*)-[0-9a-f]{24}\.log$/.exec(path.basename(pointerPath));
assert.ok(match, pointerPath);
return match[1];
}
it("finishes fast on a 50k-underscore command", () => {
for (const command of ["_".repeat(50_000) + "x", "x" + "_".repeat(50_000) + "x"]) {
const { value, ms } = persist(command);
assert.ok(value, "pointer expected");
assert.ok(ms < FAST_MS, `slug took ${ms.toFixed(1)}ms on ${command.length} chars`);
}
});
it("keeps the same slug for ordinary commands", () => {
const cases: Array<[string, string]> = [
["git status --short", "git_status_--short"],
[" npm test -- --watch=false ", "npm_test_--_--watch_false"],
["__init__", "init"],
["cargo build --release && ./target/release/app", "cargo_build_--release_target_release_app"],
["a".repeat(100), "a".repeat(48)],
];
for (const [command, expected] of cases) {
const { value } = persist(command);
assert.ok(value);
assert.equal(slugOf(value.path), expected, command);
}
const { value } = persist("");
assert.ok(value);
assert.equal(slugOf(value.path), "tool-output");
});
});
describe("#1349 ccr grep pattern", () => {
it("refuses a multi-quantifier pattern on a 500+ char line quickly", () => {
const text = "a".repeat(600);
const { value, ms } = timed(() => queryBlock(text, { mode: "grep", pattern: ".*.*.*.*x" }));
assert.ok("error" in value, JSON.stringify(value));
assert.ok(ms < FAST_MS, `grep took ${ms.toFixed(1)}ms`);
});
it("stops a single-quantifier pattern that exceeds the time budget", () => {
// 2 MiB of 4096-char lines: `.*x` is quadratic per line (minutes before the fix).
const text = Array.from({ length: 512 }, () => "a".repeat(4095)).join("\n");
const { value, ms } = timed(() => queryBlock(text, { mode: "grep", pattern: ".*x" }));
assert.ok("error" in value, JSON.stringify(value).slice(0, 200));
assert.match((value as { error: string }).error, /time budget/);
assert.ok(ms < BUDGET_CEILING_MS, `grep took ${ms.toFixed(1)}ms`);
});
it("counts only unbounded quantifiers outside classes and escapes", () => {
const tooMany = ["a.*b.*c", "\\d+\\.\\d+", "x{2,}y+", "a.*?b.+?c"];
for (const pattern of tooMany) {
const r = queryBlock("abc", { mode: "grep", pattern });
assert.ok("error" in r, pattern);
assert.match((r as { error: string }).error, /unbounded quantifier/, pattern);
}
const text = ["l1 ERROR upstream timeout", "l2 *+ literal", "l3 {2,} braces", "l4 ok"].join(
"\n"
);
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "ERROR.*timeout" }), {
content: "l1 ERROR upstream timeout",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "[*+]+ literal" }), {
content: "l2 *+ literal",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "\\*\\+ lit.*" }), {
content: "l2 *+ literal",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "\\{2,\\} b.*s" }), {
content: "l3 {2,} braces",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "l[0-9]{1,2} (ok|ERROR)" }), {
content: "l1 ERROR upstream timeout\nl4 ok",
});
});
it("keeps grep results unchanged on an ordinary log block", () => {
const lines = Array.from(
{ length: 5_000 },
(_, i) => `2026-11-20T10:00:${String(i % 60).padStart(2, "0")}Z INFO req=${i} status=200`
);
lines[1234] = "2026-11-20T10:00:34Z ERROR req=1234 upstream timeout";
lines[4321] = "2026-11-20T10:00:01Z WARN req=4321 slow upstream";
const text = lines.join("\n");
const expected = (re: RegExp) => lines.filter((l) => re.test(l)).join("\n");
for (const pattern of ["ERROR", "(WARN|ERROR) req=", "req=12\\d\\d ", "^\\S+ WARN"]) {
assert.deepEqual(
queryBlock(text, { mode: "grep", pattern }),
{ content: expected(new RegExp(pattern)) },
pattern
);
}
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "INFO", unique: true }), {
content: lines
.filter((l) => l.includes("INFO"))
.slice(0, 1000)
.join("\n")
.concat("\n…[truncated at 1000 matches]"),
});
});
});

View File

@@ -1,459 +0,0 @@
// CodeQL #1389 (js/resource-exhaustion), remaining sites after #20824: `poll_interval_ms` and
// `timeout_ms` from the request body still reached `sleep()` and the polling deadline with no
// upper bound in the Kie (image / video / music), Runway, DashScope, Novita, MiniMax, video
// job-preset, RenderHour video / speech and UC (image / video) handlers.
//
// Each handler is driven against a fake upstream that never finishes. Timers created by the
// polling sleep are intercepted (identified by the call stack), recorded, and fired at once while
// a virtual clock advances by the requested delay, so a multi-day wait runs in milliseconds. The
// UC handlers take an injectable sleep, so there the stub records the delay directly.
import test from "node:test";
import assert from "node:assert/strict";
import { handleImageGeneration } from "../../open-sse/handlers/imageGeneration.ts";
import { handleVideoGeneration } from "../../open-sse/handlers/videoGeneration.ts";
import { handleMusicGeneration } from "../../open-sse/handlers/musicGeneration.ts";
import { handleAudioSpeech } from "../../open-sse/handlers/audioSpeech.ts";
import { handleUcImageGeneration } from "../../open-sse/handlers/imageGeneration/providers/ucImage.ts";
import {
handleUcVideoGeneration,
UC_DIRECT_VIDEO_URL,
UC_PERSONA_TEXT_TO_VIDEO_URL,
} from "../../open-sse/handlers/videoGeneration/providers/ucVideo.ts";
import { UC_PERSONA_IMAGE_URL } from "../../open-sse/handlers/imageGeneration/providers/ucImage.ts";
import { isUcClerkMintUrl } from "./helpers/ucClerkUrl.ts";
const HUGE_MS = 1e12; // ~31 years
const INTERVAL_CEILING = 30_000;
// Video jobs render for minutes; their caller interval ceiling is longer (pollBounds.ts).
const VIDEO_INTERVAL_CEILING = 120_000;
const intervalCeilingFor = (name: string) =>
/video|runway|dashscope|novita|minimax/i.test(name) ? VIDEO_INTERVAL_CEILING : INTERVAL_CEILING;
const TIMEOUT_CEILING = 600_000;
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;
const originalDateNow = Date.now;
type SleepTrace = { sleeps: number[]; elapsedMs: () => number };
/** Files whose `setTimeout` is the polling sleep of a handler under test. */
const SLEEP_FRAMES = ["utils/sleep.ts", "videoGeneration/minimaxHandler.ts"];
/** Intercepts timers created by the polling sleeps and drives a virtual clock with them. */
function installVirtualSleep(): SleepTrace {
const start = originalDateNow();
let offset = 0;
const sleeps: number[] = [];
Date.now = () => start + offset;
globalThis.setTimeout = ((fn: (...args: unknown[]) => void, ms?: number, ...args: unknown[]) => {
const stack = new Error().stack ?? "";
if (!SLEEP_FRAMES.some((frame) => stack.includes(frame))) {
return originalSetTimeout(fn, ms, ...args);
}
const delay = Number(ms) || 0;
sleeps.push(delay);
offset += delay;
return originalSetTimeout(fn, 0, ...args);
}) as typeof setTimeout;
return { sleeps, elapsedMs: () => offset };
}
/** A virtual clock driven by an injected `sleepImpl` (UC handlers). */
function virtualSleepImpl(): SleepTrace & { sleepImpl: (ms: number) => Promise<void> } {
const start = originalDateNow();
let offset = 0;
const sleeps: number[] = [];
Date.now = () => start + offset;
return {
sleeps,
elapsedMs: () => offset,
sleepImpl: async (ms: number) => {
sleeps.push(ms);
offset += ms;
},
};
}
function restore() {
globalThis.fetch = originalFetch;
globalThis.setTimeout = originalSetTimeout;
Date.now = originalDateNow;
}
test.afterEach(restore);
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
});
}
/** Kie: every create endpoint returns a task id, every record-info poll says "pending". */
const kieFetch = (async (input: string | URL) => {
const url = String(input);
if (url.includes("record-info") || url.includes("recordInfo")) {
return json({ code: 200, data: { status: "GENERATING" } });
}
return json({ code: 200, data: { taskId: "kie-task-1" } });
}) as typeof fetch;
/** RenderHour: the job is accepted and stays "running". */
const renderhourFetch = (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/v1/generations")) return json({ id: "job-1", status: "queued" }, 201);
return json({ id: "job-1", status: "running" });
}) as typeof fetch;
type Site = {
/** Default poll interval the handler uses when the caller sends none. */
defaultIntervalMs: number;
/** Default polling window; a default above the ceiling stays the effective ceiling. */
defaultTimeoutMs: number;
fetch: typeof fetch;
run: (extraBody: Record<string, unknown>) => Promise<unknown>;
};
const SITES: Record<string, Site> = {
"kie image": {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: kieFetch,
run: (extra) =>
handleImageGeneration({
body: { model: "kie/gpt4o-image", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "kie-key" },
log: null,
}),
},
"kie video": {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: kieFetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "kie/kling-3.0/video", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "kie-key" },
log: null,
}),
},
"kie music": {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: kieFetch,
run: (extra) =>
handleMusicGeneration({
body: { model: "kie/V4", prompt: "a sea shanty", ...extra },
credentials: { apiKey: "kie-key" },
log: null,
}),
},
runway: {
defaultIntervalMs: 5_000,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("_to_video")) return json({ id: "task-1" });
return json({ id: "task-1", status: "RUNNING" });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "runwayml/gen4.5", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "runway-key" },
log: null,
}),
},
dashscope: {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/video-synthesis")) {
return json({ output: { task_id: "ali-task-1", task_status: "PENDING" } });
}
return json({ output: { task_id: "ali-task-1", task_status: "RUNNING" } });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "alibaba/wan2.7-t2v-2026-06-12", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "alibaba-key", providerSpecificData: { region: "global-sg" } },
log: null,
}),
},
novita: {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.includes("/task-result")) {
return json({ task: { task_id: "n-1", status: "TASK_STATUS_PROCESSING" } });
}
return json({ task_id: "n-1" });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "novita/wan-t2v", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "novita-key" },
log: null,
}),
},
minimax: {
defaultIntervalMs: 5_000,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.includes("/query/video_generation")) {
return json({ task_id: "mm-1", status: "Processing", base_resp: { status_code: 0 } });
}
return json({ task_id: "mm-1", base_resp: { status_code: 0, status_msg: "success" } });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "minimax/MiniMax-Hailuo-02", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "minimax-key" },
log: null,
}),
},
"video job preset (agnes)": {
defaultIntervalMs: 2_000,
// No deadline here: the window is the preset's poll count (60) times the interval.
defaultTimeoutMs: 60 * INTERVAL_CEILING,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/v1/videos")) return json({ video_id: "vid-1" });
return json({ status: "processing" });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "agnes/agnes-video-v2.0", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "agnes-key" },
log: null,
}),
},
"renderhour video": {
defaultIntervalMs: 5_000,
defaultTimeoutMs: 900_000,
fetch: renderhourFetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "renderhour/kling-3.0", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "rh_key" },
log: null,
}),
},
"renderhour speech": {
defaultIntervalMs: 2_000,
defaultTimeoutMs: 180_000,
fetch: renderhourFetch,
run: (extra) =>
handleAudioSpeech({
body: { model: "renderhour/eleven-v4", input: "Hello there", ...extra },
credentials: { apiKey: "rh_key" },
}),
},
};
async function runSite(name: string, extraBody: Record<string, unknown>) {
const site = SITES[name];
globalThis.fetch = site.fetch;
const trace = installVirtualSleep();
const result = await site.run(extraBody);
restore();
return { result, trace };
}
function isFailure(result: unknown): boolean {
if (result instanceof Response) return result.status >= 400;
return (result as { success?: boolean }).success === false;
}
const HUGE_BODY = { poll_interval_ms: HUGE_MS, timeout_ms: HUGE_MS * 10 };
test("video job preset (agnes): a huge caller max_polls cannot stretch the polling window", async () => {
const { result, trace } = await runSite("video job preset (agnes)", {
poll_interval_ms: HUGE_MS,
max_polls: 1e9,
});
assert.equal((result as { success: boolean }).success, false);
assert.ok(
trace.elapsedMs() <= TIMEOUT_CEILING + VIDEO_INTERVAL_CEILING,
`polling ran for ${trace.elapsedMs()}ms of virtual time`
);
});
for (const [name, site] of Object.entries(SITES)) {
test(`${name}: a huge caller poll interval and timeout are clamped to the ceilings`, async () => {
const { result, trace } = await runSite(name, HUGE_BODY);
assert.ok(isFailure(result), "a job that never finishes must fail");
assert.ok(trace.sleeps.length > 0, "the handler polled at least once");
const longest = Math.max(...trace.sleeps);
assert.ok(
longest <= intervalCeilingFor(name),
`longest single sleep ${longest}ms > ${intervalCeilingFor(name)}`
);
const window = Math.max(TIMEOUT_CEILING, site.defaultTimeoutMs);
assert.ok(
trace.elapsedMs() <= window + intervalCeilingFor(name),
`polling ran for ${trace.elapsedMs()}ms of virtual time, above the ${window}ms window`
);
});
test(`${name}: a small caller poll interval is used as given`, async () => {
const { trace } = await runSite(name, { poll_interval_ms: 1_000, timeout_ms: 5_000 });
assert.ok(trace.sleeps.length > 0);
assert.ok(
trace.sleeps.every((ms) => ms === 1_000),
`sleeps: ${trace.sleeps.join(",")}`
);
});
test(`${name}: the default poll interval is unchanged when the caller sends none`, async () => {
const { trace } = await runSite(name, {});
assert.equal(trace.sleeps[0], site.defaultIntervalMs);
});
}
test("renderhour video: an operator default above the ceiling stays reachable", async () => {
// 900 s is the built-in RenderHour video window; a caller may ask for it but not for more.
// A huge interval too, so the unclamped code ends after one sleep instead of polling
// ~33 million times (which is the defect itself).
const { result, trace } = await runSite("renderhour video", {
poll_interval_ms: HUGE_MS,
timeout_ms: HUGE_MS,
});
assert.match(String((result as { error?: unknown }).error), /within 900 s/);
assert.ok(trace.elapsedMs() > TIMEOUT_CEILING, `elapsed ${trace.elapsedMs()}ms`);
assert.ok(
trace.elapsedMs() <= 900_000 + VIDEO_INTERVAL_CEILING,
`elapsed ${trace.elapsedMs()}ms`
);
});
// --- UC (injectable sleep) ---------------------------------------------------------------------
const UC_PERSONA_CRED = {
providerSpecificData: {
ucClientCookie: "clientcookie-abc",
ucSid: "sess_123",
ucUid: "b03dd963-d0c1-4193-99c9-f5a9d0c66b7f",
ucCookies: { __client: "clientcookie-abc", __cf_bm: "cf" },
},
};
const UC_DIRECT_CRED = { apiKey: "uai_sk_live_deadbeef" };
function fakeJwt(): string {
const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
const exp = Math.floor(originalDateNow() / 1000) + 3600 * 24 * 365 * 100;
return `${b64({ alg: "RS256" })}.${b64({ uid: "uid", exp, sub: "user_1", sid: "sess_123" })}.sig`;
}
function ucResponse(ok: boolean, status: number, body: unknown = {}): Response {
return {
ok,
status,
headers: { get: () => "" },
async json() {
return body;
},
async text() {
return typeof body === "string" ? body : JSON.stringify(body);
},
} as unknown as Response;
}
/** UC persona: mint, accept the job, keep the result URL pending forever. */
function ucPersonaFetch(submitUrl: string, resultUrl: string): typeof fetch {
const jwt = fakeJwt();
return (async (url: string) => {
if (isUcClerkMintUrl(url)) return ucResponse(true, 200, { object: "token", jwt });
if (url === submitUrl) return ucResponse(true, 200, { status: "pending", url: resultUrl });
if (url === resultUrl) return ucResponse(false, 403, "");
throw new Error(`unexpected fetch to ${url}`);
}) as unknown as typeof fetch;
}
const UC_SITES: Record<
string,
{
defaultIntervalMs: number;
run: (
extra: Record<string, unknown>,
sleepImpl: (ms: number) => Promise<void>
) => Promise<unknown>;
}
> = {
"uc image (persona)": {
defaultIntervalMs: 2_000,
run: (extra, sleepImpl) =>
handleUcImageGeneration({
model: "uc/seedream-v5",
provider: "uc",
body: { prompt: "x", ...extra },
credentials: UC_PERSONA_CRED,
fetchImpl: ucPersonaFetch(UC_PERSONA_IMAGE_URL, "https://gen.moveinwater.com/never.png"),
sleepImpl,
}),
},
"uc video (persona)": {
defaultIntervalMs: 3_000,
run: (extra, sleepImpl) =>
handleUcVideoGeneration({
model: "uc/wan-2.2-spicy",
provider: "uc",
body: { prompt: "x", ...extra },
credentials: UC_PERSONA_CRED,
fetchImpl: ucPersonaFetch(
UC_PERSONA_TEXT_TO_VIDEO_URL,
"https://videogen.moveinwater.com/never"
),
sleepImpl,
}),
},
"uc video (direct)": {
defaultIntervalMs: 3_000,
run: (extra, sleepImpl) =>
handleUcVideoGeneration({
model: "uc-direct/t2v-standard",
provider: "uc",
body: { prompt: "x", ...extra },
credentials: UC_DIRECT_CRED,
fetchImpl: (async (url: string) => {
const statusUrl = "https://api.uncensored.com/api/v1/videos/status/1";
if (url === UC_DIRECT_VIDEO_URL) {
return ucResponse(true, 200, { status: "pending", status_url: statusUrl, id: "job_1" });
}
if (url === statusUrl) return ucResponse(true, 200, { status: "processing" });
throw new Error(`unexpected fetch to ${url}`);
}) as unknown as typeof fetch,
sleepImpl,
}),
},
};
for (const [name, site] of Object.entries(UC_SITES)) {
test(`${name}: a huge caller poll interval and timeout are clamped to the ceilings`, async () => {
const clock = virtualSleepImpl();
const result = (await site.run(HUGE_BODY, clock.sleepImpl)) as { success: boolean };
restore();
assert.equal(result.success, false, "a job that never finishes must fail");
assert.ok(clock.sleeps.length > 0, "the handler polled at least once");
const longest = Math.max(...clock.sleeps);
assert.ok(
longest <= intervalCeilingFor(name),
`longest single sleep ${longest}ms > ${intervalCeilingFor(name)}`
);
assert.ok(
clock.elapsedMs() <= TIMEOUT_CEILING + intervalCeilingFor(name),
`polling ran for ${clock.elapsedMs()}ms of virtual time`
);
});
test(`${name}: the default poll interval is unchanged when the caller sends none`, async () => {
const clock = virtualSleepImpl();
await site.run({ timeout_ms: 20_000 }, clock.sleepImpl);
restore();
assert.equal(clock.sleeps[0], site.defaultIntervalMs);
});
}

View File

@@ -1,197 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
// CodeQL js/polynomial-redos #1325, #1324, #1296: three model/library id regexes backtracked in
// O(n^2) on crafted ids. Each id reaches its regex without a length cap (a client model id
// "gh/<id>", an upstream /v1/models id, a raw Context7 search item id).
//
// Two checks per function:
// - a 50k-char pathological id returns fast (measured on the exported function);
// - a truth table generated by running the pre-fix functions (git show of the base) stays the
// same, so the linear rewrites keep the exact accept/reject behavior.
const { inferGithubUnsyncedTargetFormat } =
await import("../../src/sse/services/githubResponsesFallback.ts");
const { modelDisplayName } = await import("../../src/shared/utils/modelDisplayName.ts");
const { isValidContext7LibraryId } = await import("../../open-sse/executors/context7-fetch.ts");
const PATHOLOGICAL_LENGTH = 50_000;
const BUDGET_MS = 200;
function elapsedMs(fn: () => unknown): number {
const start = performance.now();
fn();
return performance.now() - start;
}
const GITHUB_TABLE: Array<[string, string, string | null]> = [
["gh", "gpt-6", "openai-responses"],
["gh", "gpt-6.1-sol", "openai-responses"],
["gh", "GPT-7-mini", "openai-responses"],
["gh", "gpt-9", "openai-responses"],
["gh", "gpt-60", "openai-responses"],
["gh", "gpt-5.5", "openai-responses"],
["gh", "gpt-5.9-codex", "openai-responses"],
["gh", "GPT-5.5", "openai-responses"],
["gh", "gpt-5.4", null],
["gh", "gpt-5", null],
["gh", "gpt-5.10", null],
["gh", "gpt-5-codex", "openai-responses"],
["gh", "gpt-4o", null],
["gh", "gpt-4.1", null],
["gh", "gpt-10", null],
["gh", "gpt-", null],
["gh", "gpt_6", null],
["gh", "agpt-6", null],
["gh", " gpt-6", null],
["gh", "gpt-6 ", "openai-responses"],
["gh", "codex-mini", "openai-responses"],
["gh", "my-CODEX", "openai-responses"],
["gh", "codex", "openai-responses"],
["gh", "Codex-Max", "openai-responses"],
["gh", "code-x", null],
["gh", "claude-codex", null],
["gh", "gemini-codex", null],
["gh", "gpt-6-claude", null],
["gh", "o3", null],
["gh", "", null],
["gh", "gpt-6\n", null],
["gh", "gpt-6\nx", null],
["gh", "\ngpt-6", null],
["gh", "codex\r", null],
["gh", "gpt-6\u2028x", null],
["gh", "x\u2029codex", null],
["gh", "codex\t", "openai-responses"],
["gh", "gpt-6\u0085", "openai-responses"],
["gh", "gh/gpt-6", "openai-responses"],
["gh", "github/gpt-6.1", "openai-responses"],
["gh", "GH/codex", "openai-responses"],
["gh", "ghe-copilot/gpt-5.5", "openai-responses"],
["github", "gpt-6", "openai-responses"],
["ghe-copilot", "gpt-5.6-codex", "openai-responses"],
["github", "claude-opus-5-5", null],
["openai", "gpt-6", null],
["codex", "codex-mini", null],
["gh", "openai/gpt-6", null],
["gh", "x/codex", "openai-responses"],
];
const DISPLAY_TABLE: Array<[string, string]> = [
["deepseek-v4.1-flash", "DeepSeek V4.1 Flash"],
["gpt-v2", "GPT-V2"],
["gpt-V2.6", "GPT-V2.6"],
["gpt-v", "GPT V"],
["gpt-v.", "GPT V."],
["gpt-v.1", "GPT V.1"],
["gpt-v1.", "GPT-V1."],
["gpt-v1..2", "GPT-V1..2"],
["gpt-v1x", "GPT V1x"],
["gpt-vx1", "GPT Vx1"],
["gpt-v12.3.4", "GPT-V12.3.4"],
["gpt-v1-turbo", "GPT-V1 Turbo"],
["gpt-vv1", "GPT Vv1"],
["gpt-4-v1", "GPT-4 V1"],
["foo-v2.6-bar", "Foo V2.6 Bar"],
["v1", "V1"],
["v", "V"],
["mistral-v0.1", "Mistral V0.1"],
["model-V2.6", "Model V2.6"],
["gpt-6.1-sol", "GPT-6.1 Sol"],
["claude-opus-5-5", "Claude Opus 5.5"],
["glm-5.3-flash", "GLM 5.3 Flash"],
["claude-3-5-sonnet-20241022", "Claude 3.5 Sonnet"],
["qwen3.8", "Qwen 3.8"],
["cmc/deepseek/deepseek-v4.1-flash", "DeepSeek V4.1 Flash"],
["gpt-v1 x", "GPT-V1 X"],
["", ""],
];
const CONTEXT7_TABLE: Array<[string, boolean]> = [
["/vercel/next.js", true],
["/upstash/context7", true],
["/a/b", true],
["/a.b/c-d_e", true],
["/a/b/c", false],
["//a", false],
["/a//b", false],
["/a/", false],
["a/b", false],
["/a/b/", false],
["/a/b\n", false],
["/a\n/b", false],
["/\n/b", false],
["/a/\n", false],
["/a/b\r", false],
["/a/b\u2028", false],
["/a\u2029/b", false],
["/./b", false],
["/a/..", false],
["/a/b..c", false],
["/-a/b", false],
["/a/b.", false],
["/a/.b", false],
["", false],
["/", false],
["//", false],
["///", false],
["/a", false],
["/a/b c", false],
["/A1/B2", true],
["/_a/b", false],
];
test("#1325 GitHub Responses-only inference is linear on a 'codex' run ending in a line break", () => {
const id = "codex".repeat(PATHOLOGICAL_LENGTH / 5) + "\n!";
let result: unknown = "unset";
const ms = elapsedMs(() => {
result = inferGithubUnsyncedTargetFormat("gh", id);
});
assert.equal(result, undefined);
assert.ok(ms < BUDGET_MS, `took ${ms.toFixed(1)}ms`);
});
test("#1325 GitHub Responses-only inference keeps the pre-fix truth table", () => {
for (const [providerId, modelId, expected] of GITHUB_TABLE) {
assert.equal(
inferGithubUnsyncedTargetFormat(providerId, modelId) ?? null,
expected,
JSON.stringify([providerId, modelId])
);
}
});
test("#1324 model display name is linear on a long version-marker token", () => {
const id = "gpt-v" + "0".repeat(PATHOLOGICAL_LENGTH - 6) + "x";
let result = "";
const ms = elapsedMs(() => {
result = modelDisplayName(id);
});
assert.ok(result.startsWith("GPT V0"));
assert.ok(ms < BUDGET_MS, `took ${ms.toFixed(1)}ms`);
});
test("#1324 model display name keeps the pre-fix truth table", () => {
for (const [id, expected] of DISPLAY_TABLE) {
assert.equal(modelDisplayName(id), expected, JSON.stringify(id));
}
});
test("#1296 Context7 library id check is linear on a run of slashes ending in a line break", () => {
for (const id of [
"/".repeat(PATHOLOGICAL_LENGTH - 1) + "\n",
"/a".repeat(PATHOLOGICAL_LENGTH / 2 - 1) + "\n",
]) {
let result: unknown = "unset";
const ms = elapsedMs(() => {
result = isValidContext7LibraryId(id);
});
assert.equal(result, false);
assert.ok(ms < BUDGET_MS, `took ${ms.toFixed(1)}ms`);
}
});
test("#1296 Context7 library id check keeps the pre-fix truth table", () => {
for (const [id, expected] of CONTEXT7_TABLE) {
assert.equal(isValidContext7LibraryId(id), expected, JSON.stringify(id));
}
});

View File

@@ -602,30 +602,3 @@ test("syncConnectionModels logs removed synced and custom models separately", as
assert.equal(logged[0], "[ModelSync] demo (conn-1): ✓ 40 models (removed: 110 synced, 3 custom)");
assert.equal(logged[1], "[ModelSync] demo (conn-2): ✓ 40 models");
});
test("CodeQL #1407: a failed sync logs with a constant format, so a provider id cannot act as one", async () => {
const { syncConnectionModels, getModelSyncInternalBaseUrl } = await loadScheduler("log-format");
const originalFetch = globalThis.fetch;
const originalWarn = console.warn;
const warned: unknown[][] = [];
globalThis.fetch = async () => {
throw new Error("socket hang up");
};
console.warn = (...args: unknown[]) => {
warned.push(args);
};
try {
assert.equal(
await syncConnectionModels("conn-fmt-1", "evil%s%o%c", getModelSyncInternalBaseUrl()),
false
);
} finally {
globalThis.fetch = originalFetch;
console.warn = originalWarn;
}
const entry = warned.find((args) => args.includes("evil%s%o%c"));
assert.ok(entry, "the provider id is logged as a plain argument");
assert.equal(typeof entry[0], "string");
assert.ok(!String(entry[0]).includes("evil"), "the format string carries no caller data");
assert.ok(entry.includes("socket hang up"), "the error message is still logged");
});