Files
OmniRoute/src/lib/db/apiKeys/rowParsers.ts
Moseyuh333 eeec4d9e87 feat(chaos): big update - optimize, fix bugs, add features, enhance UX (#6728)
* feat(chaos): add Chaos Mode — multi-model parallel/collaborative execution

- New DB column chaos_mode_enabled on api_keys table
- API key create/PATCH routes support chaosModeEnabled toggle
- Core library src/lib/chaos/chaosConfig.ts for persistent config
- API routes: GET/PUT/DELETE /api/chaos/config
- Chaos execution POST /api/skills/collect/chaos with key auth
- Dashboard page at /dashboard/chaos with full config UI
- Sidebar entry in Agentic Features section
- Chaos mode toggle in API Key editor permissions panel
- i18n keys for chaos config (en.json)

* feat(chaos): big update — optimize, fix bugs, add features

=== Changes ===

1. NEW: src/lib/chaos/chaosExecutor.ts — shared execution engine
   - Removed ~150 lines of duplicate dispatch logic between two API routes
   - Single executeChaosRun() function used by both endpoints
   - Added concurrency limit (max 10 parallel requests)
   - Added proper TypeScript interfaces (ChaosRunInput, ChaosRunResult)
   - Added error logging throughout

2. FIX: src/app/api/skills/collect/chaos/route.ts
   - Was MISSING logger import (log.error was undefined at runtime)
   - Reduced from 388 lines → 142 lines by delegating to shared executor
   - Added maxTokens support in schema validation

3. REFACTOR: src/app/api/chaos/run/route.ts
   - Simplified to thin wrapper: auth + validate + delegate to executor
   - Added maxTokens support

4. ENHANCE: src/lib/chaos/chaosConfig.ts
   - Added maxTokens config field (256-128k, default 4096)
   - Persisted per-instance via settings table

5. ENHANCE: UI — ChaosConfigPageClient.tsx
   - Loads available providers from /api/models for dropdown autocomplete
   - Added datalist-based provider selector in overrides section
   - Added Max Tokens configuration input
   - Added expandable provider list showing all detected providers
   - Fixed duplicate override detection

* fix(chaos): fetch providers from /api/providers instead of /api/keys

* fix(chaos): remove dead code isOverrideDuplicate, fix maxTokens fallback to include global config

* fix(chaos): resetConfig now shows error on HTTP failure (was silent)

* feat(dashboard): Chaos Mode — multi-model parallel/collaborative execution

Splits the PR down to only the genuinely new Chaos Mode feature (drops the
duplicate Skill Collector/GitHub-discovery portion already shipped via
#6186). Replaces the loopback fetch() dispatch (hardcoded to the wrong port)
with the established in-process synthetic-Request/route-handler pattern used
by src/lib/batches/dispatch.ts, moves settings persistence off raw SQL, and
adds unit test coverage for chaosConfig, chaosExecutor and the 3 chaos API
routes.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* fix(chaos): fix external Bearer-auth bypass and stale config cache in tests

validateApiKey() returns a plain boolean for both the deployment-time env key
and a DB-backed key, so branching on `keyInfo === true` in
verifyChaosKey() (src/app/api/skills/collect/chaos/route.ts) treated every
valid API key as having full env-key access, silently skipping the
chaosModeEnabled permission check entirely. Now always resolves through
getApiKeyMetadata() and only bypasses the per-key check for the synthesized
env-key record (id: "env-key").

Also exports invalidateChaosConfigCache() from chaosConfig.ts and wires it
into the route tests' resetStorage() — the in-process config cache was
surviving DB resets between tests, causing state to leak across cases.

Fixes CHANGELOG-eat from the release merge (re-inserted the Chaos Mode
bullet against the base CHANGELOG.md, verified additive via
check-changelog-integrity.mjs) and re-syncs against release/v3.8.47 tip.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* docs(changelog): Chaos Mode overhaul bullet referencing #6728 after release sync

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* fix(merge): restore #6126 clinepass files reverted by release auto-resolve + baseline re-merge

The release sync's auto-resolve reverted sibling PR #6126's clinepass work
(registry, catalog, oauth constants, clineAuth.ts, token-refresh case, tests)
and the file-size baseline — all outside this PR's scope. Restored to the
release versions, re-applied only this PR's own baseline entries, restored the
#6126 CHANGELOG bullet (re-inserting only this PR's own).

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* fix(dashboard): chaos client hook must not import the server Pino logger

useChaosConfigData ("use client") pulled @/sse/utils/logger → shared Pino →
logRotation/dataPaths → node:fs into the browser bundle, breaking next build
(Turbopack: Can't resolve 'fs') — caught by the DAST smoke's isolated build.
console.error matches every other dashboard client component.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* test(api-manager): align switch-count invariant with the extracted toggle components

The Self-service block now renders 4 inline switches; the #5731 quota-bypass
and #6728 chaos-access toggles were extracted into dedicated components. The
type="button" invariant is preserved AND extended: the test now also asserts
each extracted component's switches declare type="button".

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* chore(sync): merge release tip + restore own CHANGELOG bullet

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: Moseyuh333 <Moseyuh333@users.noreply.github.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
2026-07-09 23:49:48 -03:00

166 lines
4.8 KiB
TypeScript

/**
* db/apiKeys/rowParsers.ts — pure column parsers for persisted api_keys rows.
*
* Extracted verbatim from db/apiKeys.ts (god-file decomposition): the family of
* functions that coerce raw SQLite column values (JSON strings, 0/1 flags, nullable
* timestamps) into the typed shapes the host hydrates rows with. Pure — no DB handle,
* no caches, no side effects — so they live as a co-located leaf. Behavior-preserving
* move; apiKeys.ts imports them back for getApiKeys/getApiKeyById/getApiKeyMetadata.
*/
import type { AccessSchedule, RateLimitRule } from "./types";
/**
* Helper function to safely parse allowed_models JSON
*/
export function parseAllowedModels(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? parsed.filter((entry): entry is string => typeof entry === "string")
: [];
} catch {
return [];
}
}
export function parseAllowedCombos(value: unknown): string[] {
return parseStringList(value);
}
export function parseNoLog(value: unknown): boolean {
return value === true || value === 1 || value === "1";
}
export function parseAutoResolve(value: unknown): boolean {
return value === true || value === 1 || value === "1";
}
export function parseDisableNonPublicModels(value: unknown): boolean {
return value === true || value === 1 || value === "1";
}
export function parseAllowUsageCommand(value: unknown): boolean {
return value === true || value === 1 || value === "1";
}
export function parseChaosModeEnabled(value: unknown): boolean {
return value === true || value === 1 || value === "1";
}
export function parseIsActive(value: unknown): boolean {
// DEFAULT 1 — active unless explicitly set to 0
if (value === 0 || value === "0" || value === false) return false;
return true;
}
export function parseAccessSchedule(value: unknown): AccessSchedule | null {
if (!value || typeof value !== "string" || value.trim() === "") return null;
try {
const parsed: unknown = JSON.parse(value);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
const obj = parsed as Record<string, unknown>;
if (
typeof obj["enabled"] !== "boolean" ||
typeof obj["from"] !== "string" ||
typeof obj["until"] !== "string" ||
!Array.isArray(obj["days"]) ||
typeof obj["tz"] !== "string"
) {
return null;
}
const days = (obj["days"] as unknown[]).filter(
(d): d is number => typeof d === "number" && Number.isInteger(d) && d >= 0 && d <= 6
);
return {
enabled: obj["enabled"],
from: obj["from"],
until: obj["until"],
days,
tz: obj["tz"],
};
} catch {
return null;
}
}
export function parseRateLimits(value: unknown): RateLimitRule[] | null {
if (!value || typeof value !== "string" || value.trim() === "") return null;
try {
const parsed = JSON.parse(value);
if (!Array.isArray(parsed)) return null;
return parsed.filter(
(rule: RateLimitRule) =>
typeof rule === "object" &&
rule !== null &&
typeof rule.limit === "number" &&
typeof rule.window === "number"
) as RateLimitRule[];
} catch {
return null;
}
}
/**
* Helper function to safely parse allowed_connections JSON
*/
export function parseAllowedConnections(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? parsed.filter((entry): entry is string => typeof entry === "string")
: [];
} catch {
return [];
}
}
/**
* Helper function to safely parse allowed_quotas JSON
*/
export function parseAllowedQuotas(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? parsed.filter((entry): entry is string => typeof entry === "string")
: [];
} catch {
return [];
}
}
export function parseStringList(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") return [];
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? parsed.filter((entry): entry is string => typeof entry === "string")
: [];
} catch {
return [];
}
}
export function parseNullableTimestamp(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed === "" ? null : trimmed;
}
export function parseIsBanned(value: unknown): boolean {
return value === 1 || value === "1" || value === true;
}
export function parseStreamDefaultMode(value: unknown): "legacy" | "json" {
return value === "json" ? "json" : "legacy";
}