Files
OmniRoute/tests/unit/compression/rtk-raw-output-route.test.ts
Diego Rodrigues de Sa e Souza 743be29852 feat(compression): RTK compression roadmap (#1889)
* chore(rtk): initialize compression roadmap branch

* feat(compression): add RTK engine and compression combos

Introduce RTK command-aware tool-output compression alongside
stacked RTK -> Caveman pipelines for mixed prompt contexts.

Add engine registration, declarative RTK filter packs, language-aware
Caveman rule loading, compression combo persistence and assignments,
analytics grouped by engine/combo, and new MCP/API endpoints for
configuration, previews, filters, and combo management.

Expose the new capabilities in the dashboard with dedicated Context &
Cache pages for Caveman, RTK, and compression combos, and update docs,
i18n strings, migrations, and tests to cover the expanded compression
surface.

* feat(compression): expand RTK DSL, filter catalog, and recovery APIs

Add RTK parity features across the compression pipeline, dashboard,
and management APIs. This expands the built-in filter catalog, adds
trust-gated custom filter loading, inline filter verification, code
stripping, smarter detection, and optional redacted raw-output
retention for authenticated recovery.

Also extend Caveman with file-based multilingual rule packs, localized
output-mode instructions, stricter preview/config schemas, engine
registry metadata, analytics fields, and broad unit test coverage for
RTK, rule loading, and stacked compression behavior.

* fix(auth): protect oauth routes and health reset operations

Require authenticated dashboard access for OAuth endpoints that can
create or import provider connections when login enforcement is
enabled.

Move `/api/monitoring/health` to the readonly public route list so
safe methods remain public while DELETE now returns 401 for anonymous
requests.

Also update Next.js native `.node` handling to avoid webpack parse
failures from external packages such as ngrok and keytar, and add
coverage for the new auth behavior.

* build(compression): ship RTK rule and filter assets with app bundles

Include compression JSON assets in Next output tracing, prepublish copies,
and pack artifact policy checks so standalone and packaged builds can
load RTK filters and caveman rule packs at runtime.

Also harden compression runtime behavior by resolving alternate asset
directories, scoping rule cache entries by source path, carrying RTK raw
output pointers through stacked runs, degrading oversized preview diffs,
and applying combo language/output mode defaults during chat routing.

Add coverage for packaging rules, provider-scoped model parsing, smart
truncate edge cases, raw output retention, and combo-driven compression
behavior.

* docs(workflows): update local repo paths to OmniRoute

Replace outdated `/home/diegosouzapw/dev/proxys/9router` references
with the current `OmniRoute` directory across deploy, release, and
version bump workflow guides so local command examples match the
renamed repository layout

* feat(compression): complete RTK parity coverage

* test(build): align next config assertions

---------

Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com>
2026-05-03 00:37:08 -03:00

139 lines
4.7 KiB
TypeScript

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 TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-raw-route-"));
const originalDataDir = process.env.DATA_DIR;
const originalJwtSecret = process.env.JWT_SECRET;
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../../src/lib/db/core.ts");
const settingsDb = await import("../../../src/lib/db/settings.ts");
const route = await import("../../../src/app/api/context/rtk/raw-output/[id]/route.ts");
const rawOutput = await import("../../../open-sse/services/compression/engines/rtk/rawOutput.ts");
type ErrorResponseBody = {
error: string | { message?: string };
};
async function resetAuthRequiredStorage(): Promise<void> {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
await settingsDb.updateSettings({
requireLogin: true,
setupComplete: true,
password: "test-password-hash",
});
}
test.beforeEach(async () => {
process.env.DATA_DIR = TEST_DATA_DIR;
await resetAuthRequiredStorage();
});
test.after(() => {
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
if (originalJwtSecret === undefined) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = originalJwtSecret;
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("RTK raw-output route requires management auth before reading retained output", async () => {
const pointer = rawOutput.maybePersistRtkRawOutput("error: full output", {
retention: "always",
command: "pytest",
});
assert.ok(pointer);
const response = await route.GET(
new Request(`http://localhost/api/context/rtk/raw-output/${pointer.id}`),
{ params: Promise.resolve({ id: pointer.id }) }
);
const body = (await response.json()) as ErrorResponseBody;
assert.equal(response.status, 401);
assert.equal(
typeof body.error === "object" ? body.error.message : null,
"Authentication required"
);
});
test("RTK raw-output route rejects bearer tokens without a dashboard session", async () => {
const response = await route.GET(
new Request("http://localhost/api/context/rtk/raw-output/0123456789abcdef01234567", {
headers: { authorization: "Bearer invalid-management-token" },
}),
{ params: Promise.resolve({ id: "0123456789abcdef01234567" }) }
);
const body = (await response.json()) as ErrorResponseBody;
assert.equal(response.status, 403);
assert.equal(
typeof body.error === "object" ? body.error.message : null,
"Invalid management token"
);
});
test("RTK raw-output route validates pointer ids for authenticated callers", async () => {
const request = await makeManagementSessionRequest(
"http://localhost/api/context/rtk/raw-output/not-a-pointer"
);
const response = await route.GET(request, {
params: Promise.resolve({ id: "not-a-pointer" }),
});
const body = (await response.json()) as ErrorResponseBody;
assert.equal(response.status, 400);
assert.equal(body.error, "Invalid raw output id");
});
test("RTK raw-output route returns 404 for missing authenticated pointers", async () => {
const request = await makeManagementSessionRequest(
"http://localhost/api/context/rtk/raw-output/0123456789abcdef01234567"
);
const response = await route.GET(request, {
params: Promise.resolve({ id: "0123456789abcdef01234567" }),
});
const body = (await response.json()) as ErrorResponseBody;
assert.equal(response.status, 404);
assert.equal(body.error, "Raw output not found");
});
test("RTK raw-output route returns retained redacted output for authenticated callers", async () => {
const pointer = rawOutput.maybePersistRtkRawOutput(
"token=secret-value\nAuthorization: Bearer abcdef123456\nerror: full output",
{
retention: "always",
command: "pytest",
}
);
assert.ok(pointer);
const request = await makeManagementSessionRequest(
`http://localhost/api/context/rtk/raw-output/${pointer.id}`
);
const response = await route.GET(request, {
params: Promise.resolve({ id: pointer.id }),
});
const content = await response.text();
assert.equal(response.status, 200);
assert.equal(response.headers.get("cache-control"), "no-store");
assert.match(response.headers.get("content-type") ?? "", /text\/plain/);
assert.match(content, /token=\[REDACTED\]/);
assert.match(content, /Authorization: Bearer \[REDACTED\]/);
assert.ok(!content.includes("secret-value"));
assert.ok(!content.includes("abcdef123456"));
});