Compare commits

..

4 Commits

Author SHA1 Message Date
diegosouzapw
3ee7ddb512 chore(cli): leave the translated CLI catalogs to the release refresh
Carrier for #18263 by @mcspanky802 (their fork does not allow maintainer edits). Since v3.8.54 a feature PR edits only bin/cli/locales/en.json; check:pr-derived-paths fails a PR that also writes the pt-BR, zh-CN and zh-TW catalogs. They go back to the base; the release refresh translates the new key, and the CLI shows it in English until then. The contributor's two commits are kept as authored.
2026-11-18 21:07:14 -03:00
diegosouzapw
4b9062d5eb Merge remote-tracking branch 'origin/release/v3.8.55' into fix/cli-limit-validation-18263 2026-11-18 20:44:01 -03:00
spanky
3f7b20170f docs(changelog): record CLI limit parsing fix 2026-10-26 14:55:58 -06:00
spanky
ad6fe67161 fix(cli): validate positive integer limits without radix corruption 2026-10-26 14:55:08 -06:00
15 changed files with 172 additions and 389 deletions

View File

@@ -4,6 +4,7 @@ import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch, getBaseUrl } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
import { parsePositiveInt } from "../utils/positiveInteger.mjs";
function fmtTs(v) {
if (!v) return "-";
@@ -97,7 +98,7 @@ export function registerBatches(program) {
batches
.command("list")
.option("--status <s>", t("batches.list.status"))
.option("--limit <n>", t("batches.list.limit"), parseInt, 50)
.option("--limit <n>", t("batches.list.limit"), parsePositiveInt, 50)
.action(async (opts, cmd) => {
const params = new URLSearchParams({ limit: String(opts.limit) });
if (opts.status) params.set("status", opts.status);

View File

@@ -4,6 +4,7 @@ import { createInterface } from "node:readline";
import { apiFetch, getBaseUrl } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
import { parsePositiveInt } from "../utils/positiveInteger.mjs";
function fmtTs(v) {
if (!v) return "-";
@@ -49,7 +50,7 @@ export function registerFiles(program) {
files
.command("list")
.option("--purpose <p>", t("files.list.purpose"))
.option("--limit <n>", t("files.list.limit"), parseInt, 100)
.option("--limit <n>", t("files.list.limit"), parsePositiveInt, 100)
.action(async (opts, cmd) => {
const params = new URLSearchParams({ limit: String(opts.limit) });
if (opts.purpose) params.set("purpose", opts.purpose);

View File

@@ -13,6 +13,7 @@ import {
import { encryptCredential } from "../encryption.mjs";
import { openOmniRouteDb } from "../sqlite.mjs";
import { t } from "../i18n.mjs";
import { parsePositiveInt } from "../utils/positiveInteger.mjs";
import { registerProviderCrud } from "./provider-crud.mjs";
function publicConnection(connection) {
@@ -824,7 +825,7 @@ export function extendProvidersMetrics(providers) {
.option("--period <p>", t("providers.metrics.period"), "24h")
.option("--metric <m>", t("providers.metrics.metric"))
.option("--sort-by <field>", t("providers.metrics.sort"))
.option("--limit <n>", t("providers.metrics.limit"), parseInt, 50)
.option("--limit <n>", t("providers.metrics.limit"), parsePositiveInt, 50)
.option("--watch", t("providers.metrics.watch"))
.option("--compare <list>", t("providers.metrics.compare"))
.action(runProvidersMetrics);

View File

@@ -12,7 +12,8 @@
"dryRun": "[dry-run] would {action}",
"cancelled": "Cancelled.",
"jsonOpt": "Output as JSON",
"yesOpt": "Skip confirmation prompt"
"yesOpt": "Skip confirmation prompt",
"positiveIntegerRequired": "Limit must be a positive integer."
},
"setup": {
"title": "OmniRoute Setup",

View File

@@ -0,0 +1,18 @@
import { z } from "zod";
import { InvalidArgumentError } from "commander";
import { t } from "../i18n.mjs";
const positiveIntSchema = z
.string()
.trim()
.regex(/^[0-9]+$/)
.transform(Number)
.pipe(z.number().int().positive().max(Number.MAX_SAFE_INTEGER));
export function parsePositiveInt(value) {
const result = positiveIntSchema.safeParse(String(value ?? ""));
if (!result.success) {
throw new InvalidArgumentError(t("common.positiveIntegerRequired"));
}
return result.data;
}

View File

@@ -0,0 +1 @@
- **fix(cli):** Parse positive safe integer `--limit` values correctly for provider metrics, batch lists, and file lists instead of passing Commander's previous value to `parseInt` as a radix ([#18263](https://github.com/cheaper-inference/OmniRoute/pull/18263)) — thanks @mcspanky802.

View File

@@ -1 +0,0 @@
- **fix(security):** plugin hooks (`onRequest`/`onResponse`/`onError`) no longer receive the client's `authorization`, `x-api-key` or `proxy-authorization` headers or the API key value; the Plugin SDK and marketplace docs now state that plugins run as ordinary Node.js processes with the OmniRoute user's privileges (`requires.permissions` only selects environment variables), and the plugins page shows a warning to that effect ([#20566](https://github.com/cheaper-inference/OmniRoute/pull/20566))

View File

@@ -50,9 +50,8 @@ Dashboard (/dashboard/plugins)
`plugin.json`.
- **Scanner** — `src/lib/plugins/scanner.ts`: discovers plugins on disk under
the plugin directory.
- **Loader** — `src/lib/plugins/loader.ts`: spawns each plugin in a separate
Node.js child process and brokers hook calls over IPC. The child is not a
sandbox (see "Plugin execution isolation" below).
- **Loader** — `src/lib/plugins/loader.ts`: spawns each plugin in an isolated
child process and brokers hook calls over IPC.
## Marketplace Catalog
@@ -243,14 +242,6 @@ silently falls back to the built-in seed registry and logs a warning.
### Plugin execution isolation
> **Plugins are not sandboxed.** The child is an ordinary Node.js process running
> as the OmniRoute user, with no VM context and no Node.js permission flags, so
> plugin code can read and write any file that user can, run programs and reach
> the network. `requires.permissions` only decides which environment variables
> the child receives; the other permissions are not enforced. Install only
> plugins you trust. The process boundary below contains crashes and hangs; it
> is not a security boundary.
- **Process isolation** — `loadPlugin()` (`src/lib/plugins/loader.ts`) spawns
each plugin in a separate Node.js child process and communicates over IPC.
Hook calls have a timeout with `SIGTERM` → `SIGKILL` escalation.
@@ -266,12 +257,8 @@ silently falls back to the built-in seed registry and logs a warning.
- **Optional integrity pin** — a manifest may declare an `integrity`
(`sha256-<base64>`, SRI format) field. When present, the loader verifies the
entry file hash at load time and refuses to activate on mismatch. It is
opt-in tamper-detection, **not** a security boundary: it does not limit what
a loaded plugin can do.
- **No client credentials in hooks** — the context passed to `onRequest`,
`onResponse` and `onError` has the `authorization`, `x-api-key`,
`proxy-authorization` and `cookie` headers removed, and the API key record carries no key
value (`redactPluginContext()` in `src/lib/plugins/hooks.ts`).
opt-in tamper-detection, **not** a security boundary — loopback-only routing
and the permission model are the real boundaries.
## Manifest (`plugin.json`)
@@ -295,9 +282,7 @@ Validated by `PluginManifestSchema` (`src/lib/plugins/manifest.ts`):
| `integrity` | string? | Optional `sha256-<base64>` entry-file pin |
Permissions are drawn from the enum
`network` / `file-read` / `file-write` / `env` / `exec`. Only `env` has a
runtime effect (a slightly larger environment-variable allowlist for the
child); the others are declarations and are not enforced.
`network` / `file-read` / `file-write` / `env` / `exec`.
## Lifecycle Flow
@@ -366,9 +351,6 @@ The dashboard page at `/dashboard/plugins`
- **Marketplace** — shows the catalog from `GET /api/plugins/marketplace` with a
field to set the custom registry URL.
The page always shows a warning that plugins run with the full privileges of
the OmniRoute process.
A per-plugin config page lives at `/dashboard/plugins/[name]/config`
(`src/app/(dashboard)/dashboard/plugins/[name]/config/page.tsx`).

View File

@@ -48,8 +48,8 @@ Block the request and optionally return a custom response.
```ts
onRequest: (ctx) => {
if (!ctx.headers?.["x-client-team"]) {
return blockRequest({ error: "Missing x-client-team header", status: 400 });
if (!ctx.headers["authorization"]) {
return blockRequest({ error: "Unauthorized", status: 401 });
}
};
```
@@ -76,22 +76,15 @@ onRequest: (ctx) => {
## Plugin Context (`PluginContext`)
| Field | Type | Description |
| ------------ | ------------------------- | --------------------------- |
| `requestId` | `string` | Unique request identifier |
| `model` | `string` | Requested model name |
| `provider` | `string` | Target provider ID |
| `body` | `Record<string, unknown>` | Request body |
| `headers` | `Record<string, string>` | Request headers (see note) |
| `metadata` | `Record<string, unknown>` | Mutable metadata |
| `timestamp` | `number` | Request timestamp |
| `apiKeyInfo` | `object` (optional) | API key metadata (see note) |
The context never carries the client's credentials: the `authorization`, `x-api-key`,
`proxy-authorization` and `cookie` headers are removed (any casing), and `apiKeyInfo` keeps the key's
metadata (such as `id`, `name` and `scopes`) but not the key value or its fingerprint
(`redactPluginContext()` in `src/lib/plugins/hooks.ts`). This applies to `onRequest`,
`onResponse` and `onError`.
| Field | Type | Description |
| ----------- | ------------------------- | ------------------------- |
| `requestId` | `string` | Unique request identifier |
| `model` | `string` | Requested model name |
| `provider` | `string` | Target provider ID |
| `body` | `Record<string, unknown>` | Request body |
| `headers` | `Record<string, string>` | Request headers |
| `metadata` | `Record<string, unknown>` | Mutable metadata |
| `timestamp` | `number` | Request timestamp |
## Manifest (`plugin.json`)
@@ -146,22 +139,17 @@ Or as simple booleans (default priority 100):
## Permission System
Plugins are **not sandboxed**. Each active plugin runs as a separate, ordinary Node.js child
process (`loadPlugin()` in `src/lib/plugins/loader.ts`) under the same operating-system user as
OmniRoute, with no VM context and no Node.js permission flags. Plugin code can use `node:fs`,
`node:child_process`, `fetch` and every other Node.js API: it can read and write any file the
OmniRoute user can (including the data directory), run programs and reach the network.
Plugins run in a sandboxed VM context. Access to external resources requires explicit permissions:
The manifest's `requires.permissions` accepts `network`, `file-read`, `file-write`, `env` and
`exec`, but today only `env` has an effect at runtime:
| Permission | Grants |
| ------------ | ------------------------------------------------------------ |
| `network` | `fetch`, `AbortController`, `Headers`, `Request`, `Response` |
| `file-read` | `fs.readFile`, `fs.readdir`, `fs.stat` |
| `file-write` | `fs.writeFile`, `fs.mkdir`, `fs.rm` |
| `env` | Read-only `process.env` proxy |
| `exec` | `child_process.exec`, `child_process.execSync` |
| Permission | Effect today |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `env` | The plugin process also receives `PORT`, `HOSTNAME`, `TZ` and `TMPDIR`. Without it, it receives only `PATH`, `HOME`, `USER`, `LANG`, `LC_ALL`, `NODE_ENV`, `PLUGIN_ENTRY` and `PLUGIN_NAME` (plus `SystemRoot` and `windir` on Windows). |
| `network`, `file-read`, `file-write`, `exec` | None. They are declarations only: nothing is blocked when they are missing. |
Installing a plugin is like installing any other program on the host. Install only plugins whose
source you trust.
Without a permission, the corresponding globals are simply not available in the sandbox.
## Config Schema
@@ -229,7 +217,7 @@ export default definePlugin({
name: "rate-limiter",
priority: 10,
onRequest: async (ctx) => {
const key = ctx.apiKeyInfo?.id || "anonymous";
const key = ctx.headers["x-api-key"] || "anonymous";
const now = Date.now();
const window = 60000; // 1 minute
const maxRequests = 100;

View File

@@ -2,10 +2,8 @@
import { useState, useEffect, useCallback } from "react";
import { PageHeader } from "@omniroute/ui-kit/page-header";
import { Alert } from "@omniroute/ui-kit/alert";
import { Card, Button, EmptyState } from "@/shared/components";
import Badge from "@/shared/components/Badge";
import Icon from "@/shared/components/Icon";
import { useNotificationStore } from "@/store/notificationStore";
import { useConfirmDialog } from "@/shared/hooks/useConfirmDialog";
import { useTranslations } from "next-intl";
@@ -114,13 +112,6 @@ export default function PluginsPage() {
</Button>
}
/>
<Alert
variant="warning"
dismissible={false}
icon={<Icon name="warning" size={18} />}
title={t("privilegesWarningTitle")}
description={t("privilegesWarningBody")}
/>
{plugins.length === 0 ? (
<EmptyState title={t("noPlugins")} description={t("noPluginsDescription")} />
) : (

View File

@@ -13434,8 +13434,6 @@
"scanForPlugins": "Scan for Plugins",
"noPlugins": "No plugins installed",
"noPluginsDescription": "Place plugin directories in ~/.omniroute/plugins/ and click Scan.",
"privilegesWarningTitle": "Plugins run with full privileges",
"privilegesWarningBody": "A plugin runs as a regular Node.js process with the same access as OmniRoute: it can read files, run programs and use the network, whatever permissions its manifest declares. Install only plugins you trust.",
"activate": "Activate",
"deactivate": "Deactivate",
"uninstall": "Uninstall",

View File

@@ -231,55 +231,11 @@ export interface PluginContext {
/** Client request headers available at the call site. Optional — not all callers
* have access to headers (e.g. internal triggers, retries). Exposed so
* observability/trace-export plugins can read request-scoped context sent by the
* client (trace ids, correlation ids, session markers). Credential headers are removed
* before a hook sees the context (see redactPluginContext). */
* client (trace ids, correlation ids, session markers). */
headers?: Record<string, string | string[] | undefined>;
metadata: Record<string, unknown>;
}
// ── Credential redaction ──
// Plugins are third-party code running as an ordinary Node process with the OmniRoute
// user's privileges, so anything in the hook context is readable by them. The client's
// credentials never go there: the request pipeline keeps its own (unmodified) copy.
const CREDENTIAL_HEADER_NAMES: ReadonlySet<string> = new Set([
"authorization",
"x-api-key",
"proxy-authorization",
// The dashboard session token travels in a cookie.
"cookie",
]);
/** API key record fields that carry the key itself or a fingerprint of it. */
const API_KEY_SECRET_FIELDS: ReadonlySet<string> = new Set(["key", "apiKey", "rawKey", "keyHash"]);
function omitFields(
record: Record<string, unknown>,
shouldOmit: (field: string) => boolean
): Record<string, unknown> {
return Object.fromEntries(Object.entries(record).filter(([field]) => !shouldOmit(field)));
}
/**
* Copy of a hook context without the client's credentials: drops the `authorization`,
* `x-api-key`, `proxy-authorization` and `cookie` headers (any casing) and the key value/fingerprint
* from the API key record. The input is never mutated.
*/
function redactPluginContext<T extends PluginContext>(ctx: T): T {
const redacted: T = { ...ctx };
if (ctx.headers && typeof ctx.headers === "object") {
redacted.headers = omitFields(ctx.headers, (name) =>
CREDENTIAL_HEADER_NAMES.has(name.toLowerCase())
) as PluginContext["headers"];
}
if (ctx.apiKeyInfo && typeof ctx.apiKeyInfo === "object") {
redacted.apiKeyInfo = omitFields(ctx.apiKeyInfo as Record<string, unknown>, (field) =>
API_KEY_SECRET_FIELDS.has(field)
);
}
return redacted;
}
export interface PluginResult {
blocked?: boolean;
response?: unknown;
@@ -374,7 +330,7 @@ export async function runOnRequest(ctx: PluginContext): Promise<PluginResult> {
// When no plugins exist, avoid lazy loading arbitrary plugin code in this request.
if (!canInitializeRequestPlugins()) return {};
await ensurePluginsLoaded();
return emitHookBlocking("onRequest", redactPluginContext(ctx));
return emitHookBlocking("onRequest", ctx);
}
/**
@@ -383,11 +339,10 @@ export async function runOnRequest(ctx: PluginContext): Promise<PluginResult> {
export async function runOnResponse(ctx: PluginContext, response: unknown): Promise<unknown> {
let currentResponse = response;
const list = hooks.get("onResponse") || [];
const hookCtx = redactPluginContext(ctx);
for (const reg of list) {
assertPluginHandlerAllowed();
try {
const result = await reg.handler({ ...hookCtx, response: currentResponse });
const result = await reg.handler({ ...ctx, response: currentResponse });
if (
result !== undefined &&
result !== null &&
@@ -408,7 +363,7 @@ export async function runOnResponse(ctx: PluginContext, response: unknown): Prom
* Run onError hooks — fire-and-forget notification.
*/
export async function runOnError(ctx: PluginContext, error: Error): Promise<void> {
await emitHook("onError", { ...redactPluginContext(ctx), error });
await emitHook("onError", { ...ctx, error });
}
/**

View File

@@ -0,0 +1,115 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { Command } from "commander";
import { registerBatches } from "../../bin/cli/commands/batches.mjs";
import { registerFiles } from "../../bin/cli/commands/files.mjs";
import { extendProvidersMetrics } from "../../bin/cli/commands/providers.mjs";
function findSubcommand(root: Command, path: string[]): Command {
let current: Command | undefined = root;
for (const segment of path) {
current = current?.commands.find((c) => c.name() === segment);
assert.ok(current, `Expected subcommand "${segment}" to exist`);
}
return current;
}
function buildProgramWithCapture(path: string[]) {
const program = new Command();
program.exitOverride();
program.configureOutput({
writeOut: () => {},
writeErr: () => {},
});
const providers = program.command("providers");
extendProvidersMetrics(providers);
registerBatches(program);
registerFiles(program);
const target = findSubcommand(program, path);
let capturedOpts: Record<string, unknown> | null = null;
target.action((opts: Record<string, unknown>) => {
capturedOpts = opts;
});
return {
parse: async (extraArgs: string[]) => {
capturedOpts = null;
await program.parseAsync(["node", "omniroute", ...path, ...extraArgs]);
return capturedOpts;
},
};
}
const TARGET_COMMANDS: Array<{
label: string;
path: string[];
defaultLimit: number;
}> = [
{ label: "providers metrics", path: ["providers", "metrics"], defaultLimit: 50 },
{ label: "batches list", path: ["batches", "list"], defaultLimit: 50 },
{ label: "files list", path: ["files", "list"], defaultLimit: 100 },
];
describe("CLI --limit positive integer parsing regression", () => {
for (const { label, path, defaultLimit } of TARGET_COMMANDS) {
describe(label, () => {
it(`uses default limit (${defaultLimit}) when --limit is omitted`, async () => {
const { parse } = buildProgramWithCapture(path);
const opts = await parse([]);
assert.ok(opts);
assert.equal(opts.limit, defaultLimit);
});
it("parses explicit valid positive integer --limit without radix corruption", async () => {
const { parse } = buildProgramWithCapture(path);
for (const [raw, expected] of [
["1", 1],
["10", 10],
["25", 25],
["250", 250],
[String(Number.MAX_SAFE_INTEGER), Number.MAX_SAFE_INTEGER],
] as const) {
const opts = await parse(["--limit", raw]);
assert.ok(opts);
assert.equal(opts.limit, expected);
assert.equal(Number.isNaN(opts.limit), false);
}
});
it("rejects zero, negative, malformed, and unsafe integer --limit values", async () => {
const { parse } = buildProgramWithCapture(path);
const invalidValues = [
"0",
"00",
"-1",
"-50",
"1.5",
"10abc",
"abc",
"",
" ",
"NaN",
"Infinity",
"1e5",
"0x10",
"9007199254740992",
"99999999999999999999",
];
for (const bad of invalidValues) {
await assert.rejects(
() => parse(["--limit", bad]),
(err: unknown) => {
assert.ok(err instanceof Error);
assert.match(err.message, /positive integer/i);
return true;
},
`Expected "${bad}" to be rejected for ${label}`
);
}
});
});
}
});

View File

@@ -1,176 +0,0 @@
// Plugin hooks must not receive the client's credentials. A plugin is third-party code
// running as a plain Node child process, so whatever the hook context carries is fully
// readable by it. The request headers handed to onRequest/onResponse/onError must not
// include `authorization`, `x-api-key`, `proxy-authorization` or `cookie` (any casing), and the
// API key record must not carry the key itself — only its id/name/scopes-style metadata.
import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const { registerHook, unregisterHooks, runOnResponse, runOnError } =
await import("../../src/lib/plugins/hooks.ts");
const { runPluginOnRequestHook } =
await import("../../open-sse/handlers/chatCore/pluginOnRequest.ts");
const { loadPlugin } = await import("../../src/lib/plugins/loader.ts");
const SECRET = "sk-client-secret-value-0001";
const CREDENTIAL_HEADERS = ["authorization", "x-api-key", "proxy-authorization", "cookie"];
function clientHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${SECRET}`,
"X-Api-Key": SECRET,
"proxy-authorization": `Basic ${SECRET}`,
Cookie: `auth_token=${SECRET}; theme=dark`,
"x-trace-id": "trace-123",
"content-type": "application/json",
};
}
function apiKeyRecord() {
return {
id: "key-id-1",
name: "ci key",
scopes: ["chat"],
noLog: false,
key: SECRET,
keyHash: "fingerprint-of-the-key",
};
}
function assertNoCredentials(seen: unknown) {
const ctx = seen as { headers?: Record<string, unknown>; apiKeyInfo?: Record<string, unknown> };
assert.ok(ctx, "expected the hook to run");
const headerNames = Object.keys(ctx.headers ?? {}).map((h) => h.toLowerCase());
for (const name of CREDENTIAL_HEADERS) {
assert.equal(headerNames.includes(name), false, `hook received the ${name} header`);
}
assert.equal(ctx.headers?.["x-trace-id"], "trace-123", "non-credential headers stay visible");
assert.equal(ctx.apiKeyInfo?.id, "key-id-1");
assert.equal(ctx.apiKeyInfo?.name, "ci key");
assert.deepEqual(ctx.apiKeyInfo?.scopes, ["chat"]);
assert.equal("key" in (ctx.apiKeyInfo ?? {}), false, "hook received the API key value");
assert.equal("keyHash" in (ctx.apiKeyInfo ?? {}), false, "hook received the key fingerprint");
assert.equal(JSON.stringify(seen).includes(SECRET), false, "the client secret reached the hook");
}
const registered: string[] = [];
afterEach(() => {
for (const name of registered.splice(0)) unregisterHooks(name);
});
test("a real plugin process's onRequest hook never sees the client's credentials", async (t) => {
const pluginDir = await mkdtemp(join(tmpdir(), "omniroute-plugin-cred-"));
const entryPoint = join(pluginDir, "index.mjs");
await writeFile(
entryPoint,
`export async function onRequest(ctx) {
return { body: { seen: { headers: ctx.headers ?? null, apiKeyInfo: ctx.apiKeyInfo ?? null } } };
}
`,
"utf-8"
);
const loaded = await loadPlugin(entryPoint, {
name: "credential-probe",
version: "1.0.0",
license: "MIT",
main: "index.mjs",
source: "local",
tags: [],
requires: { permissions: [] },
hooks: { onRequest: true, onResponse: false, onError: false },
skills: [],
enabledByDefault: false,
configSchema: {},
} as unknown as Parameters<typeof loadPlugin>[1]);
t.after(async () => {
loaded.cleanup();
await rm(pluginDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
registerHook("onRequest", "credential-probe", loaded.plugin.onRequest as never);
registered.push("credential-probe");
const headers = clientHeaders();
const gate = await runPluginOnRequestHook({
requestId: "req-cred-1",
body: { messages: [{ role: "user", content: "hi" }] },
model: "gpt-x",
provider: "openai",
apiKeyInfo: apiKeyRecord(),
headers,
});
assert.equal(gate.blocked, false);
if (gate.blocked) return;
const body = gate.body as { seen?: unknown } | undefined;
assertNoCredentials(body?.seen);
// The caller's own header record is not mutated: the request pipeline still needs it.
assert.equal(headers.Authorization, `Bearer ${SECRET}`);
assert.equal(headers["X-Api-Key"], SECRET);
});
test("onResponse hooks never see the client's credentials", async () => {
let seen: unknown;
registerHook("onResponse", "credential-probe-response", async (ctx: unknown) => {
seen = ctx;
});
registered.push("credential-probe-response");
await runOnResponse(
{
requestId: "req-cred-2",
body: {},
model: "gpt-x",
provider: "openai",
apiKeyInfo: apiKeyRecord(),
headers: clientHeaders(),
metadata: {},
},
{ status: 200 }
);
assertNoCredentials(seen);
});
test("onError hooks never see the client's credentials", async () => {
let seen: unknown;
registerHook("onError", "credential-probe-error", async (ctx: unknown) => {
seen = ctx;
});
registered.push("credential-probe-error");
await runOnError(
{
requestId: "req-cred-3",
body: {},
model: "gpt-x",
provider: "openai",
apiKeyInfo: apiKeyRecord(),
headers: clientHeaders(),
metadata: {},
},
new Error("upstream failed")
);
assertNoCredentials(seen);
});
test("a context without headers or API key record still reaches the hook unchanged", async () => {
let seen: Record<string, unknown> | undefined;
registerHook("onError", "credential-probe-empty", async (ctx: unknown) => {
seen = ctx as Record<string, unknown>;
});
registered.push("credential-probe-empty");
await runOnError(
{ requestId: "req-cred-4", body: {}, model: "m", provider: "p", metadata: {} },
new Error("x")
);
assert.ok(seen);
assert.equal(seen!.headers, undefined);
assert.equal(seen!.apiKeyInfo, undefined);
assert.equal(seen!.requestId, "req-cred-4");
});

View File

@@ -1,92 +0,0 @@
// @vitest-environment jsdom
/**
* The plugins page must tell the operator that plugins run with the full privileges of the
* OmniRoute process. The manifest's `requires.permissions` is not a sandbox (it only selects
* which environment variables the plugin process receives), so the notice is shown whether
* or not any plugin is installed and cannot be dismissed.
*/
import React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
usePathname: () => "/dashboard/plugins",
}));
vi.mock("@/store/notificationStore", () => ({
useNotificationStore: () => ({ addNotification: vi.fn() }),
}));
let pluginList: unknown[] = [];
vi.stubGlobal(
"fetch",
vi
.fn()
.mockImplementation(() =>
Promise.resolve({ ok: true, json: async () => ({ plugins: pluginList }) })
)
);
import PluginsPage from "../../../src/app/(dashboard)/dashboard/plugins/page";
describe("plugins page — full-privileges notice", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => {
root.unmount();
});
document.body.removeChild(container);
pluginList = [];
});
async function renderPage() {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={{ plugins: messages.plugins }}>
<PluginsPage />
</NextIntlClientProvider>
);
});
}
function notice(): HTMLElement | null {
return container.querySelector('[data-slot="alert"][data-variant="warning"]');
}
it("shows the notice when no plugin is installed", async () => {
await renderPage();
const alert = notice();
expect(alert).not.toBeNull();
expect(alert!.textContent).toContain(messages.plugins.privilegesWarningTitle);
expect(alert!.textContent).toContain(messages.plugins.privilegesWarningBody);
expect(alert!.querySelector("button.ci-alert__dismiss")).toBeNull();
});
it("shows the notice alongside installed plugins", async () => {
pluginList = [
{ name: "demo", version: "1.0.0", status: "active", enabled: true, hooks: ["onRequest"] },
];
await renderPage();
expect(container.textContent).toContain("demo");
expect(notice()?.textContent).toContain(messages.plugins.privilegesWarningTitle);
});
it("the notice says permissions are not a sandbox and to trust the plugin", () => {
const body = messages.plugins.privilegesWarningBody;
expect(body).toMatch(/whatever permissions its manifest declares/);
expect(body).toMatch(/only plugins you trust/);
});
});