Compare commits

..

2 Commits

Author SHA1 Message Date
diegosouzapw
ba4384c8ec chore(changelog): name the benchmark-range fragment after its PR 2026-11-18 23:58:16 -03:00
diegosouzapw
0bc92ffc16 fix(security): opt-in block of 198.18.0.0/15 in the strict outbound guard
isPrivateHost() treats the RFC 2544 benchmarking range as public, on purpose: fake-IP proxies (Clash, Mihomo, Surge TUN) answer every name with an address in it (#15039). OMNIROUTE_BLOCK_BENCHMARK_RANGE=true now lets an operator without such a proxy treat the whole /15 as private in every spelling the guard reads. Default unchanged.
2026-11-18 23:54:38 -03:00
17 changed files with 215 additions and 445 deletions

View File

@@ -662,6 +662,15 @@ ALLOW_API_KEY_REVEAL=false
# Used by: src/shared/network/outboundUrlGuardPolicy.ts
# OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS=false
# Treat 198.18.0.0/15 (the RFC 2544 benchmarking range) as private in the strict public-only
# checks (caller-supplied image/media URLs, public-only DNS and connect-time guards). Off by
# default because fake-IP proxies (Clash, Mihomo, Surge in TUN mode) answer every name with an
# address in that range; turn it on only when no such proxy is in use and the range holds
# internal services.
# Used by: src/shared/network/privateHost.ts
# Default: false
# OMNIROUTE_BLOCK_BENCHMARK_RANGE=true
# Legacy alias; its dashboard toggle (a DB override) is read before this environment value.
# "false", "0", "no", or "off" in either turns the host checks off the way
# OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS=true does, even when that flag's dashboard toggle

View File

@@ -450,13 +450,12 @@ jobs:
echo "✅ Published omniroute@$VERSION (dist-tag=$TAG) via Trusted Publishing"
- name: Publish to npm (staged — owner approves with 2FA)
# Only on an explicit request now: Trusted Publishing above is the default. Staging
# also goes through OIDC (Trusted Publishers allow `npm stage publish`); the approve
# step still needs the owner's 2FA.
# Only on an explicit request now: Trusted Publishing below is the default.
if: github.event_name == 'workflow_dispatch' && inputs.publish_mode == 'staged'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
@@ -480,9 +479,6 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
echo "✅ Staged omniroute@$VERSION (dist-tag=$TAG) — awaiting owner 'npm stage approve'"
# The one step still on a token: for when Trusted Publishing itself is broken. npm caps
# write tokens at 90 days, so mint a fresh granular token (publish on omniroute, 2FA
# bypass) and set NPM_TOKEN right before dispatching publish_mode=direct.
- name: Publish to npm (DIRECT — emergency fallback)
if: github.event_name == 'workflow_dispatch' && inputs.publish_mode == 'direct'
env:
@@ -602,13 +598,10 @@ jobs:
working-directory: "@omniroute/opencode-plugin"
run: npm test
# Trusted Publishing (OIDC), like the main package: no NODE_AUTH_TOKEN. npm >= 11.5
# detects the job's id-token itself. The Trusted Publisher of this package
# (cheaper-inference/OmniRoute, npm-publish.yml, no environment, "npm publish" allowed)
# was set up on 2026-11-18, after the long-lived NPM_TOKEN expired and v3.8.54's
# plugin publishes answered E404.
- name: Publish @omniroute/opencode-plugin to npm
working-directory: "@omniroute/opencode-plugin"
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
@@ -728,13 +721,10 @@ jobs:
working-directory: "@omniroute/opencode-plugin-v2"
run: npm test
# Trusted Publishing (OIDC), like the main package: no NODE_AUTH_TOKEN. npm >= 11.5
# detects the job's id-token itself. The Trusted Publisher of this package
# (cheaper-inference/OmniRoute, npm-publish.yml, no environment, "npm publish" allowed)
# was set up on 2026-11-18, after the long-lived NPM_TOKEN expired and v3.8.54's
# plugin publishes answered E404.
- name: Publish @omniroute/opencode-plugin-v2 to npm
working-directory: "@omniroute/opencode-plugin-v2"
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")

View File

@@ -1 +0,0 @@
- **fix(security):** `POST /api/plugins` now installs only from the `plugin-sources` directory next to the plugin root (canonicalized with `realpath`, symlinks escaping it refused, fail closed) and requires the management credential even when login is disabled

View File

@@ -1 +0,0 @@
- **fix(ci):** the OpenCode plugins and the staged release mode publish to npm through Trusted Publishing (OIDC) only; the expired long-lived `NPM_TOKEN` is left solely on the DIRECT emergency fallback ([#20489](https://github.com/cheaper-inference/OmniRoute/pull/20489))

View File

@@ -0,0 +1 @@
- **fix(security):** `OMNIROUTE_BLOCK_BENCHMARK_RANGE=true` makes the strict public-only outbound checks treat 198.18.0.0/15 (RFC 2544 benchmarking) as private; the range stays public by default for fake-IP proxies

View File

@@ -94,7 +94,7 @@ loopback-only — `/api/plugins` and `/api/plugins/` are listed in
| Endpoint | Method | Description |
| -------------------------------- | ------ | --------------------------------------------------- |
| `/api/plugins` | GET | List installed plugins (optional `?status=` filter) |
| `/api/plugins` | POST | Install a plugin from the plugin sources directory |
| `/api/plugins` | POST | Install a plugin from an absolute local path |
| `/api/plugins/scan` | POST | Scan the plugin directory and register new plugins |
| `/api/plugins/marketplace` | GET | List marketplace catalog entries |
| `/api/plugins/[name]` | GET | Get installed plugin details |
@@ -123,20 +123,10 @@ curl -X POST http://localhost:20128/api/plugins \
-d '{ "path": "/absolute/path/to/my-plugin" }'
```
The `path` must be an **absolute** path to a directory **inside the plugin
sources directory**: `plugin-sources` next to the plugin root, so
`~/.omniroute/plugin-sources/` by default, or `<parent of OMNIROUTE_PLUGINS_DIR>/plugin-sources/`
when that variable is set (`getPluginSourcesDir()` in
`src/lib/plugins/installSource.ts`). Copy or clone the plugin there first. The
install is refused with `400` when the path contains `..` or a null byte, lies
outside that directory, resolves outside it through a symlink, contains a symlink
whose target is outside it, or when the directory does not exist. The source
directory must contain a valid `plugin.json` (or be a parent of one). On success
the response is `201` with the installed plugin row.
Unlike the other plugin routes, this one requires the management credential (a
dashboard session or a manage-scoped API key) even when login is disabled
(`requireLogin=false`): installing code is never an anonymous action.
The `path` must be **absolute** and may not contain `..` traversal segments or
null bytes (enforced by Zod). The source directory must contain a valid
`plugin.json` (or be a parent of one). On success the response is `201` with the
installed plugin row.
### Browse the marketplace
@@ -258,10 +248,6 @@ silently falls back to the built-in seed registry and logs a warning.
- **Env allowlist** — the child receives only an allowlisted set of environment
variables; the broader set is only granted when the manifest requests the
`env` permission.
- **Install source containment** — `POST /api/plugins` only reads from the plugin
sources directory (see "Install from a local path"): the path is canonicalized
with `realpath`, must stay strictly inside that directory, and a source tree
carrying a symlink that escapes it is refused before anything is copied.
- **Path containment** — install/upgrade/uninstall assert that the plugin
directory and `manifest.main` resolve **within** the managed plugin root
before any copy or recursive delete (guards against tampered DB paths and

View File

@@ -254,6 +254,7 @@ OmniRoute uses **SQLite** (via `better-sqlite3`) for all persistence. These vari
| `OUTBOUND_SSRF_GUARD_ENABLED` | `true` | `src/shared/network/outboundUrlGuardPolicy.ts` | Legacy alias. Its dashboard toggle (a DB override) is read before this environment value; `false`, `0`, `no`, or `off` in either turns the host checks off the way `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS=true` does, even when that flag's dashboard toggle is saved off; other values leave the guard to the two flags below. |
| `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS` | `false` | `src/shared/network/outboundUrlGuardPolicy.ts` | Turns off the outbound URL guard's host checks, cloud-metadata block included (all of 169.254.0.0/16, metadata.google.internal), on the provider paths that follow the guard mode: URL validation, model discovery, provider-node base URLs (including remote rerank nodes), and the proxy-fallback test, among other provider-adjacent outbound paths such as remote image/media fetch. It also allows private webhook targets, except cloud-metadata/link-local endpoints, which stay blocked even with this flag on. Chat requests dispatched through `BaseExecutor.execute()` keep their cloud-metadata check. Local providers work with the defaults: `OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS` (default `true`) already allows local and LAN URLs on the validation, discovery, and provider-node paths; the proxy-fallback test and private webhook targets consult only this flag and block local/LAN hosts while it is off. Overrides `OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS=false`. A value saved from the dashboard toggle takes precedence over this variable. |
| `OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS` | `true` | `src/shared/network/outboundUrlGuardPolicy.ts` | Allow provider URLs on local/private addresses (127.0.0.1, localhost, LAN, private ranges) for provider validation, model discovery, chat, and the other provider-adjacent outbound paths the guard mode governs. **Default `true`** (local-first): the guard then blocks cloud-metadata endpoints — all of 169.254.0.0/16 plus the known metadata hostnames (metadata.google.internal, metadata.goog, Alibaba/Azure/Oracle IMDS, fd00:ec2::254). Set `false` for public-only mode, which blocks private and loopback hosts too. The guard checks the hostname or IP literal as written, before any DNS lookup; in public-only mode the safe-fetch wrapper additionally resolves the hostname and refuses any private answer. `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS=true` turns these checks off on the paths its row lists. Built-in local providers, such as LM Studio, Ollama, vLLM, Llamafile, and Triton, skip all host checks for key validation and chat. A value saved from the dashboard toggle takes precedence over this variable. (#5066) |
| `OMNIROUTE_BLOCK_BENCHMARK_RANGE` | `false` | `src/shared/network/privateHost.ts` | Treat 198.18.0.0/15 (RFC 2544 benchmarking range) as private in the strict public-only checks: caller-supplied image and media URLs and the public-only DNS and connect-time guards. Off by default because fake-IP proxies (Clash, Mihomo, Surge in TUN mode) answer every hostname with an address in that range, so blocking it would refuse every guarded download behind such a proxy (#15039). Set `true` only when no fake-IP proxy is in use and the range holds internal services. |
| `AUDIO_REMOTE_PROVIDER_NODES` | `false` | `src/app/api/v1/_shared/audioProviderNodes.ts` | Let the `/v1/audio/*` routes (transcriptions, speech, translations) use an OpenAI-compatible provider node hosted outside localhost. Off by default — routing audio to a remote host changes egress identity and must be an explicit operator decision. Loopback/private nodes (localhost, 127.0.0.1, 172.16-31.x) are always allowed and unaffected. (#3963) |
| `RERANK_REMOTE_PROVIDER_NODES` | `false` | `src/app/api/v1/_shared/rerankProviderNodes.ts` | Let `POST /v1/rerank` (and the memory engine's loopback rerank step) use an OpenAI-compatible provider node hosted outside localhost — a LAN box or Tailscale peer running TEI, Infinity, vLLM, etc. Off by default — routing to a remote host changes egress identity and must be an explicit operator decision. Loopback nodes (localhost, 127.0.0.1, 172.16-31.x) are always allowed and unaffected. A remote node's base URL must also pass the provider outbound URL policy (`OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS` / `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS`). |
| `OMNIROUTE_LOCAL_PROVIDER_NODE_HOSTS` | _(empty)_ | `src/shared/network/localNodeHosts.ts` | Hostnames (comma or whitespace separated) that provider-node routing treats as local — typically the Docker/Compose service name of a reranker, TEI or audio sidecar on OmniRoute's own Docker network (`http://reranker:8080/v1`), so the node does not need a hard-coded container IP. Listed hosts are eligible for `/v1/rerank`, `/v1/audio/*` and the local health check without turning on `RERANK_REMOTE_PROVIDER_NODES` / `AUDIO_REMOTE_PROVIDER_NODES` for every remote node, and are called directly — never through `HTTP(S)_PROXY` or a connection's pinned proxy. They still send the connection's API key. Only single-label names and `.internal`/`.local` names are accepted; public FQDNs, IP literals and cloud-metadata names are ignored with a warning. (#14635) |

View File

@@ -5,11 +5,34 @@
*/
import { z } from "zod";
import { resolve, normalize, isAbsolute } from "path";
import { toSafeMcpErrorMessage } from "../errorMessage";
import { listPlugins, getPluginByName, updatePluginConfig } from "../../../src/lib/db/plugins";
import { pluginManager } from "../../../src/lib/plugins/manager";
import { validatePluginConfig, type ConfigField } from "../../../src/lib/plugins/manifest";
/**
* Validate a path is safe for plugin installation.
* Prevents directory traversal and null byte injection.
*/
function validatePluginPath(path: string): string {
// Reject null bytes
if (path.includes("\0")) {
throw new Error("Invalid path: contains null bytes");
}
// Must be absolute
if (!isAbsolute(path)) {
throw new Error("Path must be absolute");
}
// Normalize and resolve to prevent traversal
const normalized = normalize(resolve(path));
// Reject paths with traversal patterns
if (normalized.includes("..") || normalized.includes("~")) {
throw new Error("Invalid path: directory traversal detected");
}
return normalized;
}
export const pluginTools = [
{
name: "plugin_list",
@@ -41,19 +64,14 @@ export const pluginTools = [
{
name: "plugin_install",
description: "Install a plugin from a local directory inside the plugin sources directory.",
description: "Install a plugin from a local directory path.",
scopes: ["write:plugins"],
inputSchema: z.object({
path: z
.string()
.describe(
"Absolute path to a plugin directory (containing plugin.json) inside the plugin sources directory"
),
path: z.string().describe("Absolute path to the plugin directory containing plugin.json"),
}),
handler: async (args: { path: string }) => {
// Same containment as POST /api/plugins: the source must resolve inside the
// plugin sources directory (src/lib/plugins/installSource.ts).
const plugin = await pluginManager.installFromLocalSource(args.path);
const safePath = validatePluginPath(args.path);
const plugin = await pluginManager.install(safePath);
return {
success: true,
plugin: {

View File

@@ -3,7 +3,6 @@ import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
import { listPlugins } from "@/lib/db/plugins";
import { pluginManager } from "@/lib/plugins/manager";
import { PluginInstallSourceError } from "@/lib/plugins/installSource";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { z } from "zod";
@@ -41,12 +40,10 @@ export async function GET(request: NextRequest) {
}
/**
* POST /api/plugins — Install a plugin from a local path inside the plugin sources
* directory. Installing (and possibly activating) code is never anonymous, so the
* management credential is required even when login is disabled.
* POST /api/plugins — Install a plugin from a local path
*/
export async function POST(request: NextRequest) {
const authError = await requireManagementAuth(request, { alwaysRequireAuth: true });
const authError = await requireManagementAuth(request);
if (authError) return authError;
let body: unknown;
try {
@@ -58,13 +55,10 @@ export async function POST(request: NextRequest) {
);
}
const schema = z.object({
path: z
.string()
.min(1)
.refine(
(p) => !p.includes("\0") && !p.includes(".."),
"Path must not contain traversal patterns or null bytes"
),
path: z.string().min(1).regex(/^\/[^]*$/, "Path must be absolute").refine(
(p) => !p.includes("\0") && !p.includes(".."),
"Path must not contain traversal patterns or null bytes"
),
});
const parsed = schema.safeParse(body);
@@ -76,22 +70,12 @@ export async function POST(request: NextRequest) {
}
try {
const plugin = await pluginManager.installFromLocalSource(parsed.data.path);
const plugin = await pluginManager.install(parsed.data.path);
return NextResponse.json(
{ plugin: formatPlugin(plugin) },
{ status: 201, headers: CORS_HEADERS }
);
} catch (err: unknown) {
if (err instanceof PluginInstallSourceError) {
console.warn("[plugins] Refused plugin install source:", err.message);
return NextResponse.json(
buildErrorBody(
400,
"Plugin path must be an existing directory inside the plugin sources directory"
),
{ status: 400, headers: CORS_HEADERS }
);
}
console.error("[plugins] Failed to install plugin:", err);
return NextResponse.json(buildErrorBody(400, "Failed to install plugin"), {
status: 400,

View File

@@ -1,97 +0,0 @@
/**
* Install-source containment for the local-path plugin install.
*
* `POST /api/plugins` installs (and, with `enabledByDefault`, activates) the code
* found at a caller-supplied path. That path must live inside one operator-managed
* directory: the `plugin-sources` directory next to the plugin root
* (`~/.omniroute/plugin-sources` by default, or `<dirname(OMNIROUTE_PLUGINS_DIR)>/
* plugin-sources` when the plugin root is overridden). Anything else is refused.
*
* Every check fails closed: a missing root, a path that does not exist, a path that
* resolves (through symlinks) outside the root, or a symlink inside the source tree
* whose target escapes the root all reject the install.
*
* @module plugins/installSource
*/
import { lstat, readdir, realpath } from "fs/promises";
import { dirname, isAbsolute, join, resolve, sep } from "path";
export const PLUGIN_SOURCES_DIRNAME = "plugin-sources";
export class PluginInstallSourceError extends Error {
constructor(message: string) {
super(message);
this.name = "PluginInstallSourceError";
}
}
/** The directory local-path installs may read from, derived from the plugin root. */
export function getPluginSourcesDir(pluginDir: string): string {
return join(dirname(resolve(pluginDir)), PLUGIN_SOURCES_DIRNAME);
}
function isStrictlyInside(root: string, target: string): boolean {
return target.startsWith(root + sep);
}
async function assertNoEscapingSymlinks(dir: string, realRoot: string): Promise<void> {
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
for (const entry of entries) {
if (!entry.isSymbolicLink()) continue;
const entryPath = join(entry.parentPath, entry.name);
const target = await realpath(entryPath).catch(() => null);
if (!target || !isStrictlyInside(realRoot, target)) {
throw new PluginInstallSourceError(
"Plugin source contains a symlink that resolves outside the plugin sources directory"
);
}
}
}
/**
* Validate a caller-supplied install path against the plugin sources root and
* return its canonical (symlink-free) form, which is what the installer must use.
*/
export async function resolvePluginInstallSource(
requestedPath: string,
sourcesRoot: string
): Promise<string> {
if (
typeof requestedPath !== "string" ||
requestedPath.length === 0 ||
requestedPath.includes("\0") ||
!isAbsolute(requestedPath)
) {
throw new PluginInstallSourceError("Plugin path must be an absolute path");
}
const root = resolve(sourcesRoot);
const realRoot = await realpath(root).catch(() => null);
if (!realRoot) {
throw new PluginInstallSourceError("Plugin sources directory does not exist");
}
// Lexical check first, so a path outside the root is refused without ever being
// touched on disk (no existence probe of arbitrary host paths).
const lexical = resolve(requestedPath);
if (!isStrictlyInside(root, lexical) && !isStrictlyInside(realRoot, lexical)) {
throw new PluginInstallSourceError("Plugin path is outside the plugin sources directory");
}
const realSource = await realpath(requestedPath).catch(() => null);
if (!realSource) {
throw new PluginInstallSourceError("Plugin path does not exist");
}
if (!isStrictlyInside(realRoot, realSource)) {
throw new PluginInstallSourceError("Plugin path is outside the plugin sources directory");
}
const info = await lstat(realSource);
if (!info.isDirectory()) {
throw new PluginInstallSourceError("Plugin path must be a directory");
}
await assertNoEscapingSymlinks(realSource, realRoot);
return realSource;
}

View File

@@ -13,7 +13,6 @@ import { join, dirname, resolve, sep } from "path";
import { randomUUID } from "crypto";
import { logger } from "../../../open-sse/utils/logger.ts";
import { getDefaultPluginDir, scanPluginDir } from "./scanner";
import { getPluginSourcesDir, resolvePluginInstallSource } from "./installSource";
import { loadPlugin, type LoadedPlugin } from "./loader";
import { registerHook, unregisterHooks, emitHook, type HookHandler, type Plugin } from "./hooks";
import {
@@ -122,21 +121,6 @@ class PluginManager {
return PluginManager.instance;
}
/** Directory that caller-supplied local install paths must live in. */
getSourcesDir(): string {
return getPluginSourcesDir(this.pluginDir);
}
/**
* Install from a caller-supplied local path (POST /api/plugins). The path must
* resolve inside {@link getSourcesDir}; see ./installSource for the checks.
* Throws PluginInstallSourceError when the path is refused.
*/
async installFromLocalSource(requestedPath: string): Promise<PluginRow> {
const source = await resolvePluginInstallSource(requestedPath, this.getSourcesDir());
return this.install(source);
}
/**
* Install a plugin from a source directory.
* Copies to a staging dir first, validates manifest.main containment, then

View File

@@ -115,6 +115,17 @@ export function isSameIpv6Address(a: string, b: string): boolean {
return !!first && !!second && first.every((value, index) => value === second[index]);
}
/**
* 198.18.0.0/15 (RFC 2544 benchmarking) is never routed publicly, but it stays public by default:
* fake-IP proxies (Clash, Mihomo, Surge in TUN mode) answer every name with an address in it, so
* blocking it would refuse every guarded download behind such a proxy (#15039). An operator whose
* network has real internal services in that range opts in with
* OMNIROUTE_BLOCK_BENCHMARK_RANGE=true. Read on every call so a change applies without a restart.
*/
function blocksBenchmarkRange(): boolean {
return typeof process !== "undefined" && process.env?.OMNIROUTE_BLOCK_BENCHMARK_RANGE === "true";
}
export function isPrivateHost(hostname: string) {
const normalized = normalizeHost(hostname);
if (!normalized) return true;
@@ -150,6 +161,7 @@ export function isPrivateHost(hostname: string) {
// 192.0.0.0/24 (IETF protocol assignments), 224.0.0.0/4 multicast, and the Azure host
// fabric address.
if (a === 192 && b === 0 && c === 0) return true;
if (a === 198 && (b === 18 || b === 19) && blocksBenchmarkRange()) return true;
if (a >= 224 && a <= 239) return true;
// 240.0.0.0/4 reserved ("Class E"), whose top address is the limited broadcast
// 255.255.255.255. Never a public destination; some cloud networks use it as private space.

View File

@@ -7,10 +7,9 @@
* must surface as a clean 400, while a well-formed body keeps its existing behavior.
*
* DB setup mirrors tests/unit/api-malformed-json-400.test.ts: a temp DATA_DIR with no
* configured password. Both POST /api/plugins and PATCH /api/relay/tokens/[id] always
* require management auth, so their requests carry a manage-scoped API key, as in
* tests/unit/relay-tokens-always-protected.test.ts; the relay requests target a seeded
* token. DB handles
* configured password, so POST /api/plugins needs no login. PATCH /api/relay/tokens/[id]
* always requires management auth, so its requests carry a manage-scoped API key, as in
* tests/unit/relay-tokens-always-protected.test.ts, and target a seeded token. DB handles
* are released in test.after (resetDbInstance), as unreleased SQLite handles hang the runner.
*/
@@ -70,21 +69,14 @@ test.after(() => {
test("POST /api/plugins — malformed JSON body returns 400", async () => {
const res = await pluginsRoute.POST(
managedJsonRequest("http://localhost/api/plugins", "POST", "not-json") as never
jsonRequest("http://localhost/api/plugins", "POST", "not-json") as never
);
assert.equal(res.status, 400);
});
test("POST /api/plugins — malformed JSON without credentials is still 401", async () => {
const res = await pluginsRoute.POST(
jsonRequest("http://localhost/api/plugins", "POST", "not-json") as never
);
assert.equal(res.status, 401);
});
test("POST /api/plugins — well-formed but invalid body still returns 400", async () => {
const res = await pluginsRoute.POST(
managedJsonRequest("http://localhost/api/plugins", "POST", JSON.stringify({})) as never
jsonRequest("http://localhost/api/plugins", "POST", JSON.stringify({})) as never
);
assert.equal(res.status, 400);
const body = (await res.json()) as { error?: string };

View File

@@ -1,53 +0,0 @@
// npm publishing goes through Trusted Publishing (OIDC) only. The long-lived NPM_TOKEN expired
// in silence (npm caps write tokens at 90 days) and the v3.8.54 plugin publishes failed with
// E404 because the plugin jobs still sent it; the Trusted Publisher for both plugins was set up
// on 2026-11-18 and @omniroute/opencode-plugin@0.2.2 / -v2@0.1.1 shipped through OIDC. The
// only step left on a token is the DIRECT emergency fallback of `stage-npm`, which exists for
// the case where Trusted Publishing itself is broken and needs a freshly minted token.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import YAML from "yaml";
const root = fileURLToPath(new URL("../../../", import.meta.url));
const workflow = YAML.parse(readFileSync(join(root, ".github/workflows/npm-publish.yml"), "utf8"));
const DIRECT_FALLBACK = "Publish to npm (DIRECT — emergency fallback)";
function stepsUsingNpmToken() {
const found = [];
for (const [jobName, job] of Object.entries(workflow.jobs)) {
for (const step of job.steps || []) {
if (JSON.stringify(step).includes("secrets.NPM_TOKEN"))
found.push(`${jobName} → ${step.name}`);
}
}
return found;
}
test("only the DIRECT emergency fallback still reads the NPM_TOKEN secret", () => {
assert.deepEqual(stepsUsingNpmToken(), [`stage-npm → ${DIRECT_FALLBACK}`]);
});
for (const jobName of ["publish-opencode-plugin", "publish-opencode-plugin-v2"]) {
test(`${jobName} publishes through OIDC: id-token write, no auth token on the publish step`, () => {
const job = workflow.jobs[jobName];
assert.equal(job.permissions["id-token"], "write");
const publish = job.steps.find((s) => /^Publish @omniroute\//.test(s.name || ""));
assert.ok(publish, `${jobName} has a publish step`);
assert.equal(publish.env?.NODE_AUTH_TOKEN, undefined);
assert.match(publish.run, /npm publish --provenance --access public/);
});
}
test("stage-npm staged mode publishes through OIDC as well", () => {
const job = workflow.jobs["stage-npm"];
assert.equal(job.permissions["id-token"], "write");
const staged = job.steps.find((s) => (s.name || "").startsWith("Publish to npm (staged"));
assert.ok(staged, "stage-npm has the staged step");
assert.equal(staged.env?.NODE_AUTH_TOKEN, undefined);
assert.match(staged.run, /npm stage publish/);
});

View File

@@ -1,172 +0,0 @@
// POST /api/plugins installs — and, with `enabledByDefault`, activates — the code at a
// caller-supplied path. Two guarantees are pinned here:
// 1. the install source must live inside the operator-managed `plugin-sources`
// directory next to the plugin root; any other absolute path, a path that
// resolves outside it through a symlink, or a source tree carrying a symlink
// that escapes it is refused before anything is copied;
// 2. the route needs a management credential even when login is disabled
// (requireLogin=false): "anonymous" is never the right audience for
// "install and run this code on the host".
import test 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 { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const BASE_DIR = fs.mkdtempSync(
path.join(process.env.DATA_DIR || os.tmpdir(), "plugin-src-guard-")
);
const PLUGIN_ROOT = path.join(BASE_DIR, "plugins");
const SOURCES_ROOT = path.join(BASE_DIR, "plugin-sources");
const OUTSIDE_ROOT = path.join(BASE_DIR, "outside");
fs.mkdirSync(PLUGIN_ROOT, { recursive: true });
fs.mkdirSync(SOURCES_ROOT, { recursive: true });
fs.mkdirSync(OUTSIDE_ROOT, { recursive: true });
const ORIGINAL_ENV = {
OMNIROUTE_PLUGINS_DIR: process.env.OMNIROUTE_PLUGINS_DIR,
JWT_SECRET: process.env.JWT_SECRET,
API_KEY_SECRET: process.env.API_KEY_SECRET,
};
process.env.OMNIROUTE_PLUGINS_DIR = PLUGIN_ROOT;
process.env.JWT_SECRET = "plugin-src-guard-jwt-secret";
process.env.API_KEY_SECRET = "plugin-src-guard-api-key-secret";
const core = await import("../../src/lib/db/core.ts");
const pluginsDb = await import("../../src/lib/db/plugins.ts");
const { updateSettings } = await import("../../src/lib/db/settings.ts");
const pluginsRoute = await import("../../src/app/api/plugins/route.ts");
const loadInstallSource = () => import("../../src/lib/plugins/installSource.ts");
const URL_PLUGINS = "http://localhost:20128/api/plugins";
test.after(() => {
core.resetDbInstance();
fs.rmSync(BASE_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
function writePlugin(parent: string, name: string): string {
const dir = path.join(parent, name);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, "plugin.json"),
JSON.stringify({ name, version: "1.0.0", main: "index.js" })
);
fs.writeFileSync(path.join(dir, "index.js"), "module.exports = {};\n");
return dir;
}
function anonymousPost(body: unknown): Request {
return new Request(URL_PLUGINS, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
function sessionPost(body: unknown): Promise<Request> {
return makeManagementSessionRequest(URL_PLUGINS, { method: "POST", body: body as never });
}
async function assertRefused(response: Response, status: number): Promise<void> {
const text = await response.text();
assert.equal(response.status, status, `expected ${status}, got ${response.status}: ${text}`);
assert.ok(!text.includes("at /"), "error body must not leak a stack trace");
}
test("getPluginSourcesDir is the plugin-sources sibling of the plugin root", async () => {
const installSource = await loadInstallSource();
assert.equal(installSource.getPluginSourcesDir(PLUGIN_ROOT), SOURCES_ROOT);
});
test("resolvePluginInstallSource refuses paths outside the sources root", async () => {
const installSource = await loadInstallSource();
const outside = writePlugin(OUTSIDE_ROOT, "outside-direct");
const cases = [
outside,
"/etc",
"relative/plugin",
"",
`${SOURCES_ROOT}/../outside/outside-direct`,
SOURCES_ROOT,
`${SOURCES_ROOT}-sibling/x`,
`${SOURCES_ROOT}/x\0y`,
];
for (const candidate of cases) {
await assert.rejects(
installSource.resolvePluginInstallSource(candidate, SOURCES_ROOT),
installSource.PluginInstallSourceError,
`must refuse ${JSON.stringify(candidate)}`
);
}
});
test("resolvePluginInstallSource refuses symlinks that escape the sources root", async () => {
const installSource = await loadInstallSource();
const outside = writePlugin(OUTSIDE_ROOT, "outside-linked");
const linkedDir = path.join(SOURCES_ROOT, "linked-dir");
fs.symlinkSync(outside, linkedDir, "dir");
await assert.rejects(
installSource.resolvePluginInstallSource(linkedDir, SOURCES_ROOT),
installSource.PluginInstallSourceError
);
const inner = writePlugin(SOURCES_ROOT, "inner-escape");
fs.mkdirSync(path.join(inner, "lib"));
fs.symlinkSync(path.join(outside, "index.js"), path.join(inner, "lib", "evil.js"));
await assert.rejects(
installSource.resolvePluginInstallSource(inner, SOURCES_ROOT),
installSource.PluginInstallSourceError
);
});
test("resolvePluginInstallSource fails closed when the sources root does not exist", async () => {
const installSource = await loadInstallSource();
const missingRoot = path.join(BASE_DIR, "missing-root");
await assert.rejects(
installSource.resolvePluginInstallSource(path.join(missingRoot, "p"), missingRoot),
installSource.PluginInstallSourceError
);
});
test("resolvePluginInstallSource accepts a plugin directory inside the sources root", async () => {
const installSource = await loadInstallSource();
const good = writePlugin(SOURCES_ROOT, "inside-ok");
fs.symlinkSync(path.join(good, "index.js"), path.join(good, "alias.js"));
const resolved = await installSource.resolvePluginInstallSource(good, SOURCES_ROOT);
assert.equal(resolved, fs.realpathSync(good));
});
test("POST /api/plugins refuses an install source outside the plugin sources directory", async () => {
const outside = writePlugin(OUTSIDE_ROOT, "route-outside");
const response = await pluginsRoute.POST((await sessionPost({ path: outside })) as never);
await assertRefused(response, 400);
assert.equal(pluginsDb.getPluginByName("route-outside"), null, "nothing may be installed");
assert.equal(fs.existsSync(path.join(PLUGIN_ROOT, "route-outside")), false);
});
test("POST /api/plugins installs from inside the plugin sources directory", async () => {
const good = writePlugin(SOURCES_ROOT, "route-inside");
const response = await pluginsRoute.POST((await sessionPost({ path: good })) as never);
const text = await response.text();
assert.equal(response.status, 201, text);
assert.equal(JSON.parse(text).plugin.name, "route-inside");
assert.ok(pluginsDb.getPluginByName("route-inside"));
});
test("with login disabled, an anonymous POST /api/plugins is refused", async () => {
const good = writePlugin(SOURCES_ROOT, "route-anon");
await updateSettings({ requireLogin: false });
try {
const response = await pluginsRoute.POST(anonymousPost({ path: good }) as never);
await assertRefused(response, 401);
assert.equal(pluginsDb.getPluginByName("route-anon"), null, "nothing may be installed");
} finally {
await updateSettings({ requireLogin: true });
}
});

View File

@@ -22,11 +22,10 @@ function getTool(name: string) {
return tool!;
}
function writeTestPlugin(opts?: { name?: string; onRequest?: boolean; parent?: string }) {
function writeTestPlugin(opts?: { name?: string; onRequest?: boolean }) {
const name = opts?.name ?? "test-tools-plugin";
const onRequest = opts?.onRequest ?? true;
if (opts?.parent) fs.mkdirSync(opts.parent, { recursive: true });
const sourceDir = fs.mkdtempSync(path.join(opts?.parent ?? os.tmpdir(), "omniroute-plugin-src-"));
const sourceDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-plugin-src-"));
const pluginDir = path.join(sourceDir, name);
fs.mkdirSync(pluginDir, { recursive: true });
const manifest = {
@@ -127,12 +126,8 @@ test("plugin_list: filters by status", async () => {
// ── plugin_install ──
test("plugin_install: installs a valid plugin from the plugin sources directory", async () => {
const { pluginManager } = await import("../../src/lib/plugins/manager.ts");
const { sourceDir, name } = writeTestPlugin({
name: "install-tool",
parent: pluginManager.getSourcesDir(),
});
test("plugin_install: installs a valid plugin", async () => {
const { sourceDir, name } = writeTestPlugin({ name: "install-tool" });
activeSourceDirs.push(sourceDir);
const tool = getTool("plugin_install");
@@ -140,30 +135,16 @@ test("plugin_install: installs a valid plugin from the plugin sources directory"
assert.equal(result.success, true);
assert.equal(result.plugin.name, name);
const { pluginManager } = await import("../../src/lib/plugins/manager.ts");
await pluginManager.uninstall(name);
});
test("plugin_install: refuses a path outside the plugin sources directory", async () => {
const { sourceDir, name } = writeTestPlugin({ name: "install-tool-outside" });
activeSourceDirs.push(sourceDir);
const tool = getTool("plugin_install");
await assert.rejects(
() => tool.handler({ path: sourceDir }),
(err: Error) => {
assert.equal(err.name, "PluginInstallSourceError");
return true;
}
);
assert.equal(dbPlugins.getPluginByName(name), null, "nothing may be installed");
});
test("plugin_install: throws for invalid path", async () => {
const tool = getTool("plugin_install");
await assert.rejects(
() => tool.handler({ path: "/nonexistent/path" }),
(err: Error) => {
assert.equal(err.name, "PluginInstallSourceError");
assert.ok(err.message.includes("No valid plugin found"));
return true;
}
);

View File

@@ -0,0 +1,136 @@
/**
* 198.18.0.0/15 is reserved for network benchmarking (RFC 2544) and is never routed publicly.
* It stays public by default, because fake-IP proxies (Clash, Mihomo, Surge in TUN mode) answer
* every name with an address in it (#15039). With OMNIROUTE_BLOCK_BENCHMARK_RANGE=true the strict
* outbound guard refuses it like the other non-public IPv4 blocks: as a dotted IPv4, as
* IPv4-mapped IPv6 (compressed and expanded), as NAT64, in a URL, and as a DNS answer to
* `safeOutboundFetch({ guard: "public-only" })`. The addresses right outside the /15 stay public
* in both modes.
*
* Run with:
* node --import tsx/esm --test tests/unit/private-host-benchmark-range.test.ts
*/
import { afterEach, beforeEach, describe, it } from "node:test";
import assert from "node:assert/strict";
import {
isPrivateHost,
parseAndValidatePublicUrl,
OutboundUrlGuardError,
} from "../../src/shared/network/outboundUrlGuard.ts";
const { safeOutboundFetch, SafeOutboundFetchError } =
await import("../../src/shared/network/safeOutboundFetch.ts");
const FLAG = "OMNIROUTE_BLOCK_BENCHMARK_RANGE";
// Each entry: [IPv4 address, the same address as expanded IPv4-mapped IPv6, as NAT64].
const BENCHMARK = [
["198.18.0.0", "0:0:0:0:0:ffff:c612:0", "64:ff9b::c612:0"],
["198.18.0.1", "0:0:0:0:0:ffff:c612:1", "64:ff9b::c612:1"],
["198.19.255.254", "0:0:0:0:0:ffff:c613:fffe", "64:ff9b::c613:fffe"],
["198.19.255.255", "0:0:0:0:0:ffff:c613:ffff", "64:ff9b::c613:ffff"],
] as const;
// The addresses right outside 198.18.0.0/15.
const NEIGHBOURS = ["198.17.255.255", "198.20.0.0", "0:0:0:0:0:ffff:c611:ffff"];
async function guardCode(address: string): Promise<string | null> {
try {
await safeOutboundFetch("http://bench.alias.test:9/", {
guard: "public-only",
retry: false,
timeoutMs: 500,
dnsLookup: async () => [{ address, family: address.includes(":") ? 6 : 4 }],
});
return null;
} catch (error) {
return error instanceof SafeOutboundFetchError ? error.code : "OTHER";
}
}
let saved: string | undefined;
function restoreFlag() {
if (saved === undefined) delete process.env[FLAG];
else process.env[FLAG] = saved;
}
describe("198.18.0.0/15 by default - public, for fake-IP proxies", () => {
beforeEach(() => {
saved = process.env[FLAG];
delete process.env[FLAG];
});
afterEach(restoreFlag);
it("isPrivateHost treats every spelling as public", () => {
for (const [ipv4, mapped, nat64] of BENCHMARK) {
assert.equal(isPrivateHost(ipv4), false, ipv4);
assert.equal(isPrivateHost(mapped), false, mapped);
assert.equal(isPrivateHost(nat64), false, nat64);
}
});
it("parseAndValidatePublicUrl accepts the range", () => {
for (const [ipv4] of BENCHMARK) {
assert.doesNotThrow(() => parseAndValidatePublicUrl(`http://${ipv4}/v1`), ipv4);
}
});
it("safeOutboundFetch public-only does not refuse a fake-IP answer", async () => {
assert.notEqual(await guardCode("198.18.0.1"), "URL_GUARD_BLOCKED");
});
it("any value other than true keeps the default", () => {
for (const value of ["false", "1", "TRUE", ""]) {
process.env[FLAG] = value;
assert.equal(isPrivateHost("198.18.0.1"), false, JSON.stringify(value));
}
});
});
describe("198.18.0.0/15 with OMNIROUTE_BLOCK_BENCHMARK_RANGE=true - private", () => {
beforeEach(() => {
saved = process.env[FLAG];
process.env[FLAG] = "true";
});
afterEach(restoreFlag);
for (const [ipv4, mapped, nat64] of BENCHMARK) {
it(`isPrivateHost treats ${ipv4}, ${mapped} and ${nat64} as private`, () => {
assert.equal(isPrivateHost(ipv4), true);
assert.equal(isPrivateHost(mapped), true);
assert.equal(isPrivateHost(`[${mapped}]`), true);
assert.equal(isPrivateHost(nat64), true);
});
for (const url of [`http://${ipv4}/v1`, `http://[::ffff:${ipv4}]/v1`, `http://[${mapped}]/`]) {
it(`parseAndValidatePublicUrl rejects ${url}`, () => {
assert.throws(
() => parseAndValidatePublicUrl(url),
(error: unknown) => error instanceof OutboundUrlGuardError
);
});
}
}
it("keeps the neighbours public", () => {
for (const host of NEIGHBOURS) {
assert.equal(isPrivateHost(host), false, host);
}
for (const url of ["http://198.17.255.255/", "http://198.20.0.0/"]) {
assert.doesNotThrow(() => parseAndValidatePublicUrl(url), url);
}
});
for (const address of ["198.18.0.1", "198.19.255.254", "0:0:0:0:0:ffff:c612:1"]) {
it(`safeOutboundFetch public-only refuses a name resolving to ${address}`, async () => {
assert.equal(await guardCode(address), "URL_GUARD_BLOCKED");
});
}
it("safeOutboundFetch public-only does not refuse a neighbour address", async () => {
assert.notEqual(await guardCode("198.20.0.1"), "URL_GUARD_BLOCKED");
});
});