mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-20 22:22:57 +03:00
Release v3.8.27 (#3968)
* chore(release): open v3.8.27 development cycle * fix(security): polynomial ReDoS in comboAgentMiddleware regex (#3982) * fix(security): eliminate polynomial ReDoS in comboAgentMiddleware <omniModel> regex (CodeQL js/polynomial-redos) CACHE_TAG_PATTERN wrapped the tag in an unbounded `(?:\\n|\n|\r)*` prefix/suffix. On an unanchored `.test()`/`.exec()` that is O(n²) on inputs with many newlines (CodeQL js/polynomial-redos, alerts #612/#613). The surrounding runs are irrelevant to detecting/capturing the tag, so the detection pattern now matches only the core `<omniModel>([^<]+)</omniModel>`; the global strip pattern still consumes the wrapping newlines (combo.ts streaming, #531) but BOUNDED ({0,16}) so it stays linear. Behavior preserved: detection, model extraction, multi-tag stripping (#454) and blank-line cleanup all unchanged (107 related tests green). Adds ReDoS-safety regression tests (50k-newline inputs complete in <1ms). * docs(changelog): add #3982 ReDoS fix to [3.8.27] * ci(security): harden workflows — artipacked persist-credentials + cache-poisoning + SC2086 (#3965) * Refine provider quota card display (#3969) Integrated into release/v3.8.27 * feat: add sidebar group separator toggles (#3971) Integrated into release/v3.8.27 * Gate control-plane proxy direct fallback (#3963) Integrated into release/v3.8.27 * Capture actual upstream provider requests (#3941) Integrated into release/v3.8.27 * ci(quality): flip require-tighten + osv + Trivy to blocking (v3.8.27 cycle-end) (#3984) * fix(resilience): respect connection cooldown stored as numeric epoch (#3954) (#3995) rate_limited_until is a TEXT column, but setConnectionRateLimitUntil (Antigravity full-quota path) persists a raw epoch number that SQLite coerces to a numeric string ("1781696905131.0"). The selection predicate isAccountUnavailable then did new Date("1781696905131.0") -> NaN, so the cooling connection was never skipped and the router kept dispatching to rate-limited accounts. Normalize numeric-epoch strings (and number/Date/ISO) via a shared cooldownUntilMs() helper in isAccountUnavailable / getEarliestRateLimitedUntil / filterAvailableAccounts / parseFutureDateMs. ISO behavior preserved. * fix(providers): fetch live /models for LLM7 and BytePlus (#3976) (#3996) llm7 and byteplus carry a real modelsUrl but were not classified by any live-fetch branch of the model-import route, so their hardcoded 4-entry registry catalog was served (source local_catalog) instead of the upstream catalog. Add both to NAMED_OPENAI_STYLE_PROVIDERS so the route probes <baseUrl>/models and serves the live list, falling back to the local catalog only on fetch failure. * fix(dashboard): logs auto-refresh reads live visibility, not a stale mount ref (#3972) (#3997) The auto-refresh interval gated each tick on visibleRef, seeded once at mount and updated only by a visibilitychange event. A tab mounted while document.visibilityState is 'hidden' (background load, bfcache, embedded/proxied webviews) with no later visibilitychange left the ref false forever, so the interval ticked but never fetched — only the manual button worked. Read the live document.visibilityState in the tick instead. * feat(compression): add Indonesian caveman rules and language pack (#3975) Integrated into release/v3.8.27 (cherry picked from commitc9b5b1a892) * fix(combo): shuffle strict-random fallback remainder to spread load (#3959) (#3998) strict-random shuffled only the deck-selected slot 0 and left the fallback remainder in fixed priority order, so after a failing deck pick the chain always fell through to the same top-priority model — a persistently-failing model was retried on essentially every request and fallback load never spread across peers. Shuffle the remainder too (like the random strategy). * Add provider auth visibility controls (#3953) Integrated into release/v3.8.27 * fix(claude): forward client tool-search-tool anthropic-beta on the Claude OAuth path (#3974) (#3999) The client-negotiated anthropic-beta: tool-search-tool-2025-10-19 was dropped on both Claude code paths (default executor rebuilt from static ANTHROPIC_BETA_CLAUDE_OAUTH; selectBetaFlags only read the client beta to gate thinking/effort), so claude.ai rejected deferred-tool requests with 400 'Tool reference not found'. Add an allowlist-merge (mergeClientAnthropicBeta) that unions the client's allowlisted betas into the outbound set on both paths, preserving #3415 (no forced thinking/effort). * feat(providers): add model search filter to provider dashboard (#3950) Integrated into release/v3.8.27 * fix(vision-bridge): force bridge for tokenrouter deepseek models (#3946) Integrated into release/v3.8.27 * fix(executor): strip stream_options on non-streaming requests (#3884) (#4000) Clients that send stream_options:{include_usage:true} regardless of stream (e.g. the OpenAI Python SDK) had it passed through on non-streaming calls; NVIDIA NIM rejected it with 400 'Stream options can only be defined when stream=True'. DefaultExecutor.transformRequest only injected/cleared stream_options on the streaming branch and never stripped a client-sent value when stream=false. Add a !stream strip branch; the streaming injection path is unchanged. Global to openai-compat providers. * fix(qwen-web): cookie validation false-positive - check response body for user object (#3958) Integrated into release/v3.8.27 * fix(db): persist backup retention days (#3970) Integrated into release/v3.8.27 * 大量UI显示和i18n优化 (#3973) Integrated into release/v3.8.27 * deps: bump the npm_and_yarn group across 1 directory with 2 updates (#3943) Integrated into release/v3.8.27 * deps: bump form-data from 4.0.5 to 4.0.6 (#3944) Integrated into release/v3.8.27 * deps: bump vite from 8.0.5 to 8.0.16 (#3942) Integrated into release/v3.8.27 * chore(quality): re-baseline validation.ts 4407->4428 (#3958 qwen body-check) The qwen-web validation body-check merged in #3958 pushed validation.ts past its frozen size on the integrated release tip. Bump the baseline with justification; no logic is separately extractable from the existing qwen-web validation branch. * deps: bump the production group with 13 updates (#3915) Integrated into release/v3.8.27 — low-risk group (playwright 1.60→1.61 minor + transitive patches; fumadocs-core 16.9→16.10 minor). * chore(deps): ignore jscpd major bumps (v5 Rust rewrite breaks the duplication gate) Our duplication ratchet (scripts/check/check-duplication.mjs) is pinned to jscpd@4 and parses jscpd-report.json against a frozen baseline. jscpd v5 is a native Rust binary with no Node.js API and a different report/bin, so a major bump would break the gate. Migrate deliberately, not via dependabot. Closes the noise from #3916. * fix(perplexity-web): parse schematized diff_block stream so answers aren't empty (#4001) Integrated into release/v3.8.27 — schematized diff_block parsing follow-up to #3938. * refactor: modularize providerRegistry.ts into 159 individual provider plugins (#3993) Modularize provider registry (#3594). Integrated into release/v3.8.27 after rebase + behavior-preservation verification (provider-consistency gate 159/232/0, typecheck, registry tests, build 556/556). Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com> * fix(registry): restore byteplus + mimocode dropped by #3993 modularization The provider-registry modularization (#3993) was cut from a base predating the byteplus (#3877) and mimocode (#3837) registry entries, so merging it silently dropped both providers (getRegistryEntry returned undefined → validation reported 'not supported'). Re-add them as registry modules in the new structure; registered count 159→161, provider-consistency 161/232/0. Also align the pre-existing qwen-web validator test to #3958: since the validator now requires a real `user` object in the 200 body, the mock must carry one. * refactor: modularize schemas (non-stacked) (#3988) Modularize validation schemas (#3594). Integrated into release/v3.8.27 after rebase (reconciled the merged hiddenSidebarGroupLabels #3971 + intelligenceSyncRequestSchema into the new modules) + behavior verification (typecheck, 195 schema/settings/validation tests, build 556/556). Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com> * fix(default-executor): honor custom providerSpecificData.baseUrl for OpenAI-format providers (#4002) Integrated into release/v3.8.27 — honor custom providerSpecificData.baseUrl in DefaultExecutor (openai-format), tested. * feat(openai): honor custom base URL in model discovery + complete openai/codex pricing (#4005) Integrated into release/v3.8.27 — openai model-discovery honors custom base URL (SSRF-guarded) + pricing rows for new openai/codex models. Tested + baselines bumped. * fix(live-ws): bridge sidecar events to dashboard (#4004) Integrated into release/v3.8.27 — repair LiveWS sidecar (startup, same-origin /live-ws, main→sidecar compression.completed bridge, early-msg queue). Fixed the cookie-parse regex (\s) + added a focused unit test; baseline bumped for the non-blocking chatCore bridge. * docs(troubleshooting): note MITM proxy cannot intercept Windows-host apps under WSL (#4003) Integrated into release/v3.8.27 — MITM/WSL troubleshooting note. * fix(repo): untrack accidentally-committed root node_modules symlink + gitignore it A worktree node_modules symlink (-> the main checkout's node_modules) was staged by a `git add -A` during the #3988 merge and committed into05213ac6a. The symlink points at the repo's own node_modules path, so checking it out turns the main checkout's node_modules into a self-referential symlink (breaking tsx/all node ops). Untrack it and add a root-anchored /node_modules ignore so the symlink form can't be re-committed (the existing 'node_modules/' only matches directories). * fix(quality): allowlist socks dep (declared by #4004, never allowlisted) socks@^2.8.7 was added to package.json in #4004 (LiveWS sidecar,02302131f) as a phantom-dep cleanup but never added to dependency-allowlist.json, so check:deps has been red on the release tip ever since. socks is the standard SOCKS proxy client (dep of fetch-socks), legitimate and years old. * feat(sse): real LLMLingua-2 ONNX compression engine (stable) (#4014) Integrated into release/v3.8.27. Adjustments before merge: - Synced with the current release tip (was 11 commits behind). - Added the 3 LLMLingua-2 ONNX optional-runtime deps to dependency-allowlist.json (@atjsh/llmlingua-2, @tensorflow/tfjs, js-tiktoken) — the only gate that was red. - socks was allowlisted directly on release (separate fix d7db5c73d; it was declared by #4004 but never allowlisted, leaving check:deps red release-wide). Verified locally: check:deps OK, file-size OK, public-creds OK, provider-consistency 161/232/0, typecheck:core clean, 24/24 LLMLingua tests pass. The only remaining Fast-QG red is the pre-existing #3972 orphan test (request-logger-autorefresh-visibility-3972.test.tsx), which is release-wide and unrelated to this PR. * test(dashboard): rehome #3972 logs auto-refresh test so a runner collects it tests/unit/request-logger-autorefresh-visibility-3972.test.tsx (added by #3972 via #3997) sat at the top level of tests/unit/ as a .tsx vitest test, which NO runner collects: the node runner only globs *.test.ts, and test:vitest:ui only runs tests/unit/ui. So the #3972 regression guard never executed in CI and check:test-discovery was red release-wide. Move it under tests/unit/ui/ (the collected vitest:ui path) and fix the relative import depth. Verified: the test now runs and passes (2/2), and check:test-discovery is green. * feat(compression): capture per-engine analytics (#3960) + Lite schema fix (#3952) (#4018) Captures the net-new value from #3960 (per-engine breakdown analytics) and #3952 (Lite engine schema fix) onto release/v3.8.27. Fast QG green; 622/622 compression+analytics tests pass. * fix(sse): guard model-less registry entries in getUnsupportedParams (mimocode) (#4015) Real bugfix: guard model-less registry entries (mimocode) in getUnsupportedParams so handleChatCore no longer throws 'entry.models is not iterable' / reports 'All models failed' for unrelated requests. Includes a regression test. Fast QG green. * feat(ci): Quality Gate v2 — Onda 0 + Onda 1 (gate flips, TIA, SAST, DAST-smoke, mutation infra) (#4016) * docs(ops): add quality-gate assessment + replication playbook (Fase 9 foundation) * feat(ci): flip oasdiff breaking-change gate to blocking (ratchet) * docs(ops): deliver main branch-protection ruleset for owner to apply * fix(ci): run typecheck:core in PR->release fast-gates (close fast-gates hole, part 1) * perf(mutation): enable Stryker incremental mode + cache (scales the 60/80 rollout) * feat(ci): commit CodeQL advanced config (security-extended), replacing default-setup * feat(ci): version semgrep SAST workflow (owasp/secrets), advisory * feat(quality): TIA test-impact map builder (import-graph; map built at runtime, gitignored) * feat(quality): TIA impacted-test selector with run-all fail-safe * fix(ci): run TIA-impacted unit tests in PR->release fast-gates (build map at runtime, fail-safe full) * feat(ci): DAST-smoke per-PR (schemathesis subset + promptfoo injection-guard, blocking) * fix(ci): unbreak Fase 9 PR CI (MDX frontmatter, CodeQL conflict, dast-smoke advisory) - Add MDX frontmatter to docs/ops/{BRANCH_PROTECTION_MAIN,QUALITY_GATE_PLAYBOOK}.md. fumadocs rejects frontmatter-less docs -> 'npm run build' failed -> broke dast-smoke's build step (the release fast-gates never runs build, so this only surfaced on the PR). - codeql.yml: workflow_dispatch-only until the owner switches repo CodeQL Default->Advanced (advanced configs cannot be processed while default setup is enabled; documented inline). - dast-smoke.yml: job-level continue-on-error (advisory) so this brand-new gate matures before it blocks (repo convention: advisory -> blocking). * ci(quality): make TIA unit-test step advisory until release test-debt is cleared release/v3.8.27 carries ~17 pre-existing failing unit tests (budget #3537, apiKey #3552, several Zod schemas, Puter/Qwen executors, mimocode entry, etc.) unrelated to this PR — the new 'run tests on PR->release' gate surfaced them. Per the repo's advisory->blocking convention, this step enters advisory (it still runs + reports) so pre-existing debt doesn't block the gate program. typecheck:core stays blocking. Flip to blocking (remove continue-on-error) once the release suite is green. * fix(sse): preserve Kiro streaming finish_reason tool_calls (#3980) (#4025) * fix(guardrails): preserve original image when vision-bridge describe fails (#4012) (#4026) * feat(api): advertise combo capabilities on import surfaces (#3979) (#4027) * feat(sse): delegated Anthropic Context Editing for Claude (clear_tool_uses) (#4021) Opt-in Claude-only delegated compression: injects context_management.clear_tool_uses_20250919 at the Claude pre-serialization chokepoint (composes with clear_thinking, thinking first), threaded via ExecuteInput from handleChatCore. Pure edit-builder + 11 tests (7 unit + 4 e2e fetch-capture). Beta context-management-2025-06-27 already advertised; allowlist done. Telemetry/400-fallback/claude-web coverage deferred. * fix(opencode): map x-session-affinity to x-opencode-session for custom providers (#4022) (#4028) * fix(dashboard): Playground Compare tab loading + HTTP method guard (#4024) randomUUID non-HTTPS fallback + static CompareTab import; raw HTTP TRACE->405 method guard wired into dev + standalone servers. Integrated into release/v3.8.27. * refactor(dashboard): settings UI layout + API Keys naming (#4020) Presentation/relabel refactor of the Settings dashboard (API Manager -> API Keys), card relocations, Toggle adoption, present-but-disabled engine steps. Auth-file changes are string/comment-only (no behavior change). Integrated into release/v3.8.27. * fix: restore unit regressions dropped by lossy schema/registry modularizations (#4030) Restores schema fields (combo reasoningTokenBuffer, budget-0 #3537, openrouter preset, proxy family #3777, resilience degradation/providerCooldown), qwen-web v2 endpoint+catalog, mimocode models key — all dropped by #3988/#3993 — and aligns 3 tests to #3941/#3993. Verified: 8 failing regression tests on release tip -> 131/131 green on this branch. Integrated into release/v3.8.27. * fix(api): return 400 (not 500) for malformed JSON on /api/auth/login (#4031) Wrap request.json() so a malformed/non-JSON login body returns a structured 400 instead of falling through to the 500 catch. Fixes the schemathesis high-risk-endpoint DAST finding (verified: schemathesis step now passes). +TDD test. Integrated into release/v3.8.27. * feat(dashboard): real circuit-breaker state in the Combo Live cascade (U1b) (#4029) Overlays real provider circuit-breaker state (GET /api/monitoring/health) onto the Combo Live cascade as a 'CB: OPEN · 41s' badge. Pure enrichRunWithBreakers + fail-soft useProviderBreakerHealth poll; graceful when health is absent. +13 tests. Integrated into release/v3.8.27. * Fix promptfoo security assertion parsing (#4032) * chore(deps): dependabot security bumps + drop unused gray-matter (#4036) Integrated into release/v3.8.27 — dependabot security bumps (form-data/js-yaml/protobufjs/dompurify/hono) + drop unused gray-matter. Unblocks the npm audit:deps gate (Lint) branch-wide. * fix(ci): scope TIA to node:test unit files only (mirror test:unit glob) (#4035) Integrated into release/v3.8.27 — scopes the advisory TIA step to the test:unit node:test glob, fixing the 99 false failures. +4 TDD. * Refine compression settings, storage labels, and sidebar grouping (#4033) Integrated into release/v3.8.27 — relocate Token Saver into Compression Settings (controlled component), reorder Security/Authz tabs, storage labels + i18n relabel. Thanks @rdself! * [codex] add per-key local usage command (#4034) Integrated into release/v3.8.27 — per-key local @@om-usage command (cached quota, no upstream routing). Rebased onto modularized schemas/keys.ts + file-size rebaseline. Thanks @Witroch4! * chore(release): reconcile v3.8.27 CHANGELOG + i18n mirrors * ci(quality): unblock v3.8.27 release gates (zizmor pin + test-masking allowlist) - zizmor ratchet (151→139, no regression): SHA-pin every action ref ADDED this cycle — codeql/dast-smoke/semgrep (3 new workflows) + trivy-action (docker-publish) + actions/cache (nightly-mutation). Pre-existing tag refs keep the repo convention. - test-masking: add config/quality/test-masking-allowlist.json + allowlist support in check-test-masking.mjs (exempts ONLY the net-assert-reduction signal; tautology/skip/ deletion still fire). Allowlists 2 verified-legitimate reductions: appearance-widget-settings-schema (#4033 removed showTokenSaverOnEndpoint field) and dashboard-shell-tabs (#3973 tabs→redirect refactor, asserts replaced). +4 gate tests. * test(quality): reword test-masking self-test comments to avoid literal masking patterns The added allowlist-test comments contained the literal strings 'assert.ok(true)' and '.skip' which the masking detector's own regexes match as text — making the gate flag its own test file (net +1 tautology/skip/extended-tautology vs main). Reworded to plain prose ('a new tautology', 'a new skip marker'); test logic unchanged (24/24 pass). * fix(quality): unblock v3.8.27 release — align 3 stale tests + restore modularized settings-schema parity Release-PR full CI surfaced 3 deterministic test failures (no live product regression), all stale vs legitimate cycle changes: - settings-schema parity (#3988): the modularized updateSettingsSchema barrel (schemas/settings.ts) had diverged from the canonical settingsSchemas.ts (45 vs 85 fields — 40 dropped + 6 extra), a lossy-modularization dead-code copy. Re-export from the canonical source so the barrel can never diverge again (runtime already uses canonical). Parity test now passes. - api-manager permissions modal: #4034 added a 4th self-service switch (per-key usage allowance); a11y invariant (every switch type="button") still holds. Updated the static count 3 -> 4. - pack-artifact policy: dist/http-method-guard.cjs became a required runtime path; added it to the test's expected missing-paths list. Also documents the gate gap for Fase 9 (QUALITY_GATE_PLAYBOOK Parte 6): G1 run the deterministic unit layer + test-masking on PR->release (not just PR->main), G2 a modularization-parity gate (would have caught the #3988 drop at its PR), G3 flake quarantine. Env flakes (LiveWS startup timeout, integration server-startup cascade) are pre-existing/CI-env, triaged separately. --------- Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: Veier04 <118300867+Veier04@users.noreply.github.com> Co-authored-by: Felipe Sartori <felipesartori.ti@gmail.com> Co-authored-by: WormAlien <164898390+WormAlien@users.noreply.github.com> Co-authored-by: thezukiru <121331256+thezukiru@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: NOXX - Commiter <artur1992123@mail.ru> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: Demiurge The Single <megamen932@gmail.com> Co-authored-by: Witroch4 <witalo_rocha@hotmail.com>
This commit is contained in:
committed by
GitHub
parent
c9b5b1a892
commit
fa367dd99e
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import Card from "./Card";
|
||||
|
||||
export interface ModelMapping {
|
||||
id: string;
|
||||
@@ -141,13 +142,17 @@ export default function ModelRoutingSection({ combos: externalCombos }: { combos
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/50 dark:bg-white/[0.02] p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="material-symbols-outlined text-primary text-[18px]">route</span>
|
||||
<Card>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg bg-primary/10 text-primary">
|
||||
<span className="material-symbols-outlined text-[20px]" aria-hidden="true">
|
||||
route
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold">{t("modelRoutingTitle")}</h3>
|
||||
<p className="text-[11px] text-text-muted">{t("modelRoutingDesc")}</p>
|
||||
<h3 className="text-lg font-semibold">{t("modelRoutingTitle")}</h3>
|
||||
<p className="text-sm text-text-muted">{t("modelRoutingDesc")}</p>
|
||||
</div>
|
||||
</div>
|
||||
{!adding && (
|
||||
@@ -313,6 +318,6 @@ export default function ModelRoutingSection({ combos: externalCombos }: { combos
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import Card from "./Card";
|
||||
import Button from "./Button";
|
||||
import DistributeProxiesButton from "./DistributeProxiesButton";
|
||||
import NoAuthProviderToggle from "./NoAuthProviderToggle";
|
||||
|
||||
interface NoAuthAccountCardProps {
|
||||
providerId: string;
|
||||
@@ -12,6 +13,9 @@ interface NoAuthAccountCardProps {
|
||||
dataKey?: string;
|
||||
description?: string;
|
||||
addLabel?: string;
|
||||
enabled?: boolean;
|
||||
savingEnabled?: boolean;
|
||||
onEnabledChange?: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
interface Connection {
|
||||
@@ -48,6 +52,9 @@ export default function NoAuthAccountCard({
|
||||
dataKey = "fingerprints",
|
||||
description = "Ready to use — no signup needed. Add accounts for rate-limit rotation.",
|
||||
addLabel = "Add Account",
|
||||
enabled = true,
|
||||
savingEnabled = false,
|
||||
onEnabledChange,
|
||||
}: NoAuthAccountCardProps) {
|
||||
const [connections, setConnections] = useState<Connection[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -94,9 +101,7 @@ export default function NoAuthAccountCard({
|
||||
}
|
||||
}, [proxyAccountId]);
|
||||
|
||||
const allAccountIds = connections.flatMap(
|
||||
(c) => c.providerSpecificData?.[dataKey] || []
|
||||
);
|
||||
const allAccountIds = connections.flatMap((c) => c.providerSpecificData?.[dataKey] || []);
|
||||
|
||||
const conn = connections[0];
|
||||
const accountProxies = getAccountProxies(conn);
|
||||
@@ -251,30 +256,38 @@ export default function NoAuthAccountCard({
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<div className="inline-flex shrink-0 items-center justify-center w-10 h-10 rounded-full bg-green-500/10 text-green-500">
|
||||
<span className="material-symbols-outlined text-[20px]">lock_open</span>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">No authentication required</p>
|
||||
<p className="text-xs text-text-muted">{description}</p>
|
||||
<div className="mb-3 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div className="inline-flex shrink-0 items-center justify-center w-10 h-10 rounded-full bg-green-500/10 text-green-500">
|
||||
<span className="material-symbols-outlined text-[20px]">lock_open</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">No authentication required</p>
|
||||
<p className="text-xs text-text-muted">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<NoAuthProviderToggle
|
||||
className="w-full justify-end sm:w-auto"
|
||||
enabled={enabled}
|
||||
saving={savingEnabled}
|
||||
onEnabledChange={onEnabledChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-3 mt-3">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm font-medium">
|
||||
Accounts ({loading ? "..." : allAccountIds.length})
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{!loading && allAccountIds.length > 0 && (
|
||||
<DistributeProxiesButton
|
||||
onDistribute={handleDistributeProxies}
|
||||
disabled={adding}
|
||||
disabled={adding || !enabled}
|
||||
size="sm"
|
||||
/>
|
||||
)}
|
||||
<Button size="sm" icon="add" onClick={handleAddAccount} disabled={adding}>
|
||||
<Button size="sm" icon="add" onClick={handleAddAccount} disabled={adding || !enabled}>
|
||||
{adding ? "Adding..." : addLabel}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -305,9 +318,13 @@ export default function NoAuthAccountCard({
|
||||
<button
|
||||
onClick={() => openProxyConfig(id)}
|
||||
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-colors"
|
||||
title={proxy ? `${proxy.type}://${proxy.host}:${proxy.port}` : "Configure proxy"}
|
||||
title={
|
||||
proxy ? `${proxy.type}://${proxy.host}:${proxy.port}` : "Configure proxy"
|
||||
}
|
||||
>
|
||||
<span className={`material-symbols-outlined text-[14px] ${proxy ? "text-blue-400" : "text-text-muted"}`}>
|
||||
<span
|
||||
className={`material-symbols-outlined text-[14px] ${proxy ? "text-blue-400" : "text-text-muted"}`}
|
||||
>
|
||||
{proxy ? "shield" : "shield"}
|
||||
</span>
|
||||
<span className={proxy ? "text-blue-400" : "text-text-muted"}>
|
||||
@@ -328,9 +345,7 @@ export default function NoAuthAccountCard({
|
||||
ref={popoverRef}
|
||||
className="absolute right-0 top-full z-50 mt-1 w-80 rounded-lg border border-black/10 dark:border-white/10 bg-surface shadow-lg p-4"
|
||||
>
|
||||
<p className="text-sm font-medium mb-3">
|
||||
Proxy for Account {i + 1}
|
||||
</p>
|
||||
<p className="text-sm font-medium mb-3">Proxy for Account {i + 1}</p>
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<select
|
||||
@@ -339,7 +354,9 @@ export default function NoAuthAccountCard({
|
||||
className="rounded-md border border-black/10 dark:border-white/10 bg-bg px-2.5 py-1.5 text-xs flex-shrink-0"
|
||||
>
|
||||
{PROXY_TYPES.map((t) => (
|
||||
<option key={t.value} value={t.value}>{t.label}</option>
|
||||
<option key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
|
||||
@@ -1,20 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import Card from "./Card";
|
||||
import NoAuthProviderToggle from "./NoAuthProviderToggle";
|
||||
|
||||
export default function NoAuthProviderCard() {
|
||||
interface NoAuthProviderCardProps {
|
||||
enabled?: boolean;
|
||||
saving?: boolean;
|
||||
onEnabledChange?: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
export default function NoAuthProviderCard({
|
||||
enabled = true,
|
||||
saving = false,
|
||||
onEnabledChange,
|
||||
}: NoAuthProviderCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="inline-flex shrink-0 items-center justify-center w-10 h-10 rounded-full bg-green-500/10 text-green-500">
|
||||
<span className="material-symbols-outlined text-[20px]">lock_open</span>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">No authentication required</p>
|
||||
<p className="text-xs text-text-muted">
|
||||
This provider is ready to use immediately — no signup or API key needed.
|
||||
</p>
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div className="inline-flex shrink-0 items-center justify-center w-10 h-10 rounded-full bg-green-500/10 text-green-500">
|
||||
<span className="material-symbols-outlined text-[20px]">lock_open</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">No authentication required</p>
|
||||
<p className="text-xs text-text-muted">
|
||||
This provider is ready to use immediately — no signup or API key needed.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<NoAuthProviderToggle
|
||||
className="w-full justify-end sm:w-auto"
|
||||
enabled={enabled}
|
||||
saving={saving}
|
||||
onEnabledChange={onEnabledChange}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
|
||||
36
src/shared/components/NoAuthProviderToggle.tsx
Normal file
36
src/shared/components/NoAuthProviderToggle.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/shared/utils/cn";
|
||||
import Toggle from "./Toggle";
|
||||
|
||||
interface NoAuthProviderToggleProps {
|
||||
enabled: boolean;
|
||||
saving?: boolean;
|
||||
onEnabledChange?: (enabled: boolean) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function NoAuthProviderToggle({
|
||||
enabled,
|
||||
saving = false,
|
||||
onEnabledChange,
|
||||
className,
|
||||
}: NoAuthProviderToggleProps) {
|
||||
if (!onEnabledChange) return null;
|
||||
|
||||
return (
|
||||
<div className={cn("inline-flex items-center gap-2 rounded-md px-1 py-1", className)}>
|
||||
<span className="text-sm font-medium text-text-main">
|
||||
{saving ? "Saving" : enabled ? "Enabled" : "Disabled"}
|
||||
</span>
|
||||
<Toggle
|
||||
size="lg"
|
||||
checked={enabled}
|
||||
disabled={saving}
|
||||
onChange={onEnabledChange}
|
||||
ariaLabel="Toggle no-auth provider"
|
||||
title={enabled ? "Disable provider" : "Enable provider"}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,14 @@ import {
|
||||
truncateUrl,
|
||||
} from "@/shared/utils/formatting";
|
||||
import { getProviderDisplayLabel } from "@/shared/utils/providerDisplayLabel";
|
||||
import {
|
||||
LOG_TABLE_CLASS,
|
||||
LOG_TABLE_HEAD_CLASS,
|
||||
LOG_TABLE_HEADER_BG_STYLE,
|
||||
LOG_TABLE_HEADER_CELL_CLASS,
|
||||
LOG_TABLE_HEADER_CELL_RIGHT_CLASS,
|
||||
LOG_TABLE_ROW_CLASS,
|
||||
} from "./logTableStyles";
|
||||
|
||||
const PROXY_COLUMN_KEYS = [
|
||||
"status",
|
||||
@@ -396,64 +404,38 @@ export default function ProxyLogger() {
|
||||
) : sortedLogs.length === 0 ? (
|
||||
<div className="p-8 text-center text-text-muted">{t("noMatchingLogs")}</div>
|
||||
) : (
|
||||
<table className="w-full text-left border-collapse text-xs">
|
||||
<thead
|
||||
className="sticky top-0 z-10"
|
||||
style={{ backgroundColor: "var(--bg-primary, #0f1117)" }}
|
||||
>
|
||||
<tr
|
||||
className="border-b border-border"
|
||||
style={{ backgroundColor: "var(--bg-primary, #0f1117)" }}
|
||||
>
|
||||
<table className={LOG_TABLE_CLASS}>
|
||||
<thead className={LOG_TABLE_HEAD_CLASS} style={LOG_TABLE_HEADER_BG_STYLE}>
|
||||
<tr className={LOG_TABLE_ROW_CLASS} style={LOG_TABLE_HEADER_BG_STYLE}>
|
||||
{visibleColumns.status && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colStatus")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colStatus")}</th>
|
||||
)}
|
||||
{visibleColumns.proxy && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colProxy")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colProxy")}</th>
|
||||
)}
|
||||
{visibleColumns.tls && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colTls")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colTls")}</th>
|
||||
)}
|
||||
{visibleColumns.type && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colType")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colType")}</th>
|
||||
)}
|
||||
{visibleColumns.level && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colLevel")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colLevel")}</th>
|
||||
)}
|
||||
{visibleColumns.provider && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colProvider")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colProvider")}</th>
|
||||
)}
|
||||
{visibleColumns.target && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colTarget")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colTarget")}</th>
|
||||
)}
|
||||
{visibleColumns.latency && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
|
||||
{t("colLatency")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_RIGHT_CLASS}>{t("colLatency")}</th>
|
||||
)}
|
||||
{visibleColumns.ip && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("colClientIp")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("colClientIp")}</th>
|
||||
)}
|
||||
{visibleColumns.time && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
|
||||
{t("colTime")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_RIGHT_CLASS}>{t("colTime")}</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -480,7 +462,7 @@ export default function ProxyLogger() {
|
||||
<tr
|
||||
key={log.id}
|
||||
onClick={() => setSelectedLog(selectedLog?.id === log.id ? null : log)}
|
||||
className={`cursor-pointer hover:bg-primary/5 transition-colors ${isError ? "bg-red-500/5" : ""}`}
|
||||
className={`cursor-pointer hover:bg-sky-500/10 dark:hover:bg-sky-400/10 transition-colors ${isError ? "bg-red-500/5" : ""}`}
|
||||
>
|
||||
{visibleColumns.status && (
|
||||
<td className="px-3 py-2">
|
||||
|
||||
@@ -39,6 +39,14 @@ import {
|
||||
readSavedRefreshIntervalSec,
|
||||
writeSavedRefreshIntervalSec,
|
||||
} from "./requestLoggerPreferences";
|
||||
import {
|
||||
LOG_TABLE_CLASS,
|
||||
LOG_TABLE_HEAD_CLASS,
|
||||
LOG_TABLE_HEADER_BG_STYLE,
|
||||
LOG_TABLE_HEADER_CELL_CLASS,
|
||||
LOG_TABLE_HEADER_CELL_RIGHT_CLASS,
|
||||
LOG_TABLE_ROW_CLASS,
|
||||
} from "./logTableStyles";
|
||||
|
||||
// Number of call-log rows fetched per page. The viewer grows its window by this
|
||||
// amount on "Load more" / infinite scroll so users can browse past the first
|
||||
@@ -283,7 +291,12 @@ const RequestLoggerV2 = forwardRef<RequestLoggerV2Handle, { initialSelectedId?:
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
if (!selectedLog && shouldAutoRefresh(recording, limit, PAGE_SIZE)) {
|
||||
intervalRef.current = setInterval(() => {
|
||||
if (visibleRef.current) fetchLogs(false);
|
||||
// #3972: read live visibility each tick, not a mount-time ref. A tab
|
||||
// mounted while "hidden" with no later `visibilitychange` left the ref
|
||||
// false forever, so auto-refresh never ran (only the manual button did).
|
||||
if (typeof document === "undefined" || document.visibilityState === "visible") {
|
||||
fetchLogs(false);
|
||||
}
|
||||
}, refreshIntervalSec * 1000);
|
||||
}
|
||||
return () => {
|
||||
@@ -930,79 +943,47 @@ const RequestLoggerV2 = forwardRef<RequestLoggerV2Handle, { initialSelectedId?:
|
||||
) : sortedLogs.length === 0 ? (
|
||||
<div className="p-8 text-center text-text-muted">{t("noMatchingLogs")}</div>
|
||||
) : (
|
||||
<table className="w-full text-left border-collapse text-xs">
|
||||
<thead
|
||||
className="sticky top-0 z-10"
|
||||
style={{ backgroundColor: "var(--color-bg, #fff)" }}
|
||||
>
|
||||
<tr
|
||||
className="border-b border-border"
|
||||
style={{ backgroundColor: "var(--color-bg, #fff)" }}
|
||||
>
|
||||
<table className={LOG_TABLE_CLASS}>
|
||||
<thead className={LOG_TABLE_HEAD_CLASS} style={LOG_TABLE_HEADER_BG_STYLE}>
|
||||
<tr className={LOG_TABLE_ROW_CLASS} style={LOG_TABLE_HEADER_BG_STYLE}>
|
||||
{visibleColumns.status && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.status")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.status")}</th>
|
||||
)}
|
||||
{visibleColumns.cacheSource && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.cacheSource")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.cacheSource")}</th>
|
||||
)}
|
||||
{visibleColumns.model && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.model")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.model")}</th>
|
||||
)}
|
||||
{visibleColumns.requestedModel && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.requested")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.requested")}</th>
|
||||
)}
|
||||
{visibleColumns.provider && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.provider")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.provider")}</th>
|
||||
)}
|
||||
{visibleColumns.protocol && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.protocol")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.protocol")}</th>
|
||||
)}
|
||||
{visibleColumns.account && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.account")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.account")}</th>
|
||||
)}
|
||||
{visibleColumns.apiKey && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.apiKey")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.apiKey")}</th>
|
||||
)}
|
||||
{visibleColumns.combo && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
|
||||
{t("columns.combo")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_CLASS}>{t("columns.combo")}</th>
|
||||
)}
|
||||
{visibleColumns.tokens && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
|
||||
{t("columns.tokens")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_RIGHT_CLASS}>{t("columns.tokens")}</th>
|
||||
)}
|
||||
{visibleColumns.tps && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
|
||||
{t("columns.tps")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_RIGHT_CLASS}>{t("columns.tps")}</th>
|
||||
)}
|
||||
{visibleColumns.duration && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
|
||||
{t("columns.duration")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_RIGHT_CLASS}>{t("columns.duration")}</th>
|
||||
)}
|
||||
{visibleColumns.time && (
|
||||
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
|
||||
{t("columns.time")}
|
||||
</th>
|
||||
<th className={LOG_TABLE_HEADER_CELL_RIGHT_CLASS}>{t("columns.time")}</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
@@ -11,13 +11,16 @@ import Button from "./Button";
|
||||
import { ConfirmModal } from "./Modal";
|
||||
import CloudSyncStatus from "./CloudSyncStatus";
|
||||
import { useTranslations } from "next-intl";
|
||||
import {
|
||||
HIDDEN_SIDEBAR_GROUP_LABELS_SETTING_KEY,
|
||||
normalizeHiddenSidebarGroupLabels,
|
||||
} from "@/shared/constants/sidebarGroupVisibility";
|
||||
import {
|
||||
HIDDEN_SIDEBAR_ITEMS_SETTING_KEY,
|
||||
SIDEBAR_SETTINGS_UPDATED_EVENT,
|
||||
SIDEBAR_SECTION_ORDER_KEY,
|
||||
SIDEBAR_ITEM_ORDER_KEY,
|
||||
SIDEBAR_SECTIONS,
|
||||
getSectionItems,
|
||||
normalizeHiddenSidebarItems,
|
||||
applySectionOrder,
|
||||
applyItemOrder,
|
||||
@@ -75,6 +78,7 @@ export default function Sidebar({
|
||||
const [isDisconnected, setIsDisconnected] = useState(false);
|
||||
const [showDebug, setShowDebug] = useState(false);
|
||||
const [hiddenSidebarItems, setHiddenSidebarItems] = useState<string[]>([]);
|
||||
const [hiddenSidebarGroupLabels, setHiddenSidebarGroupLabels] = useState<string[]>([]);
|
||||
const [sidebarSectionOrder, setSidebarSectionOrder] = useState<SidebarSectionId[]>([]);
|
||||
const [sidebarItemOrder, setSidebarItemOrder] = useState<SidebarItemOrder>({});
|
||||
const [customAppName, setCustomAppName] = useState<string | null>(null);
|
||||
@@ -117,6 +121,9 @@ export default function Sidebar({
|
||||
const applySettings = (data) => {
|
||||
setShowDebug(data?.debugMode === true);
|
||||
setHiddenSidebarItems(normalizeHiddenSidebarItems(data?.[HIDDEN_SIDEBAR_ITEMS_SETTING_KEY]));
|
||||
setHiddenSidebarGroupLabels(
|
||||
normalizeHiddenSidebarGroupLabels(data?.[HIDDEN_SIDEBAR_GROUP_LABELS_SETTING_KEY])
|
||||
);
|
||||
setCustomAppName(data?.instanceName || null);
|
||||
setCustomLogo(data?.customLogoBase64 || data?.customLogoUrl || null);
|
||||
};
|
||||
@@ -142,6 +149,11 @@ export default function Sidebar({
|
||||
normalizeHiddenSidebarItems(detail[HIDDEN_SIDEBAR_ITEMS_SETTING_KEY])
|
||||
);
|
||||
}
|
||||
if (HIDDEN_SIDEBAR_GROUP_LABELS_SETTING_KEY in detail) {
|
||||
setHiddenSidebarGroupLabels(
|
||||
normalizeHiddenSidebarGroupLabels(detail[HIDDEN_SIDEBAR_GROUP_LABELS_SETTING_KEY])
|
||||
);
|
||||
}
|
||||
if (SIDEBAR_SECTION_ORDER_KEY in detail && Array.isArray(detail[SIDEBAR_SECTION_ORDER_KEY])) {
|
||||
setSidebarSectionOrder(detail[SIDEBAR_SECTION_ORDER_KEY] as SidebarSectionId[]);
|
||||
}
|
||||
@@ -184,6 +196,7 @@ export default function Sidebar({
|
||||
};
|
||||
|
||||
const hiddenSidebarSet = new Set(hiddenSidebarItems);
|
||||
const hiddenSidebarGroupLabelsSet = new Set(hiddenSidebarGroupLabels);
|
||||
|
||||
const orderedSections = applySectionOrder(
|
||||
SIDEBAR_SECTIONS.filter((section) => section.visibility !== "debug" || showDebug),
|
||||
@@ -209,9 +222,11 @@ export default function Sidebar({
|
||||
return {
|
||||
...child,
|
||||
title: getSidebarLabel(child.titleKey, child.titleFallback),
|
||||
separatorHidden: hiddenSidebarGroupLabelsSet.has(child.id),
|
||||
items,
|
||||
} as SidebarItemGroup & {
|
||||
title: string;
|
||||
separatorHidden: boolean;
|
||||
items: (SidebarItemDefinition & { label: string })[];
|
||||
};
|
||||
}
|
||||
@@ -578,15 +593,17 @@ export default function Sidebar({
|
||||
{section.children.map((child: any) => {
|
||||
if (child.type === "group") {
|
||||
if (child.items.length === 0) return null;
|
||||
const separatorHidden = child.separatorHidden === true;
|
||||
return (
|
||||
<div key={child.id} className="mt-2">
|
||||
{/* Visual sub-group separator */}
|
||||
<div className="flex items-center gap-1.5 px-2 py-0.5 mb-0.5">
|
||||
<div className="h-px flex-1 bg-black/8 dark:bg-white/8" />
|
||||
<span className="text-[8px] font-semibold text-text-muted/40 uppercase tracking-widest">
|
||||
{child.title}
|
||||
</span>
|
||||
</div>
|
||||
<div key={child.id} className={separatorHidden ? "mt-0.5" : "mt-2"}>
|
||||
{!separatorHidden && (
|
||||
<div className="flex items-center gap-1.5 px-2 py-0.5 mb-0.5">
|
||||
<div className="h-px flex-1 bg-black/8 dark:bg-white/8" />
|
||||
<span className="text-[8px] font-semibold text-text-muted/40 uppercase tracking-widest">
|
||||
{child.title}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{child.items.map(renderNavLink)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -73,8 +73,9 @@ export default function Toggle({
|
||||
className={cn(
|
||||
"relative inline-flex shrink-0 cursor-pointer rounded-full",
|
||||
"transition-colors duration-200 ease-in-out",
|
||||
"border shadow-inner",
|
||||
"focus:outline-none focus:ring-1 focus:ring-primary/30",
|
||||
checked ? "bg-primary" : "bg-black/10 dark:bg-white/20",
|
||||
checked ? "border-primary bg-primary" : "border-border bg-surface-2 dark:bg-white/20",
|
||||
sizes[size].track,
|
||||
disabled && "cursor-not-allowed"
|
||||
)}
|
||||
|
||||
@@ -112,7 +112,7 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
let currentConfig: Record<string, unknown> = {};
|
||||
const step = comboData?.pipeline?.find((s) => s.engine === engineId);
|
||||
if (step) {
|
||||
currentEnabled = true;
|
||||
currentEnabled = step.config?.enabled !== false;
|
||||
currentConfig = step.config ?? {};
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
for (const field of foundEngine?.configSchema ?? []) {
|
||||
defaults[field.key] = field.defaultValue;
|
||||
}
|
||||
setConfigState({ ...defaults, ...currentConfig });
|
||||
setConfigState({ ...defaults, ...currentConfig, enabled: currentEnabled });
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
@@ -140,32 +140,40 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
|
||||
async function handleToggle() {
|
||||
const next = !enabled;
|
||||
const nextConfig = { ...configState, enabled: next };
|
||||
setEnabled(next);
|
||||
setConfigState(nextConfig);
|
||||
setToggleError(null);
|
||||
try {
|
||||
const res = await fetch("/api/context/combos/default", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ engineId, enabled: next }),
|
||||
body: JSON.stringify({ engineId, enabled: next, config: nextConfig }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setToggleError("Failed to update engine state.");
|
||||
setEnabled(!next); // revert
|
||||
setConfigState(configState);
|
||||
}
|
||||
} catch {
|
||||
setToggleError("Failed to update engine state.");
|
||||
setEnabled(!next); // revert
|
||||
setConfigState(configState);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
const nextEnabled = typeof configState.enabled === "boolean" ? configState.enabled : enabled;
|
||||
const nextConfig = { ...configState, enabled: nextEnabled };
|
||||
setEnabled(nextEnabled);
|
||||
setConfigState(nextConfig);
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
const res = await fetch("/api/context/combos/default", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ engineId, enabled, config: configState }),
|
||||
body: JSON.stringify({ engineId, enabled: nextEnabled, config: nextConfig }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setSaveError("Failed to save configuration.");
|
||||
@@ -220,6 +228,7 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
}
|
||||
|
||||
const subtitle = engine.metadata?.description ?? engine.description;
|
||||
const visibleConfigSchema = engine.configSchema.filter((field) => field.key !== "enabled");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 p-6 max-w-3xl">
|
||||
@@ -242,9 +251,11 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-border bg-surface p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium text-text">Ativar camada</span>
|
||||
<span className="text-sm font-medium text-text">Enable layer</span>
|
||||
<span className="text-xs text-text-muted">
|
||||
{enabled ? "Esta camada está ativa no pipeline padrão." : "Esta camada está inativa."}
|
||||
{enabled
|
||||
? "This layer is active in the default pipeline."
|
||||
: "This layer is inactive."}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
@@ -253,13 +264,12 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
checked={enabled}
|
||||
onChange={handleToggle}
|
||||
className="h-4 w-4 accent-primary cursor-pointer"
|
||||
aria-label="Ativar camada"
|
||||
aria-label="Enable layer"
|
||||
/>
|
||||
</div>
|
||||
{toggleError && <p className="text-xs text-destructive">{toggleError}</p>}
|
||||
<p className="text-xs text-text-muted" data-testid="stacked-mode-notice">
|
||||
As camadas ativadas rodam quando a compressão está no modo "stacked". Configure
|
||||
em{" "}
|
||||
Enabled layers run when compression is in "stacked" mode. Configure it in{" "}
|
||||
<a href="/dashboard/context/settings" className="underline hover:text-text">
|
||||
Compression Settings
|
||||
</a>
|
||||
@@ -269,19 +279,23 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
|
||||
{/* ── Config form ── */}
|
||||
<div className="flex flex-col gap-3 rounded-lg border border-border bg-surface p-4">
|
||||
<h2 className="text-sm font-semibold text-text">Configuração</h2>
|
||||
<EngineConfigForm
|
||||
schema={engine.configSchema}
|
||||
value={configState}
|
||||
onChange={setConfigState}
|
||||
/>
|
||||
<h2 className="text-sm font-semibold text-text">Configuration</h2>
|
||||
{visibleConfigSchema.length > 0 ? (
|
||||
<EngineConfigForm
|
||||
schema={visibleConfigSchema}
|
||||
value={configState}
|
||||
onChange={setConfigState}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-text-muted">No additional configuration.</p>
|
||||
)}
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="px-4 py-1.5 rounded bg-primary text-primary-foreground text-sm font-medium disabled:opacity-50"
|
||||
>
|
||||
{saving ? "Salvando…" : "Salvar"}
|
||||
{saving ? "Saving..." : "Save"}
|
||||
</button>
|
||||
{saveError && <p className="text-xs text-destructive">{saveError}</p>}
|
||||
</div>
|
||||
@@ -302,20 +316,20 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
disabled={previewLoading}
|
||||
className="px-4 py-1.5 rounded bg-primary text-primary-foreground text-sm font-medium disabled:opacity-50"
|
||||
>
|
||||
{previewLoading ? "Processando…" : "Preview"}
|
||||
{previewLoading ? "Processing..." : "Preview"}
|
||||
</button>
|
||||
</div>
|
||||
{previewError && <p className="text-xs text-destructive">{previewError}</p>}
|
||||
{preview && (
|
||||
<div className="flex gap-4 text-sm pt-1">
|
||||
<span className="text-text-muted">
|
||||
Tokens originais: <strong className="text-text">{preview.originalTokens}</strong>
|
||||
Original tokens: <strong className="text-text">{preview.originalTokens}</strong>
|
||||
</span>
|
||||
<span className="text-text-muted">
|
||||
Tokens comprimidos: <strong className="text-text">{preview.compressedTokens}</strong>
|
||||
Compressed tokens: <strong className="text-text">{preview.compressedTokens}</strong>
|
||||
</span>
|
||||
<span className="text-text-muted">
|
||||
Economia: <strong className="text-primary">{preview.savingsPct.toFixed(1)}%</strong>
|
||||
Savings: <strong className="text-primary">{preview.savingsPct.toFixed(1)}%</strong>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -323,17 +337,20 @@ export function EngineConfigPage({ engineId }: { engineId: string }) {
|
||||
|
||||
{/* ── Analytics strip ── */}
|
||||
<div className="flex flex-col gap-3 rounded-lg border border-border bg-surface p-4">
|
||||
<h2 className="text-sm font-semibold text-text">Últimos 7 dias</h2>
|
||||
<h2 className="text-sm font-semibold text-text">Last 7 days</h2>
|
||||
{analytics && analytics.runs === 0 ? (
|
||||
<p className="text-sm text-text-muted">Sem dados ainda / No data yet</p>
|
||||
<p className="text-sm text-text-muted">No data yet</p>
|
||||
) : analytics ? (
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<StatCard label="Execuções" value={analytics.runs.toLocaleString()} />
|
||||
<StatCard label="Tokens economizados" value={analytics.tokensSaved.toLocaleString()} />
|
||||
<StatCard label="Economia média" value={`${analytics.avgSavingsPercent.toFixed(1)}%`} />
|
||||
<StatCard label="Runs" value={analytics.runs.toLocaleString()} />
|
||||
<StatCard label="Tokens saved" value={analytics.tokensSaved.toLocaleString()} />
|
||||
<StatCard
|
||||
label="Average savings"
|
||||
value={`${analytics.avgSavingsPercent.toFixed(1)}%`}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-text-muted">Sem dados ainda / No data yet</p>
|
||||
<p className="text-sm text-text-muted">No data yet</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
7
src/shared/components/logTableStyles.ts
Normal file
7
src/shared/components/logTableStyles.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export const LOG_TABLE_CLASS = "w-full text-left border-collapse text-xs";
|
||||
export const LOG_TABLE_HEAD_CLASS = "sticky top-0 z-10";
|
||||
export const LOG_TABLE_ROW_CLASS = "border-b border-border";
|
||||
export const LOG_TABLE_HEADER_CELL_CLASS =
|
||||
"px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]";
|
||||
export const LOG_TABLE_HEADER_CELL_RIGHT_CLASS = `${LOG_TABLE_HEADER_CELL_CLASS} text-right`;
|
||||
export const LOG_TABLE_HEADER_BG_STYLE = { backgroundColor: "var(--color-bg, #fff)" } as const;
|
||||
@@ -12,7 +12,7 @@ export interface FeatureFlagDefinition {
|
||||
}
|
||||
|
||||
export const FEATURE_FLAG_DEFINITIONS: FeatureFlagDefinition[] = [
|
||||
// ──────────────── Security (6) ────────────────
|
||||
// ──────────────── Security (9) ────────────────
|
||||
{
|
||||
key: "REQUIRE_API_KEY",
|
||||
label: "Require API Key",
|
||||
@@ -93,8 +93,19 @@ export const FEATURE_FLAG_DEFINITIONS: FeatureFlagDefinition[] = [
|
||||
requiresRestart: false,
|
||||
warningLevel: "info",
|
||||
},
|
||||
|
||||
// ──────────────── Network (5) ────────────────
|
||||
{
|
||||
key: "ALLOW_API_KEY_REVEAL",
|
||||
label: "API Key Reveal",
|
||||
description:
|
||||
"Allow authenticated dashboard users to reveal stored API keys instead of only seeing masked values.",
|
||||
descriptionI18nKey: "featureFlagAllowApiKeyRevealDescription",
|
||||
category: "security",
|
||||
defaultValue: "false",
|
||||
type: "boolean",
|
||||
requiresRestart: false,
|
||||
warningLevel: "danger",
|
||||
},
|
||||
// ──────────────── Network (7) ────────────────
|
||||
{
|
||||
key: "ENABLE_TLS_FINGERPRINT",
|
||||
label: "TLS Fingerprint",
|
||||
@@ -129,6 +140,18 @@ export const FEATURE_FLAG_DEFINITIONS: FeatureFlagDefinition[] = [
|
||||
requiresRestart: false,
|
||||
warningLevel: "caution",
|
||||
},
|
||||
{
|
||||
key: "OMNIROUTE_CONTROL_PLANE_PROXY_DIRECT_FALLBACK",
|
||||
label: "Control-Plane Proxy Direct Fallback",
|
||||
description:
|
||||
"Allow OAuth and provider validation flows to bypass a pinned proxy and connect directly when proxy reachability pre-checks fail. Off by default because this can change account egress IP.",
|
||||
descriptionI18nKey: "featureFlagOmnirouteControlPlaneProxyDirectFallbackDescription",
|
||||
category: "network",
|
||||
defaultValue: "false",
|
||||
type: "boolean",
|
||||
requiresRestart: false,
|
||||
warningLevel: "danger",
|
||||
},
|
||||
{
|
||||
key: "MITM_DISABLE_TLS_VERIFY",
|
||||
label: "Disable TLS Verify (MITM)",
|
||||
|
||||
@@ -3,4 +3,3 @@
|
||||
*/
|
||||
|
||||
export const PIN_PROVIDER_QUOTA_TO_HOME_KEY = "pinProviderQuotaToHome";
|
||||
export const SHOW_TOKEN_SAVER_ON_ENDPOINT_KEY = "showTokenSaverOnEndpoint";
|
||||
|
||||
@@ -257,7 +257,14 @@ export const DEFAULT_PRICING = {
|
||||
reasoning: 9.0,
|
||||
cache_creation: 1.5,
|
||||
},
|
||||
// gpt-5.4 reasoning-effort variants share the gpt-5.4 tier (registry exposes
|
||||
// -xhigh/-high/-medium/-low; without these rows they resolved to $0).
|
||||
"gpt-5.4-xhigh": GPT_5_3_CODEX_PRICING,
|
||||
"gpt-5.4-high": GPT_5_3_CODEX_PRICING,
|
||||
"gpt-5.4-medium": GPT_5_3_CODEX_PRICING,
|
||||
"gpt-5.4-low": GPT_5_3_CODEX_PRICING,
|
||||
// GPT 5.3 Codex family (all same pricing tier)
|
||||
"gpt-5.3-codex-spark": GPT_5_3_CODEX_PRICING,
|
||||
"gpt-5.3-codex": GPT_5_3_CODEX_PRICING,
|
||||
"gpt-5.3-codex-xhigh": GPT_5_3_CODEX_PRICING,
|
||||
"gpt-5.3-codex-high": GPT_5_3_CODEX_PRICING,
|
||||
@@ -645,6 +652,37 @@ export const DEFAULT_PRICING = {
|
||||
// OpenAI
|
||||
openai: {
|
||||
"gpt-5.5": GPT_5_5_PRICING,
|
||||
// gpt-5.4 family (public API tier; mirrors the codex 5.4 tier for the
|
||||
// base/mini, with a lower nano tier). Without these rows the openai
|
||||
// provider's gpt-5.4* models resolved to $0.
|
||||
"gpt-5.4": {
|
||||
input: 5.0,
|
||||
output: 20.0,
|
||||
cached: 2.5,
|
||||
reasoning: 30.0,
|
||||
cache_creation: 5.0,
|
||||
},
|
||||
"gpt-5.4-mini": {
|
||||
input: 1.5,
|
||||
output: 6.0,
|
||||
cached: 0.75,
|
||||
reasoning: 9.0,
|
||||
cache_creation: 1.5,
|
||||
},
|
||||
"gpt-5.4-nano": {
|
||||
input: 0.4,
|
||||
output: 1.6,
|
||||
cached: 0.2,
|
||||
reasoning: 2.4,
|
||||
cache_creation: 0.4,
|
||||
},
|
||||
"gpt-4.1": {
|
||||
input: 2.0,
|
||||
output: 8.0,
|
||||
cached: 0.5,
|
||||
reasoning: 12.0,
|
||||
cache_creation: 2.0,
|
||||
},
|
||||
"gpt-4o": {
|
||||
input: 2.5,
|
||||
output: 10.0,
|
||||
@@ -652,6 +690,13 @@ export const DEFAULT_PRICING = {
|
||||
reasoning: 15.0,
|
||||
cache_creation: 2.5,
|
||||
},
|
||||
"gpt-4o-2024-11-20": {
|
||||
input: 2.5,
|
||||
output: 10.0,
|
||||
cached: 1.25,
|
||||
reasoning: 15.0,
|
||||
cache_creation: 2.5,
|
||||
},
|
||||
"gpt-4o-mini": {
|
||||
input: 0.15,
|
||||
output: 0.6,
|
||||
@@ -659,6 +704,13 @@ export const DEFAULT_PRICING = {
|
||||
reasoning: 0.9,
|
||||
cache_creation: 0.15,
|
||||
},
|
||||
o3: {
|
||||
input: 2.0,
|
||||
output: 8.0,
|
||||
cached: 0.5,
|
||||
reasoning: 12.0,
|
||||
cache_creation: 2.0,
|
||||
},
|
||||
"gpt-4-turbo": {
|
||||
input: 10.0,
|
||||
output: 30.0,
|
||||
|
||||
31
src/shared/constants/sidebarGroupVisibility.ts
Normal file
31
src/shared/constants/sidebarGroupVisibility.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
export const HIDEABLE_SIDEBAR_GROUP_IDS = [
|
||||
"compression-context",
|
||||
"tools",
|
||||
"integrations",
|
||||
"logs",
|
||||
"audit",
|
||||
"system",
|
||||
"gamification",
|
||||
"batch",
|
||||
] as const;
|
||||
|
||||
export type HideableSidebarGroupId = (typeof HIDEABLE_SIDEBAR_GROUP_IDS)[number];
|
||||
|
||||
export const HIDDEN_SIDEBAR_GROUP_LABELS_SETTING_KEY = "hiddenSidebarGroupLabels";
|
||||
|
||||
export function normalizeHiddenSidebarGroupLabels(value: unknown): HideableSidebarGroupId[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
|
||||
const hiddenGroups = new Set<HideableSidebarGroupId>();
|
||||
|
||||
for (const item of value) {
|
||||
if (
|
||||
typeof item === "string" &&
|
||||
HIDEABLE_SIDEBAR_GROUP_IDS.includes(item as HideableSidebarGroupId)
|
||||
) {
|
||||
hiddenGroups.add(item as HideableSidebarGroupId);
|
||||
}
|
||||
}
|
||||
|
||||
return HIDEABLE_SIDEBAR_GROUP_IDS.filter((item) => hiddenGroups.has(item));
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = [
|
||||
// OmniProxy > Integrations
|
||||
"api-endpoints",
|
||||
"webhooks",
|
||||
// OmniProxy > Proxy
|
||||
// OmniProxy — proxy
|
||||
"proxy",
|
||||
"mitm-proxy",
|
||||
"1proxy",
|
||||
@@ -85,7 +85,6 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = [
|
||||
"batch",
|
||||
"batch-files",
|
||||
// Configuration
|
||||
"settings",
|
||||
"settings-general",
|
||||
"settings-appearance",
|
||||
"settings-ai",
|
||||
@@ -406,20 +405,12 @@ const INTEGRATIONS_GROUP: SidebarItemGroup = {
|
||||
],
|
||||
};
|
||||
|
||||
const PROXY_GROUP: SidebarItemGroup = {
|
||||
type: "group",
|
||||
const PROXY_ITEM: SidebarItemDefinition = {
|
||||
id: "proxy",
|
||||
titleKey: "proxyGroup",
|
||||
titleFallback: "Proxy",
|
||||
items: [
|
||||
{
|
||||
id: "proxy",
|
||||
href: "/dashboard/system/proxy",
|
||||
i18nKey: "proxy",
|
||||
subtitleKey: "proxySubtitle",
|
||||
icon: "dns",
|
||||
},
|
||||
],
|
||||
href: "/dashboard/system/proxy",
|
||||
i18nKey: "proxy",
|
||||
subtitleKey: "proxySubtitle",
|
||||
icon: "dns",
|
||||
};
|
||||
|
||||
const ANALYTICS_ITEMS: readonly SidebarItemDefinition[] = [
|
||||
@@ -636,20 +627,12 @@ const DEVTOOLS_ITEMS: readonly SidebarItemDefinition[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const MCP_GROUP: SidebarItemGroup = {
|
||||
type: "group",
|
||||
const MCP_ITEM: SidebarItemDefinition = {
|
||||
id: "mcp",
|
||||
titleKey: "mcp",
|
||||
titleFallback: "MCP Server",
|
||||
items: [
|
||||
{
|
||||
id: "mcp",
|
||||
href: "/dashboard/mcp",
|
||||
i18nKey: "mcp",
|
||||
subtitleKey: "mcpSubtitle",
|
||||
icon: "hub",
|
||||
},
|
||||
],
|
||||
href: "/dashboard/mcp",
|
||||
i18nKey: "mcp",
|
||||
subtitleKey: "mcpSubtitle",
|
||||
icon: "hub",
|
||||
};
|
||||
|
||||
const AGENTIC_FEATURES_ITEMS: readonly SidebarSectionChild[] = [
|
||||
@@ -674,7 +657,7 @@ const AGENTIC_FEATURES_ITEMS: readonly SidebarSectionChild[] = [
|
||||
subtitleKey: "omniSkillsSubtitle",
|
||||
icon: "auto_fix_high",
|
||||
},
|
||||
MCP_GROUP,
|
||||
MCP_ITEM,
|
||||
{
|
||||
id: "a2a",
|
||||
href: "/dashboard/a2a",
|
||||
@@ -755,13 +738,6 @@ const BATCH_GROUP: SidebarItemGroup = {
|
||||
};
|
||||
|
||||
const CONFIGURATION_ITEMS: readonly SidebarItemDefinition[] = [
|
||||
{
|
||||
id: "settings",
|
||||
href: "/dashboard/settings",
|
||||
i18nKey: "settings",
|
||||
subtitleKey: "settingsSubtitle",
|
||||
icon: "settings",
|
||||
},
|
||||
{
|
||||
id: "settings-general",
|
||||
href: "/dashboard/settings/general",
|
||||
@@ -872,7 +848,7 @@ export const SIDEBAR_SECTIONS: readonly SidebarSectionDefinition[] = [
|
||||
COMPRESSION_CONTEXT_GROUP,
|
||||
TOOLS_GROUP,
|
||||
INTEGRATIONS_GROUP,
|
||||
PROXY_GROUP,
|
||||
PROXY_ITEM,
|
||||
],
|
||||
defaultPinned: true,
|
||||
},
|
||||
@@ -955,7 +931,7 @@ const MINIMAL_SHOWN: ReadonlySet<HideableSidebarItemId> = new Set([
|
||||
"costs",
|
||||
"logs",
|
||||
"health",
|
||||
"settings",
|
||||
"settings-general",
|
||||
"settings-sidebar",
|
||||
"docs",
|
||||
"changelog",
|
||||
@@ -988,7 +964,7 @@ const DEVELOPER_SHOWN: ReadonlySet<HideableSidebarItemId> = new Set([
|
||||
"skills",
|
||||
"mcp",
|
||||
"a2a",
|
||||
"settings",
|
||||
"settings-general",
|
||||
"settings-routing",
|
||||
"settings-resilience",
|
||||
"settings-sidebar",
|
||||
@@ -1019,7 +995,6 @@ const ADMIN_SHOWN: ReadonlySet<HideableSidebarItemId> = new Set([
|
||||
"audit",
|
||||
"audit-mcp",
|
||||
"audit-a2a",
|
||||
"settings",
|
||||
"settings-general",
|
||||
"settings-routing",
|
||||
"settings-resilience",
|
||||
|
||||
@@ -17,6 +17,11 @@ const FORCED_VISION_BRIDGE_MODELS = new Set<string>([
|
||||
"opencode-go/qwen3.5-plus",
|
||||
"opencode-zen/deepseek-v4-flash",
|
||||
"opencode-zen/deepseek-v4-pro",
|
||||
// tokenrouter provider: upstream models overstate vision support.
|
||||
// Force Vision Bridge so images are routed through the configured
|
||||
// vision model instead of being passed through to text-only backends.
|
||||
"tokenrouter/deepseek-v4-pro",
|
||||
"tokenrouter/deepseek-v4-flash",
|
||||
]);
|
||||
|
||||
export function isVisionBridgeForcedModel(model: string | null | undefined): boolean {
|
||||
|
||||
@@ -19,7 +19,7 @@ export async function resolveApiKey(
|
||||
/**
|
||||
* Get or create a DB-backed API key for CLI tool setup.
|
||||
* Returns a valid OmniRoute API key (not a placeholder like "sk_omniroute").
|
||||
* Used when user has not explicitly selected a key from API Manager.
|
||||
* Used when user has not explicitly selected a key from API Keys.
|
||||
*/
|
||||
export async function getOrCreateApiKey(apiKeyId?: string | null): Promise<string> {
|
||||
if (apiKeyId) {
|
||||
|
||||
@@ -32,7 +32,7 @@ import { resolveQuotaKeyScope } from "@/lib/quota/quotaKey";
|
||||
import { isQuotaModelName, parseQuotaModelName } from "@/lib/quota/quotaModelNaming";
|
||||
|
||||
// Default to no per-key request cap. API keys can still opt into explicit
|
||||
// limits via Settings/API Manager, while provider/account quota controls remain
|
||||
// limits via Settings/API Keys, while provider/account quota controls remain
|
||||
// responsible for upstream 429 handling and fallback.
|
||||
// Exported so tests can lock in the "no implicit caps" contract from #2289.
|
||||
export const DEFAULT_RATE_LIMITS: RateLimitRule[] = [];
|
||||
@@ -91,6 +91,7 @@ export interface ApiKeyMetadata {
|
||||
rateLimits?: RateLimitRule[] | null;
|
||||
allowedEndpoints?: string[];
|
||||
disableNonPublicModels?: boolean;
|
||||
allowUsageCommand?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -72,6 +72,18 @@ export function isCcCompatibleProviderEnabled(): boolean {
|
||||
return isFeatureFlagEnabled("ENABLE_CC_COMPATIBLE_PROVIDER");
|
||||
}
|
||||
|
||||
export function isApiKeyRevealEnabledFlag(): boolean {
|
||||
try {
|
||||
return isFeatureFlagEnabled("ALLOW_API_KEY_REVEAL");
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[featureFlags] Failed to resolve ALLOW_API_KEY_REVEAL, defaulting to disabled:",
|
||||
error instanceof Error ? error.message : error
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isModelCatalogNamesEnabled(): boolean {
|
||||
return isFeatureFlagEnabled("MODEL_CATALOG_INCLUDE_NAMES");
|
||||
}
|
||||
@@ -79,3 +91,15 @@ export function isModelCatalogNamesEnabled(): boolean {
|
||||
export function isArenaEloSyncEnabled(): boolean {
|
||||
return isFeatureFlagEnabled("ARENA_ELO_SYNC_ENABLED");
|
||||
}
|
||||
|
||||
export function isControlPlaneProxyDirectFallbackEnabled(): boolean {
|
||||
try {
|
||||
return isFeatureFlagEnabled("OMNIROUTE_CONTROL_PLANE_PROXY_DIRECT_FALLBACK");
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[featureFlags] Failed to resolve OMNIROUTE_CONTROL_PLANE_PROXY_DIRECT_FALLBACK, defaulting to disabled:",
|
||||
error instanceof Error ? error.message : error
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ const INJECTION_PATTERNS = [
|
||||
{
|
||||
name: "system_prompt_leak",
|
||||
pattern:
|
||||
/\b(reveal|show|display|print|output|repeat)\s+(your\s+)?(system\s+prompt|instructions?|initial\s+prompt|hidden\s+prompt)/i,
|
||||
/\b(reveals?|shows?|displays?|prints?|outputs?|repeats?)\s+((your|the)\s+)?(system\s+prompt|instructions?|initial\s+prompt|hidden\s+prompt)/i,
|
||||
severity: "high",
|
||||
},
|
||||
{
|
||||
|
||||
55
src/shared/utils/noAuthProviders.ts
Normal file
55
src/shared/utils/noAuthProviders.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { NOAUTH_PROVIDERS, getProviderById } from "@/shared/constants/providers";
|
||||
|
||||
type ProviderWithAlias = { alias?: string };
|
||||
type NoAuthProviderEntry = { id: string; alias?: string };
|
||||
|
||||
const noAuthProviderEntries = Object.values(NOAUTH_PROVIDERS) as NoAuthProviderEntry[];
|
||||
|
||||
export function normalizeBlockedProviderSet(blockedProviders: unknown): Set<string> {
|
||||
const entries = blockedProviders instanceof Set ? Array.from(blockedProviders) : blockedProviders;
|
||||
return new Set(
|
||||
Array.isArray(entries)
|
||||
? entries.filter(
|
||||
(provider): provider is string => typeof provider === "string" && provider.length > 0
|
||||
)
|
||||
: []
|
||||
);
|
||||
}
|
||||
|
||||
export function isProviderBlockedByIdOrAlias(
|
||||
providerId: string,
|
||||
blockedProviders: unknown
|
||||
): boolean {
|
||||
const blockedProviderSet = normalizeBlockedProviderSet(blockedProviders);
|
||||
const provider = getProviderById(providerId) as ProviderWithAlias | undefined;
|
||||
return (
|
||||
blockedProviderSet.has(providerId) ||
|
||||
(typeof provider?.alias === "string" && blockedProviderSet.has(provider.alias))
|
||||
);
|
||||
}
|
||||
|
||||
export function isNoAuthProviderKey(...keys: Array<string | null | undefined>): boolean {
|
||||
return noAuthProviderEntries.some((provider) =>
|
||||
keys.some((key) => key === provider.id || key === provider.alias)
|
||||
);
|
||||
}
|
||||
|
||||
export function isNoAuthProviderBlocked(
|
||||
blockedProviders: unknown,
|
||||
...keys: Array<string | null | undefined>
|
||||
): boolean {
|
||||
const blockedProviderSet = normalizeBlockedProviderSet(blockedProviders);
|
||||
return noAuthProviderEntries.some(
|
||||
(provider) =>
|
||||
keys.some((key) => key === provider.id || key === provider.alias) &&
|
||||
(blockedProviderSet.has(provider.id) ||
|
||||
(typeof provider.alias === "string" && blockedProviderSet.has(provider.alias)))
|
||||
);
|
||||
}
|
||||
|
||||
export function isNoAuthRawProviderPrefix(providerId: string, prefix: string): boolean {
|
||||
const provider = noAuthProviderEntries.find((entry) => entry.id === providerId);
|
||||
return (
|
||||
typeof provider?.alias === "string" && provider.alias !== providerId && prefix === providerId
|
||||
);
|
||||
}
|
||||
@@ -61,6 +61,15 @@ export const languageConfigSchema = z
|
||||
})
|
||||
.strict();
|
||||
|
||||
// Context Editing is a provider-delegated compression mode (Claude/Anthropic only):
|
||||
// the provider clears old tool-use blocks server-side. This config only carries the
|
||||
// on/off flag; the request-time header/body injection is a separate slice.
|
||||
export const contextEditingConfigSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const aggressiveConfigSchema = z
|
||||
.object({
|
||||
thresholds: z
|
||||
@@ -159,6 +168,7 @@ export const compressionSettingsUpdateSchema = z
|
||||
languageConfig: languageConfigSchema.optional(),
|
||||
aggressive: aggressiveConfigSchema.optional(),
|
||||
ultra: ultraConfigSchema.optional(),
|
||||
contextEditing: contextEditingConfigSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
294
src/shared/validation/schemas/apiV1.ts
Normal file
294
src/shared/validation/schemas/apiV1.ts
Normal file
@@ -0,0 +1,294 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
import { modelIdSchema, nonEmptyStringSchema } from "./misc.ts";
|
||||
|
||||
export const embeddingTokenArraySchema = z
|
||||
.array(z.number().int().min(0))
|
||||
.min(1, "input token array must contain at least one item");
|
||||
|
||||
export const embeddingInputSchema = z.union([
|
||||
nonEmptyStringSchema,
|
||||
z.array(nonEmptyStringSchema).min(1, "input must contain at least one item"),
|
||||
embeddingTokenArraySchema,
|
||||
z.array(embeddingTokenArraySchema).min(1, "input must contain at least one item"),
|
||||
]);
|
||||
|
||||
export const chatMessageSchema = z
|
||||
.object({
|
||||
role: z.string().trim().min(1, "messages[].role is required"),
|
||||
content: z.union([nonEmptyStringSchema, z.array(z.unknown()).min(1), z.null()]).optional(),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const countTokensMessageSchema = z
|
||||
.object({
|
||||
content: z.union([
|
||||
nonEmptyStringSchema,
|
||||
z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
type: z.string().optional(),
|
||||
text: z.string().optional(),
|
||||
})
|
||||
.catchall(z.unknown())
|
||||
)
|
||||
.min(1, "messages[].content must contain at least one item"),
|
||||
]),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const v1EmbeddingsSchema = z
|
||||
.object({
|
||||
model: modelIdSchema,
|
||||
input: embeddingInputSchema,
|
||||
dimensions: z.coerce.number().int().positive().optional(),
|
||||
encoding_format: z.enum(["float", "base64"]).optional(),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const v1ImageGenerationSchema = z
|
||||
.object({
|
||||
model: modelIdSchema,
|
||||
prompt: nonEmptyStringSchema.optional(),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const v1AudioSpeechSchema = z
|
||||
.object({
|
||||
model: modelIdSchema,
|
||||
input: nonEmptyStringSchema,
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const v1ModerationSchema = z
|
||||
.object({
|
||||
model: modelIdSchema.optional(),
|
||||
input: z.unknown().refine((value) => {
|
||||
if (value === undefined || value === null) return false;
|
||||
if (typeof value === "string") return value.trim().length > 0;
|
||||
if (Array.isArray(value)) return value.length > 0;
|
||||
return true;
|
||||
}, "Input is required"),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const v1RerankSchema = z
|
||||
.object({
|
||||
model: modelIdSchema,
|
||||
query: nonEmptyStringSchema,
|
||||
documents: z.array(z.unknown()).min(1, "documents must contain at least one item"),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const providerChatCompletionSchema = z
|
||||
.object({
|
||||
model: modelIdSchema,
|
||||
messages: z.array(chatMessageSchema).min(1).optional(),
|
||||
input: z.union([nonEmptyStringSchema, z.array(z.unknown()).min(1)]).optional(),
|
||||
prompt: nonEmptyStringSchema.optional(),
|
||||
})
|
||||
.catchall(z.unknown())
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.messages === undefined && value.input === undefined && value.prompt === undefined) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "messages, input or prompt is required",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const v1CountTokensSchema = z
|
||||
.object({
|
||||
messages: z.array(countTokensMessageSchema).min(1, "messages must contain at least one item"),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
// ── Search Schemas ─────────────────────────────────────────────────────
|
||||
// Unified search request/response schemas. Final contract — all fields optional
|
||||
// with defaults. New features add implementations, not new fields.
|
||||
// Multi-query deferred to POST /v1/search/batch (separate PRD).
|
||||
|
||||
export const v1SearchSchema = z
|
||||
.object({
|
||||
// Core
|
||||
query: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, "Query is required")
|
||||
.max(500, "Query must be 500 characters or fewer"),
|
||||
provider: z
|
||||
.enum([
|
||||
"serper-search",
|
||||
"brave-search",
|
||||
"perplexity-search",
|
||||
"exa-search",
|
||||
"tavily-search",
|
||||
"google-pse-search",
|
||||
"linkup-search",
|
||||
"ollama-search",
|
||||
"searchapi-search",
|
||||
"youcom-search",
|
||||
"searxng-search",
|
||||
"zai-search",
|
||||
])
|
||||
.optional(),
|
||||
max_results: z.coerce.number().int().min(1).max(100).default(5),
|
||||
search_type: z.enum(["web", "news"]).default("web"),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
|
||||
// Locale
|
||||
country: z.string().max(2).toUpperCase().optional(),
|
||||
language: z.string().min(2).max(5).optional(),
|
||||
time_range: z.enum(["any", "day", "week", "month", "year"]).optional(),
|
||||
|
||||
// Content control
|
||||
content: z
|
||||
.object({
|
||||
snippet: z.boolean().default(true),
|
||||
full_page: z.boolean().default(false),
|
||||
format: z.enum(["text", "markdown"]).default("text"),
|
||||
max_characters: z.coerce.number().int().min(100).max(100000).optional(),
|
||||
})
|
||||
.optional(),
|
||||
|
||||
// Filters
|
||||
filters: z
|
||||
.object({
|
||||
include_domains: z.array(z.string().max(253)).max(20).optional(),
|
||||
exclude_domains: z.array(z.string().max(253)).max(20).optional(),
|
||||
safe_search: z.enum(["off", "moderate", "strict"]).optional(),
|
||||
})
|
||||
.optional(),
|
||||
|
||||
// Answer synthesis (Phase 2 — returns null until implemented)
|
||||
synthesis: z
|
||||
.object({
|
||||
strategy: z.enum(["none", "auto", "provider", "internal"]).default("none"),
|
||||
model: z.string().optional(),
|
||||
max_tokens: z.coerce.number().int().min(1).max(4000).optional(),
|
||||
})
|
||||
.optional(),
|
||||
|
||||
// Provider-specific passthrough
|
||||
provider_options: z.record(z.string(), z.unknown()).optional(),
|
||||
|
||||
// Strict mode — reject if provider doesn't support a requested filter
|
||||
strict_filters: z.boolean().default(false),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const searchResultSchema = z.object({
|
||||
title: z.string(),
|
||||
url: z.string(),
|
||||
display_url: z.string().optional(),
|
||||
snippet: z.string(),
|
||||
position: z.number().int().positive(),
|
||||
score: z.number().min(0).max(1).nullable().optional(),
|
||||
published_at: z.string().nullable().optional(),
|
||||
favicon_url: z.string().nullable().optional(),
|
||||
content: z
|
||||
.object({
|
||||
format: z.enum(["text", "markdown"]).optional(),
|
||||
text: z.string().optional(),
|
||||
length: z.number().int().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
metadata: z
|
||||
.object({
|
||||
author: z.string().nullable().optional(),
|
||||
language: z.string().nullable().optional(),
|
||||
source_type: z
|
||||
.enum(["article", "blog", "forum", "video", "academic", "news", "other"])
|
||||
.nullable()
|
||||
.optional(),
|
||||
image_url: z.string().nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
citation: z.object({
|
||||
provider: z.string(),
|
||||
retrieved_at: z.string(),
|
||||
rank: z.number().int().positive(),
|
||||
}),
|
||||
provider_raw: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
});
|
||||
|
||||
export const v1SearchResponseSchema = z.object({
|
||||
id: z.string(),
|
||||
provider: z.string(),
|
||||
query: z.string(),
|
||||
results: z.array(searchResultSchema),
|
||||
cached: z.boolean(),
|
||||
answer: z
|
||||
.object({
|
||||
source: z.enum(["none", "provider", "internal"]).optional(),
|
||||
text: z.string().nullable().optional(),
|
||||
model: z.string().nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
usage: z.object({
|
||||
queries_used: z.number().int().min(0),
|
||||
search_cost_usd: z.number().min(0),
|
||||
llm_tokens: z.number().int().min(0).optional(),
|
||||
}),
|
||||
metrics: z.object({
|
||||
response_time_ms: z.number().int().min(0),
|
||||
upstream_latency_ms: z.number().int().min(0).optional(),
|
||||
gateway_latency_ms: z.number().int().min(0).optional(),
|
||||
total_results_available: z.number().int().nullable(),
|
||||
}),
|
||||
errors: z
|
||||
.array(
|
||||
z.object({
|
||||
provider: z.string(),
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const v1BatchCreateSchema = z.object({
|
||||
input_file_id: z.string().min(1),
|
||||
endpoint: z.enum(SUPPORTED_BATCH_ENDPOINTS),
|
||||
completion_window: z.enum(["24h"]),
|
||||
metadata: z
|
||||
.record(z.string().max(64), z.string().max(512))
|
||||
.refine((m) => Object.keys(m).length <= 16, { message: "metadata may have at most 16 keys" })
|
||||
.optional(),
|
||||
output_expires_after: z
|
||||
.object({
|
||||
anchor: z.enum(["created_at"]),
|
||||
seconds: z.number().int().min(3600).max(2592000),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
// ── Web Fetch ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const v1WebFetchSchema = z.object({
|
||||
url: z.string().url("url must be a valid URL (http/https)"),
|
||||
provider: z.enum(["firecrawl", "jina-reader", "tavily-search"]).optional(),
|
||||
format: z.enum(["markdown", "html", "links", "screenshot"]).default("markdown"),
|
||||
depth: z.union([z.literal(0), z.literal(1), z.literal(2)]).default(0),
|
||||
wait_for_selector: z.string().max(256).optional(),
|
||||
include_metadata: z.boolean().default(false),
|
||||
});
|
||||
216
src/shared/validation/schemas/auth.ts
Normal file
216
src/shared/validation/schemas/auth.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
import { confirmedAccountSchema } from "./misc.ts";
|
||||
|
||||
// ──── Codex Import Schema ────
|
||||
|
||||
export const importCodexAuthSchema = z.object({
|
||||
source: z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("json"), json: z.unknown() }),
|
||||
z.object({
|
||||
kind: z.literal("text"),
|
||||
text: z.string().max(256 * 1024, "Paste content must be under 256 KB"),
|
||||
}),
|
||||
]),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Codex Import Bulk Schema ────
|
||||
|
||||
export const importCodexAuthBulkSchema = z.object({
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
json: z.unknown(),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
})
|
||||
)
|
||||
.min(1, "At least one entry is required")
|
||||
.max(50, "At most 50 entries per bulk import"),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Claude Auth Import Schema ────
|
||||
|
||||
export const importClaudeAuthSchema = z.object({
|
||||
source: z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("json"), json: z.unknown() }),
|
||||
z.object({
|
||||
kind: z.literal("text"),
|
||||
text: z.string().max(256 * 1024, "Paste content must be under 256 KB"),
|
||||
}),
|
||||
]),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Claude Auth Import Bulk Schema ────
|
||||
|
||||
export const importClaudeAuthBulkSchema = z.object({
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
json: z.unknown(),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
})
|
||||
)
|
||||
.min(1, "At least one entry is required")
|
||||
.max(50, "At most 50 entries per bulk import"),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Gemini CLI Auth Import Schema ────
|
||||
|
||||
export const importGeminiAuthSchema = z.object({
|
||||
source: z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("json"), json: z.unknown() }),
|
||||
z.object({
|
||||
kind: z.literal("text"),
|
||||
text: z.string().max(256 * 1024, "oauth_creds.json content exceeds 256KB"),
|
||||
}),
|
||||
]),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Antigravity CLI (`agy`) Auth Import Schema ────
|
||||
// Same source/options shape as gemini-cli; the parser handles the agy-specific token JSON.
|
||||
|
||||
export const importAgyAuthSchema = z.object({
|
||||
source: z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("json"), json: z.unknown() }),
|
||||
z.object({
|
||||
kind: z.literal("text"),
|
||||
text: z.string().max(256 * 1024, "agy token file content exceeds 256KB"),
|
||||
}),
|
||||
]),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Antigravity CLI (`agy`) auto-detect local login Schema ────
|
||||
// No `source`: the route reads the token from the local agy CLI data dir on disk.
|
||||
|
||||
export const applyLocalAgyAuthSchema = z.object({
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Gemini CLI Auth Import Bulk Schema ────
|
||||
|
||||
export const importGeminiAuthBulkSchema = z.object({
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
json: z.unknown(),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
})
|
||||
)
|
||||
.min(1, "At least one entry is required")
|
||||
.max(50, "At most 50 entries per bulk import"),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// ──── Antigravity CLI (`agy`) Auth Import Bulk Schema ────
|
||||
|
||||
export const importAgyAuthBulkSchema = z.object({
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
json: z.unknown(),
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
email: z.string().email("Must be a valid email").optional(),
|
||||
})
|
||||
)
|
||||
.min(1, "At least one entry is required")
|
||||
.max(50, "At most 50 entries per bulk import"),
|
||||
overwriteExisting: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const oauthExchangeSchema = z.object({
|
||||
code: z.string().trim().min(1),
|
||||
redirectUri: z.string().trim().min(1),
|
||||
codeVerifier: z.string().trim().min(1).optional(),
|
||||
state: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export const oauthPollSchema = z.object({
|
||||
deviceCode: z.string().trim().min(1),
|
||||
codeVerifier: z.string().optional(),
|
||||
extraData: z.unknown().optional(),
|
||||
});
|
||||
|
||||
/** Import a raw API token (e.g. WINDSURF_API_KEY) without going through the browser OAuth flow. */
|
||||
export const oauthImportTokenSchema = z.object({
|
||||
token: z.string().trim().min(1, "Token is required"),
|
||||
connectionId: z.string().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Persist tokens obtained out-of-band by the browser-driven Codex device flow.
|
||||
* The browser performs the full device authorization + token exchange against
|
||||
* auth.openai.com (the server cannot — its datacenter IP is blocked by Cloudflare),
|
||||
* then ships the final tokens here for mapping + persistence. Token fields use the
|
||||
* snake_case shape returned by the OAuth token endpoint (consumed directly by
|
||||
* each provider's mapTokens).
|
||||
*/
|
||||
export const oauthDeviceCompleteSchema = z.object({
|
||||
access_token: z.string().trim().min(1, "access_token is required"),
|
||||
refresh_token: z.string().trim().optional(),
|
||||
id_token: z.string().trim().optional(),
|
||||
expires_in: z.number().int().positive().optional(),
|
||||
connectionId: z.string().optional(),
|
||||
});
|
||||
|
||||
export const cursorImportSchema = z.object({
|
||||
accessToken: z.string().trim().min(1, "Access token is required"),
|
||||
machineId: z.string().trim().optional(),
|
||||
});
|
||||
|
||||
export const traeImportSchema = z.object({
|
||||
accessToken: z.string().trim().min(1, "Cloud-IDE-JWT access token is required"),
|
||||
webId: z.string().trim().optional(),
|
||||
bizUserId: z.string().trim().optional(),
|
||||
userUniqueId: z.string().trim().optional(),
|
||||
scope: z.string().trim().optional(),
|
||||
tenant: z.string().trim().optional(),
|
||||
region: z.string().trim().optional(),
|
||||
});
|
||||
|
||||
export const kiroImportSchema = z.object({
|
||||
refreshToken: z.string().trim().min(1, "Refresh token is required"),
|
||||
region: z.string().trim().default("us-east-1"),
|
||||
});
|
||||
|
||||
export const kiroSocialExchangeSchema = z.object({
|
||||
code: z.string().trim().min(1, "Code is required"),
|
||||
codeVerifier: z.string().trim().min(1, "Code verifier is required"),
|
||||
provider: z.enum(["google", "github"]),
|
||||
});
|
||||
|
||||
export const zedImportSchema = z.object({
|
||||
confirmedAccounts: z.array(confirmedAccountSchema),
|
||||
});
|
||||
75
src/shared/validation/schemas/cli.ts
Normal file
75
src/shared/validation/schemas/cli.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const cliMitmStartSchema = z.object({
|
||||
apiKey: z.string().trim().min(1).nullable().optional(),
|
||||
keyId: z.string().trim().min(1).nullable().optional(),
|
||||
sudoPassword: z.string().optional(),
|
||||
});
|
||||
|
||||
export const cliMitmStopSchema = z.object({
|
||||
sudoPassword: z.string().optional(),
|
||||
});
|
||||
|
||||
export const cliMitmAliasUpdateSchema = z.object({
|
||||
tool: z.string().trim().min(1, "tool and mappings required"),
|
||||
mappings: z.record(z.string(), z.string().optional()),
|
||||
});
|
||||
|
||||
export const cliBackupMutationSchema = z
|
||||
.object({
|
||||
tool: z.string().trim().min(1).optional(),
|
||||
toolId: z.string().trim().min(1).optional(),
|
||||
backupId: z.string().trim().min(1, "tool and backupId are required"),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (!value.tool && !value.toolId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "tool and backupId are required",
|
||||
path: ["tool"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const envKeySchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, "Environment key is required")
|
||||
.max(120)
|
||||
.regex(/^[A-Z_][A-Z0-9_]*$/, "Invalid environment key format");
|
||||
|
||||
export const envValueSchema = z
|
||||
.union([z.string(), z.number(), z.boolean()])
|
||||
.transform((value) => String(value))
|
||||
.refine((value) => value.length > 0, "Environment value is required")
|
||||
.refine((value) => value.length <= 10_000, "Environment value is too long");
|
||||
|
||||
export const cliSettingsEnvSchema = z.object({
|
||||
env: z
|
||||
.record(envKeySchema, envValueSchema)
|
||||
.refine((value) => Object.keys(value).length > 0, "env must contain at least one key"),
|
||||
});
|
||||
|
||||
export const cliModelConfigSchema = z.object({
|
||||
baseUrl: z.string().trim().min(1, "baseUrl and model are required"),
|
||||
apiKey: z.string().nullable().optional(),
|
||||
model: z.string().trim().min(1, "baseUrl and model are required"),
|
||||
reasoningEffort: z.enum(["none", "low", "medium", "high", "xhigh"]).optional(),
|
||||
wireApi: z.enum(["chat", "responses"]).optional(),
|
||||
modelMappings: z.record(z.string().trim().min(1), z.string().trim().min(1)).optional(),
|
||||
});
|
||||
53
src/shared/validation/schemas/cloud.ts
Normal file
53
src/shared/validation/schemas/cloud.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const cloudCredentialUpdateSchema = z.object({
|
||||
provider: z.string().trim().min(1, "Provider is required"),
|
||||
credentials: z
|
||||
.object({
|
||||
accessToken: z.string().optional(),
|
||||
refreshToken: z.string().optional(),
|
||||
expiresIn: z.coerce.number().positive().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.accessToken === undefined &&
|
||||
value.refreshToken === undefined &&
|
||||
value.expiresIn === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "At least one credential field must be provided",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
export const cloudResolveAliasSchema = z.object({
|
||||
alias: z.string().trim().min(1, "Missing alias"),
|
||||
});
|
||||
|
||||
export const cloudModelAliasUpdateSchema = z.object({
|
||||
model: z.string().trim().min(1, "Model and alias required"),
|
||||
alias: z.string().trim().min(1, "Model and alias required"),
|
||||
});
|
||||
|
||||
export const cloudSyncActionSchema = z.object({
|
||||
action: z.enum(["enable", "sync", "disable"]),
|
||||
});
|
||||
313
src/shared/validation/schemas/combo.ts
Normal file
313
src/shared/validation/schemas/combo.ts
Normal file
@@ -0,0 +1,313 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
// ──── Combo Schemas ────
|
||||
|
||||
export const comboStepMetaSchema = {
|
||||
id: z.string().trim().min(1).max(200).optional(),
|
||||
weight: z.number().min(0).max(100).optional().default(0),
|
||||
label: z.string().trim().min(1).max(200).optional(),
|
||||
};
|
||||
|
||||
export const comboModelStepInputSchema = z.object({
|
||||
kind: z.literal("model").optional(),
|
||||
provider: z.string().trim().min(1).max(120).optional(),
|
||||
providerId: z.string().trim().min(1).max(120).optional(),
|
||||
model: z.string().trim().min(1).max(300),
|
||||
connectionId: z.string().trim().min(1).max(200).nullable().optional(),
|
||||
tags: z.array(z.string().trim().min(1).max(100)).max(20).optional(),
|
||||
...comboStepMetaSchema,
|
||||
});
|
||||
|
||||
export const comboRefStepInputSchema = z.object({
|
||||
kind: z.literal("combo-ref"),
|
||||
comboName: z.string().trim().min(1).max(100),
|
||||
...comboStepMetaSchema,
|
||||
});
|
||||
|
||||
// A combo entry can be a plain string (legacy), a legacy object, or a structured ComboStep.
|
||||
export const comboModelEntry = z.union([
|
||||
z.string().trim().min(1).max(300),
|
||||
comboModelStepInputSchema,
|
||||
comboRefStepInputSchema,
|
||||
]);
|
||||
|
||||
export const shadowRoutingSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
targets: z.array(comboModelEntry).max(20).optional(),
|
||||
sampleRate: z.coerce.number().min(0).max(1).optional(),
|
||||
maxTargets: z.coerce.number().int().min(1).max(10).optional(),
|
||||
timeoutMs: z.coerce.number().int().min(1000).max(120000).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const evalRoutingSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
suiteIds: z.array(z.string().trim().min(1).max(200)).max(50).optional(),
|
||||
maxAgeHours: z.coerce.number().min(1).max(8760).optional(),
|
||||
minCases: z.coerce.number().int().min(1).max(100000).optional(),
|
||||
qualityWeight: z.coerce.number().min(0).max(1).optional(),
|
||||
latencyWeight: z.coerce.number().min(0).max(1).optional(),
|
||||
cacheTtlMs: z.coerce.number().int().min(1000).max(300000).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const comboStrategySchema = z.enum(ROUTING_STRATEGY_VALUES);
|
||||
|
||||
export const scoringWeightsSchema = z
|
||||
.object({
|
||||
quota: z.number().min(0).max(1),
|
||||
health: z.number().min(0).max(1),
|
||||
costInv: z.number().min(0).max(1),
|
||||
latencyInv: z.number().min(0).max(1),
|
||||
taskFit: z.number().min(0).max(1),
|
||||
stability: z.number().min(0).max(1),
|
||||
tierPriority: z.number().min(0).max(1).optional().default(0.05),
|
||||
tierAffinity: z.number().min(0).max(1).optional().default(0.05),
|
||||
specificityMatch: z.number().min(0).max(1).optional().default(0.05),
|
||||
contextAffinity: z.number().min(0).max(1).optional().default(0.08),
|
||||
resetWindowAffinity: z.number().min(0).max(1).optional().default(0),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const compositeTierEntrySchema = z
|
||||
.object({
|
||||
stepId: z.string().trim().min(1).max(200),
|
||||
fallbackTier: z.string().trim().min(1).max(100).optional(),
|
||||
label: z.string().trim().min(1).max(200).optional(),
|
||||
description: z.string().trim().min(1).max(500).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const compositeTiersSchema = z
|
||||
.object({
|
||||
defaultTier: z.string().trim().min(1).max(100),
|
||||
tiers: z.record(z.string().trim().min(1).max(100), compositeTierEntrySchema),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const compressionModeSchema = z.enum([
|
||||
"off",
|
||||
"lite",
|
||||
"standard",
|
||||
"aggressive",
|
||||
"ultra",
|
||||
"rtk",
|
||||
"stacked",
|
||||
]);
|
||||
|
||||
export const comboCompressionOverrideSchema = z.union([z.literal(""), compressionModeSchema]);
|
||||
|
||||
export const slaRoutingPolicySchema = z
|
||||
.object({
|
||||
targetP95Ms: z.coerce.number().int().positive().max(300000).optional(),
|
||||
maxErrorRate: z.coerce.number().min(0).max(1).optional(),
|
||||
maxCostPer1MTokens: z.coerce.number().positive().max(1000000).optional(),
|
||||
hardConstraints: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const comboRuntimeConfigSchema = z
|
||||
.object({
|
||||
strategy: comboStrategySchema.optional(),
|
||||
maxRetries: z.coerce.number().int().min(0).max(10).optional(),
|
||||
retryDelayMs: z.coerce.number().int().min(0).max(60000).optional(),
|
||||
fallbackDelayMs: z.coerce.number().int().min(0).max(60000).optional(),
|
||||
timeoutMs: z.coerce.number().int().min(1000).optional(),
|
||||
targetTimeoutMs: z.coerce.number().int().min(0).max(MAX_TIMER_TIMEOUT_MS).optional(),
|
||||
concurrencyPerModel: z.coerce.number().int().min(1).max(20).optional(),
|
||||
queueTimeoutMs: z.coerce.number().int().min(1000).max(120000).optional(),
|
||||
healthCheckEnabled: z.boolean().optional(),
|
||||
healthCheckTimeoutMs: z.coerce.number().int().min(100).max(30000).optional(),
|
||||
handoffThreshold: z.coerce.number().min(0.5).max(0.94).optional(),
|
||||
handoffModel: z.string().trim().max(200).optional(),
|
||||
handoffProviders: z.array(z.string().trim().min(1).max(100)).max(10).optional(),
|
||||
maxMessagesForSummary: z.coerce.number().int().min(5).max(100).optional(),
|
||||
maxComboDepth: z.coerce.number().int().min(1).max(10).optional(),
|
||||
trackMetrics: z.boolean().optional(),
|
||||
reasoningTokenBufferEnabled: z.boolean().optional(),
|
||||
compressionMode: compressionModeSchema.optional(),
|
||||
failoverBeforeRetry: z.boolean().optional(),
|
||||
maxSetRetries: z.coerce.number().int().min(0).max(10).optional(),
|
||||
setRetryDelayMs: z.coerce.number().int().min(0).max(60000).optional(),
|
||||
zeroLatencyOptimizationsEnabled: z.boolean().optional(),
|
||||
hedging: z.boolean().optional(),
|
||||
hedgeDelayMs: z.coerce.number().int().min(0).max(60000).optional(),
|
||||
fallbackCompressionMode: compressionModeSchema.optional(),
|
||||
fallbackCompressionThreshold: z.coerce.number().int().min(0).max(2_000_000).optional(),
|
||||
predictiveTtftMs: z.coerce.number().int().min(0).max(300000).optional(),
|
||||
// Auto-Combo / LKGP Extensions
|
||||
candidatePool: z.array(z.string().min(1)).optional(),
|
||||
weights: scoringWeightsSchema.optional(),
|
||||
modePack: z.string().max(100).optional(),
|
||||
budgetCap: z.number().positive().optional(),
|
||||
explorationRate: z.number().min(0).max(1).optional(),
|
||||
routerStrategy: z.string().optional(),
|
||||
slaTargetP95Ms: z.coerce.number().int().positive().max(300000).optional(),
|
||||
slaMaxErrorRate: z.coerce.number().min(0).max(1).optional(),
|
||||
slaMaxCostPer1MTokens: z.coerce.number().positive().max(1000000).optional(),
|
||||
slaHardConstraints: z.boolean().optional(),
|
||||
sla: slaRoutingPolicySchema.optional(),
|
||||
compositeTiers: compositeTiersSchema.optional(),
|
||||
resetAwareSessionWeight: z.coerce.number().min(0).max(100).optional(),
|
||||
resetAwareWeeklyWeight: z.coerce.number().min(0).max(100).optional(),
|
||||
resetAwareTieBandPercent: z.coerce.number().min(0).max(100).optional(),
|
||||
resetAwareExhaustionGuardPercent: z.coerce.number().min(0).max(100).optional(),
|
||||
resetAwareQuotaCacheTtlMs: z.coerce.number().int().min(0).max(300_000).optional(),
|
||||
resetAwareQuotaCacheMaxStaleMs: z.coerce.number().int().min(0).max(3_600_000).optional(),
|
||||
resetWindowWindows: z.array(z.enum(["weekly", "session", "monthly"])).optional(),
|
||||
resetWindowIncludeSession: z.boolean().optional(),
|
||||
resetWindowTieBandMs: z.coerce.number().int().min(0).max(86_400_000).optional(),
|
||||
resetWindowQuotaCacheTtlMs: z.coerce.number().int().min(0).max(300_000).optional(),
|
||||
resetWindowQuotaCacheMaxStaleMs: z.coerce.number().int().min(0).max(3_600_000).optional(),
|
||||
shadowRouting: shadowRoutingSchema.optional(),
|
||||
evalRouting: evalRoutingSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((config, ctx) => {
|
||||
if (config.zeroLatencyOptimizationsEnabled === true) return;
|
||||
|
||||
const addZeroLatencyIssue = (path: string[]) => {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"zeroLatencyOptimizationsEnabled must be true to enable zero-latency combo features",
|
||||
path,
|
||||
});
|
||||
};
|
||||
|
||||
if (config.hedging === true) {
|
||||
addZeroLatencyIssue(["hedging"]);
|
||||
}
|
||||
if (typeof config.predictiveTtftMs === "number" && config.predictiveTtftMs > 0) {
|
||||
addZeroLatencyIssue(["predictiveTtftMs"]);
|
||||
}
|
||||
if (config.fallbackCompressionMode && config.fallbackCompressionMode !== "off") {
|
||||
addZeroLatencyIssue(["fallbackCompressionMode"]);
|
||||
}
|
||||
});
|
||||
|
||||
export const comboNameSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, "Name is required")
|
||||
.max(100)
|
||||
.regex(
|
||||
/^[a-zA-Z0-9_/.\-\[\] ]+$/,
|
||||
"Name can only contain letters, numbers, spaces, -, _, /, ., [ and ]."
|
||||
);
|
||||
|
||||
export const createComboSchema = z.object({
|
||||
name: comboNameSchema,
|
||||
models: z.array(comboModelEntry).optional().default([]),
|
||||
strategy: comboStrategySchema.optional().default("priority"),
|
||||
config: comboRuntimeConfigSchema.optional(),
|
||||
allowedProviders: z.array(z.string().max(200)).optional(),
|
||||
system_message: z.string().max(50000).optional(),
|
||||
tool_filter_regex: z.string().max(1000).optional(),
|
||||
context_cache_protection: z.boolean().optional(),
|
||||
context_length: z.number().int().min(1000).max(2000000).optional(),
|
||||
});
|
||||
|
||||
export const updateComboDefaultsSchema = z
|
||||
.object({
|
||||
comboDefaults: comboRuntimeConfigSchema.optional(),
|
||||
providerOverrides: z.record(z.string().trim().min(1), comboRuntimeConfigSchema).optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (!value.comboDefaults && !value.providerOverrides) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Nothing to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (value.comboDefaults?.compositeTiers) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "compositeTiers is only supported on concrete combos",
|
||||
path: ["comboDefaults", "compositeTiers"],
|
||||
});
|
||||
}
|
||||
|
||||
for (const [providerId, config] of Object.entries(value.providerOverrides || {})) {
|
||||
if (config?.compositeTiers) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "compositeTiers is only supported on concrete combos",
|
||||
path: ["providerOverrides", providerId, "compositeTiers"],
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const updateComboSchema = z
|
||||
.object({
|
||||
name: comboNameSchema.optional(),
|
||||
models: z.array(comboModelEntry).optional(),
|
||||
strategy: comboStrategySchema.optional(),
|
||||
config: comboRuntimeConfigSchema.optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
allowedProviders: z.array(z.string().max(200)).optional(),
|
||||
system_message: z.string().max(50000).optional(),
|
||||
tool_filter_regex: z.string().max(1000).optional(),
|
||||
context_cache_protection: z.boolean().optional(),
|
||||
context_length: z.number().int().min(1000).max(2000000).optional().nullable(),
|
||||
compressionOverride: comboCompressionOverrideSchema.optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.name === undefined &&
|
||||
value.models === undefined &&
|
||||
value.strategy === undefined &&
|
||||
value.config === undefined &&
|
||||
value.isActive === undefined &&
|
||||
value.allowedProviders === undefined &&
|
||||
value.system_message === undefined &&
|
||||
value.tool_filter_regex === undefined &&
|
||||
value.context_cache_protection === undefined &&
|
||||
value.context_length === undefined &&
|
||||
value.compressionOverride === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const reorderCombosSchema = z
|
||||
.object({
|
||||
comboIds: z.array(z.string().trim().min(1).max(200)).min(1).max(1000),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (new Set(value.comboIds).size !== value.comboIds.length) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "comboIds must be unique",
|
||||
path: ["comboIds"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const testComboSchema = z.object({
|
||||
comboName: z.string().trim().min(1, "comboName is required"),
|
||||
});
|
||||
86
src/shared/validation/schemas/evals.ts
Normal file
86
src/shared/validation/schemas/evals.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const evalTargetSchema = z
|
||||
.object({
|
||||
type: z.enum(["suite-default", "model", "combo"]),
|
||||
id: z.string().trim().min(1).optional().nullable(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.type === "suite-default") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value.id !== "string" || value.id.trim().length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "target.id is required for model and combo targets",
|
||||
path: ["id"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const evalMessageSchema = z.object({
|
||||
role: z.string().trim().min(1, "message.role is required").max(50),
|
||||
content: z.string().trim().min(1, "message.content is required").max(20000),
|
||||
});
|
||||
|
||||
export const evalCaseBuilderSchema = z.object({
|
||||
id: z.string().trim().min(1).optional(),
|
||||
name: z.string().trim().min(1, "case.name is required").max(200),
|
||||
model: z.string().trim().min(1).max(300).optional().nullable(),
|
||||
input: z.object({
|
||||
messages: z.array(evalMessageSchema).min(1, "At least one message is required").max(32),
|
||||
max_tokens: z.number().int().min(1).max(8192).optional(),
|
||||
}),
|
||||
expected: z.object({
|
||||
strategy: z.enum(["contains", "exact", "regex"]),
|
||||
value: z.string().trim().min(1, "expected.value is required").max(20000),
|
||||
}),
|
||||
tags: z.array(z.string().trim().min(1).max(64)).max(20).optional(),
|
||||
});
|
||||
|
||||
export const evalRunSuiteSchema = z
|
||||
.object({
|
||||
suiteId: z.string().trim().min(1, "suiteId is required"),
|
||||
outputs: z.record(z.string(), z.string()).optional(),
|
||||
target: evalTargetSchema.optional(),
|
||||
compareTarget: evalTargetSchema.optional(),
|
||||
apiKeyId: z.string().trim().min(1, "apiKeyId must not be empty").optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.compareTarget) {
|
||||
const primaryType = value.target?.type || "suite-default";
|
||||
const primaryId = value.target?.id?.trim() || "";
|
||||
const compareId = value.compareTarget.id?.trim() || "";
|
||||
|
||||
if (primaryType === value.compareTarget.type && primaryId === compareId) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "compareTarget must differ from target",
|
||||
path: ["compareTarget"],
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const evalSuiteSaveSchema = z.object({
|
||||
id: z.string().trim().min(1).optional(),
|
||||
name: z.string().trim().min(1, "name is required").max(200),
|
||||
description: z.string().trim().max(2000).optional(),
|
||||
cases: z.array(evalCaseBuilderSchema).min(1, "At least one case is required").max(200),
|
||||
});
|
||||
59
src/shared/validation/schemas/gemini.ts
Normal file
59
src/shared/validation/schemas/gemini.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const geminiPartSchema = z
|
||||
.object({
|
||||
text: z.string().optional(),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const geminiContentSchema = z
|
||||
.object({
|
||||
role: z.string().optional(),
|
||||
parts: z.array(geminiPartSchema).optional(),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const v1betaGeminiGenerateSchema = z
|
||||
.object({
|
||||
contents: z.array(geminiContentSchema).optional(),
|
||||
systemInstruction: z
|
||||
.object({
|
||||
parts: z.array(geminiPartSchema).optional(),
|
||||
})
|
||||
.catchall(z.unknown())
|
||||
.optional(),
|
||||
generationConfig: z
|
||||
.object({
|
||||
stream: z.boolean().optional(),
|
||||
maxOutputTokens: z.coerce.number().int().min(1).optional(),
|
||||
temperature: z.coerce.number().optional(),
|
||||
topP: z.coerce.number().optional(),
|
||||
})
|
||||
.catchall(z.unknown())
|
||||
.optional(),
|
||||
})
|
||||
.catchall(z.unknown())
|
||||
.superRefine((value, ctx) => {
|
||||
if (!value.contents && !value.systemInstruction) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "contents or systemInstruction is required",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
135
src/shared/validation/schemas/keys.ts
Normal file
135
src/shared/validation/schemas/keys.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
import { accessScheduleSchema } from "./misc.ts";
|
||||
|
||||
// ──── API Key Schemas ────
|
||||
|
||||
export const createKeySchema = z.object({
|
||||
name: z.string().min(1, "Name is required").max(200),
|
||||
noLog: z.boolean().optional(),
|
||||
allowUsageCommand: z.boolean().optional(),
|
||||
scopes: z.array(z.string().trim().min(1).max(64)).max(32).optional(),
|
||||
});
|
||||
|
||||
export const createSyncTokenSchema = z.object({
|
||||
name: z.string().trim().min(1, "Name is required").max(200),
|
||||
});
|
||||
|
||||
export const setBudgetSchema = z.object({
|
||||
apiKeyId: z.string().trim().min(1, "apiKeyId is required"),
|
||||
// #3537: a limit of 0 means "no limit for this period" (checkBudget only enforces when
|
||||
// activeLimitUsd > 0). The dashboard sends 0 for unfilled fields, so 0 must be accepted —
|
||||
// `.positive()` (rejects 0) used to 400 any save that left a field blank. Negatives are
|
||||
// still rejected by `.min(0)`.
|
||||
dailyLimitUsd: z.coerce.number().min(0, "dailyLimitUsd must be zero or greater").optional(),
|
||||
weeklyLimitUsd: z.coerce.number().min(0, "weeklyLimitUsd must be zero or greater").optional(),
|
||||
monthlyLimitUsd: z.coerce.number().min(0, "monthlyLimitUsd must be zero or greater").optional(),
|
||||
warningThreshold: z.coerce.number().min(0).max(1).optional(),
|
||||
resetInterval: z.enum(["daily", "weekly", "monthly"]).optional(),
|
||||
resetTime: z
|
||||
.string()
|
||||
.trim()
|
||||
.regex(/^\d{2}:\d{2}$/, "resetTime must be in HH:MM format")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const setTokenLimitSchema = z
|
||||
.object({
|
||||
id: z.string().trim().min(1).optional(),
|
||||
apiKeyId: z.string().trim().min(1, "apiKeyId is required"),
|
||||
scopeType: z.enum(["model", "provider", "global"]),
|
||||
scopeValue: z.string().trim().default(""),
|
||||
tokenLimit: z.coerce
|
||||
.number()
|
||||
.int("tokenLimit must be an integer")
|
||||
.positive("tokenLimit must be greater than zero"),
|
||||
resetInterval: z.enum(["daily", "weekly", "monthly"]).default("monthly"),
|
||||
resetTime: z
|
||||
.string()
|
||||
.trim()
|
||||
.regex(/^\d{2}:\d{2}$/, "resetTime must be in HH:MM format")
|
||||
.optional(),
|
||||
enabled: z.boolean().default(true),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.scopeType !== "global" && (!value.scopeValue || value.scopeValue.length === 0)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "scopeValue is required unless scopeType is 'global'",
|
||||
path: ["scopeValue"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const updateKeyPermissionsSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(200).optional(),
|
||||
allowedModels: z.array(z.string().trim().min(1)).max(1000).optional(),
|
||||
allowedCombos: z.array(z.string().trim().min(1).max(200)).max(500).optional(),
|
||||
allowedConnections: z.array(z.string().uuid()).max(100).optional(),
|
||||
noLog: z.boolean().optional(),
|
||||
autoResolve: z.boolean().optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
throttleDelayMs: z.number().int().min(0).max(300000).optional(),
|
||||
isBanned: z.boolean().optional(),
|
||||
expiresAt: z.string().datetime().nullable().optional(),
|
||||
maxSessions: z.number().int().min(0).max(10000).optional(),
|
||||
accessSchedule: z.union([accessScheduleSchema, z.null()]).optional(),
|
||||
rateLimits: z
|
||||
.union([
|
||||
z
|
||||
.array(
|
||||
z.object({ limit: z.number().int().positive(), window: z.number().int().positive() })
|
||||
)
|
||||
.max(50),
|
||||
z.null(),
|
||||
])
|
||||
.optional(),
|
||||
scopes: z.array(z.string().trim().min(1).max(64)).max(32).optional(),
|
||||
allowedEndpoints: z.array(z.string().trim().min(1).max(64)).max(20).optional(),
|
||||
streamDefaultMode: z.enum(["legacy", "json"]).optional(),
|
||||
disableNonPublicModels: z.boolean().optional(),
|
||||
allowUsageCommand: z.boolean().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.name === undefined &&
|
||||
value.allowedModels === undefined &&
|
||||
value.allowedCombos === undefined &&
|
||||
value.allowedConnections === undefined &&
|
||||
value.noLog === undefined &&
|
||||
value.autoResolve === undefined &&
|
||||
value.isActive === undefined &&
|
||||
value.throttleDelayMs === undefined &&
|
||||
value.isBanned === undefined &&
|
||||
value.expiresAt === undefined &&
|
||||
value.maxSessions === undefined &&
|
||||
value.accessSchedule === undefined &&
|
||||
value.rateLimits === undefined &&
|
||||
value.scopes === undefined &&
|
||||
value.allowedEndpoints === undefined &&
|
||||
value.streamDefaultMode === undefined &&
|
||||
value.disableNonPublicModels === undefined &&
|
||||
value.allowUsageCommand === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
203
src/shared/validation/schemas/misc.ts
Normal file
203
src/shared/validation/schemas/misc.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export function isHttpUrl(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const CODEX_REASONING_EFFORT_VALUES = new Set(["none", "low", "medium", "high", "xhigh"]);
|
||||
|
||||
export const REQUEST_DEFAULT_SERVICE_TIER_VALUES = new Set(["default", "priority", "fast", "flex"]);
|
||||
|
||||
// ──── Auth Schemas ────
|
||||
|
||||
export const loginSchema = z.object({
|
||||
password: z.string().min(1, "Password is required").max(200),
|
||||
});
|
||||
|
||||
export const dbBackupCleanupSchema = z.object({
|
||||
keepLatest: z.number().int().min(1).max(200).optional(),
|
||||
retentionDays: z.number().int().min(0).max(3650).optional(),
|
||||
});
|
||||
|
||||
// ──── API Route Payload Schemas (T06) ────
|
||||
|
||||
export const modelIdSchema = z.string().trim().min(1, "Model is required").max(200);
|
||||
|
||||
export const nonEmptyStringSchema = z.string().trim().min(1, "Field is required");
|
||||
|
||||
export const policyActionSchema = z
|
||||
.object({
|
||||
action: z.enum(["unlock"]),
|
||||
identifier: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.action === "unlock" && !value.identifier) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "identifier is required for unlock action",
|
||||
path: ["identifier"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** Align with `sanitizeUpstreamHeadersMap` — allow non-ASCII names; reject Host / hop-by-hop / whitespace / ":". */
|
||||
export const upstreamHeaderNameSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.refine((s) => !/[\r\n\0]/.test(s), { message: "header name cannot contain control characters" })
|
||||
.refine((s) => !/\s/.test(s), { message: "header name cannot contain whitespace" })
|
||||
.refine((s) => !s.includes(":"), { message: "header name cannot contain ':'" })
|
||||
.refine((s) => !isForbiddenUpstreamHeaderName(s), { message: "header name is not allowed" });
|
||||
|
||||
export const upstreamHeaderValueSchema = z
|
||||
.string()
|
||||
.max(4096)
|
||||
.refine((s) => !/[\r\n]/.test(s), { message: "header value cannot contain line breaks" });
|
||||
|
||||
export const upstreamHeadersRecordSchema = z
|
||||
.record(upstreamHeaderNameSchema, upstreamHeaderValueSchema)
|
||||
.refine((rec) => Object.keys(rec).length <= 16, { message: "at most 16 custom headers" })
|
||||
.refine((rec) => !Object.keys(rec).some((k) => isForbiddenUpstreamHeaderName(k)), {
|
||||
message: "forbidden header name in record",
|
||||
});
|
||||
|
||||
export const modelCompatPerProtocolSchema = z
|
||||
.object({
|
||||
normalizeToolCallId: z.boolean().optional(),
|
||||
preserveOpenAIDeveloperRole: z.boolean().optional(),
|
||||
upstreamHeaders: upstreamHeadersRecordSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const toggleRateLimitSchema = z.object({
|
||||
connectionId: z.string().trim().min(1, "connectionId is required"),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
export const jsonObjectSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
export const resetStatsActionSchema = z.object({
|
||||
action: z.literal("reset-stats"),
|
||||
});
|
||||
|
||||
export const ipFilterModeSchema = z.enum(["blacklist", "whitelist"]);
|
||||
|
||||
export const tempBanSchema = z.object({
|
||||
ip: z.string().trim().min(1),
|
||||
durationMs: z.coerce.number().int().min(1).optional(),
|
||||
reason: z.string().max(200).optional(),
|
||||
});
|
||||
|
||||
export const updateIpFilterSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
mode: ipFilterModeSchema.optional(),
|
||||
blacklist: z.array(z.string()).optional(),
|
||||
whitelist: z.array(z.string()).optional(),
|
||||
addBlacklist: z.string().optional(),
|
||||
removeBlacklist: z.string().optional(),
|
||||
addWhitelist: z.string().optional(),
|
||||
removeWhitelist: z.string().optional(),
|
||||
tempBan: tempBanSchema.optional(),
|
||||
removeBan: z.string().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (Object.keys(value).length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const jsonRecordSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
export const nonEmptyJsonRecordSchema = jsonRecordSchema.refine(
|
||||
(value) => Object.keys(value).length > 0,
|
||||
"Body must be a non-empty object"
|
||||
);
|
||||
|
||||
export const dbBackupRestoreSchema = z.object({
|
||||
backupId: z.string().trim().min(1, "backupId is required"),
|
||||
});
|
||||
|
||||
export const accessScheduleSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
from: z.string().regex(/^\d{2}:\d{2}$/, "Time must be in HH:MM format"),
|
||||
until: z.string().regex(/^\d{2}:\d{2}$/, "Time must be in HH:MM format"),
|
||||
days: z.array(z.number().int().min(0).max(6)).min(1, "At least one day is required").max(7),
|
||||
tz: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
// Reuse the canonical upstream-headers record schema (control-char / whitespace
|
||||
// / ":" / 128-name / 4096-value / max-16 guards) so per-provider custom headers
|
||||
// inherit the same hardening as `modelCompat.upstreamHeaders` — then additionally
|
||||
// reject auth header names (the credential layer owns those; the executor drops
|
||||
// them at send time, so reject up front for an actionable error instead of a
|
||||
// silent no-op). Single denylist source: isForbiddenCustomHeaderName.
|
||||
export const customHeadersSchema = upstreamHeadersRecordSchema
|
||||
.refine((rec) => !Object.keys(rec).some((k) => isForbiddenCustomHeaderName(k)), {
|
||||
message:
|
||||
"Custom headers cannot include hop-by-hop, framing, or auth headers " +
|
||||
"(authorization / x-api-key / x-goog-api-key / api-key)",
|
||||
})
|
||||
.nullable()
|
||||
.optional();
|
||||
|
||||
export const codexProfileNameSchema = z.object({
|
||||
name: z.string().trim().min(1, "Profile name is required"),
|
||||
});
|
||||
|
||||
export const codexProfileIdSchema = z.object({
|
||||
// profileId is interpolated into a filesystem path (`<PROFILES_DIR>/<id>.json`).
|
||||
// Constrain to a safe slug charset so request bodies cannot smuggle path
|
||||
// separators or `..` segments and escape PROFILES_DIR (path traversal).
|
||||
profileId: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, "profileId is required")
|
||||
.regex(/^[a-zA-Z0-9._-]+$/, "profileId contains invalid characters")
|
||||
.refine((v) => v !== "." && v !== "..", "profileId is invalid"),
|
||||
});
|
||||
|
||||
export const versionManagerToolSchema = z.object({
|
||||
tool: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const versionManagerInstallSchema = versionManagerToolSchema.extend({
|
||||
version: z.string().trim().optional(),
|
||||
});
|
||||
|
||||
// ── Zed Credential Import Flow ──────────────────────────────────────────────────
|
||||
|
||||
export const confirmedAccountSchema = z.object({
|
||||
service: z.string().min(1).max(500),
|
||||
account: z.string().min(1).max(500),
|
||||
fingerprint: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
export type ConfirmedAccount = z.infer<typeof confirmedAccountSchema>;
|
||||
64
src/shared/validation/schemas/payloadRules.ts
Normal file
64
src/shared/validation/schemas/payloadRules.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const payloadRuleModelSpecSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1),
|
||||
protocol: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const payloadMutationRuleSchema = z
|
||||
.object({
|
||||
models: z.array(payloadRuleModelSpecSchema).min(1),
|
||||
params: z
|
||||
.record(z.string().trim().min(1), z.unknown())
|
||||
.refine((value) => Object.keys(value).length > 0, "params must contain at least one path"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const payloadFilterRuleSchema = z
|
||||
.object({
|
||||
models: z.array(payloadRuleModelSpecSchema).min(1),
|
||||
params: z.array(z.string().trim().min(1)).min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const updatePayloadRulesSchema = z
|
||||
.object({
|
||||
default: z.array(payloadMutationRuleSchema).optional(),
|
||||
override: z.array(payloadMutationRuleSchema).optional(),
|
||||
filter: z.array(payloadFilterRuleSchema).optional(),
|
||||
defaultRaw: z.array(payloadMutationRuleSchema).optional(),
|
||||
"default-raw": z.array(payloadMutationRuleSchema).optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.default === undefined &&
|
||||
value.override === undefined &&
|
||||
value.filter === undefined &&
|
||||
value.defaultRaw === undefined &&
|
||||
value["default-raw"] === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
40
src/shared/validation/schemas/pricing.ts
Normal file
40
src/shared/validation/schemas/pricing.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const pricingFieldsSchema = z
|
||||
.object({
|
||||
input: z.number().min(0).optional(),
|
||||
output: z.number().min(0).optional(),
|
||||
cached: z.number().min(0).optional(),
|
||||
reasoning: z.number().min(0).optional(),
|
||||
cache_creation: z.number().min(0).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const updatePricingSchema = z.record(
|
||||
z.string().trim().min(1),
|
||||
z.record(z.string().trim().min(1), pricingFieldsSchema)
|
||||
);
|
||||
|
||||
export const pricingSyncSourceSchema = z.enum(["litellm"]);
|
||||
|
||||
export const pricingSyncRequestSchema = z
|
||||
.object({
|
||||
sources: z.array(pricingSyncSourceSchema).min(1).optional(),
|
||||
dryRun: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
629
src/shared/validation/schemas/provider.ts
Normal file
629
src/shared/validation/schemas/provider.ts
Normal file
@@ -0,0 +1,629 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import {
|
||||
OPENROUTER_PRESET_MAX_LENGTH,
|
||||
isOpenRouterPresetValue,
|
||||
} from "@/shared/constants/openRouterPreset";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
import { isHttpUrl, CODEX_REASONING_EFFORT_VALUES, REQUEST_DEFAULT_SERVICE_TIER_VALUES, upstreamHeadersRecordSchema, modelCompatPerProtocolSchema, customHeadersSchema } from "./misc.ts";
|
||||
|
||||
export function validateProviderSpecificData(
|
||||
data: Record<string, unknown> | undefined,
|
||||
ctx: z.RefinementCtx
|
||||
): void {
|
||||
if (!data) return;
|
||||
|
||||
const baseUrl = data.baseUrl;
|
||||
if (baseUrl !== undefined && (typeof baseUrl !== "string" || !isHttpUrl(baseUrl))) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.baseUrl must be a valid http(s) URL",
|
||||
path: ["baseUrl"],
|
||||
});
|
||||
}
|
||||
|
||||
const customUserAgent = data.customUserAgent;
|
||||
if (
|
||||
customUserAgent !== undefined &&
|
||||
customUserAgent !== null &&
|
||||
(typeof customUserAgent !== "string" || customUserAgent.length > 500)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.customUserAgent must be a string up to 500 chars",
|
||||
path: ["customUserAgent"],
|
||||
});
|
||||
}
|
||||
|
||||
const cx = data.cx;
|
||||
if (cx !== undefined && cx !== null && (typeof cx !== "string" || cx.length > 500)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.cx must be a string up to 500 chars",
|
||||
path: ["cx"],
|
||||
});
|
||||
}
|
||||
|
||||
const region = data.region;
|
||||
if (
|
||||
region !== undefined &&
|
||||
region !== null &&
|
||||
(typeof region !== "string" || region.length > 64)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.region must be a string up to 64 chars",
|
||||
path: ["region"],
|
||||
});
|
||||
}
|
||||
|
||||
const openaiStoreEnabled = data.openaiStoreEnabled;
|
||||
if (openaiStoreEnabled !== undefined && typeof openaiStoreEnabled !== "boolean") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.openaiStoreEnabled must be a boolean",
|
||||
path: ["openaiStoreEnabled"],
|
||||
});
|
||||
}
|
||||
|
||||
const blockExtraUsage = data.blockExtraUsage;
|
||||
if (blockExtraUsage !== undefined && typeof blockExtraUsage !== "boolean") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.blockExtraUsage must be a boolean",
|
||||
path: ["blockExtraUsage"],
|
||||
});
|
||||
}
|
||||
|
||||
const autoFetchModels = data.autoFetchModels;
|
||||
if (autoFetchModels !== undefined && typeof autoFetchModels !== "boolean") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.autoFetchModels must be a boolean",
|
||||
path: ["autoFetchModels"],
|
||||
});
|
||||
}
|
||||
|
||||
const disableStreamOptions = data.disableStreamOptions;
|
||||
if (disableStreamOptions !== undefined && typeof disableStreamOptions !== "boolean") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.disableStreamOptions must be a boolean",
|
||||
path: ["disableStreamOptions"],
|
||||
});
|
||||
}
|
||||
|
||||
const preset = data.preset;
|
||||
if (preset !== undefined && preset !== null && !isOpenRouterPresetValue(preset)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `providerSpecificData.preset must be a string up to ${OPENROUTER_PRESET_MAX_LENGTH} chars`,
|
||||
path: ["preset"],
|
||||
});
|
||||
}
|
||||
|
||||
const requestDefaults = data.requestDefaults;
|
||||
if (requestDefaults !== undefined) {
|
||||
if (!requestDefaults || typeof requestDefaults !== "object" || Array.isArray(requestDefaults)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.requestDefaults must be an object",
|
||||
path: ["requestDefaults"],
|
||||
});
|
||||
} else {
|
||||
const requestDefaultsRecord = requestDefaults as Record<string, unknown>;
|
||||
const reasoningEffort = requestDefaultsRecord.reasoningEffort;
|
||||
if (
|
||||
reasoningEffort !== undefined &&
|
||||
reasoningEffort !== null &&
|
||||
(typeof reasoningEffort !== "string" ||
|
||||
!CODEX_REASONING_EFFORT_VALUES.has(reasoningEffort.trim().toLowerCase()))
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"providerSpecificData.requestDefaults.reasoningEffort must be one of none, low, medium, high, xhigh",
|
||||
path: ["requestDefaults", "reasoningEffort"],
|
||||
});
|
||||
}
|
||||
|
||||
const serviceTier = requestDefaultsRecord.serviceTier;
|
||||
if (
|
||||
serviceTier !== undefined &&
|
||||
serviceTier !== null &&
|
||||
(typeof serviceTier !== "string" ||
|
||||
!REQUEST_DEFAULT_SERVICE_TIER_VALUES.has(serviceTier.trim().toLowerCase()))
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"providerSpecificData.requestDefaults.serviceTier must be one of default, priority, fast, flex when provided",
|
||||
path: ["requestDefaults", "serviceTier"],
|
||||
});
|
||||
}
|
||||
|
||||
const context1m = requestDefaultsRecord.context1m;
|
||||
if (context1m !== undefined && context1m !== null && typeof context1m !== "boolean") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.requestDefaults.context1m must be a boolean",
|
||||
path: ["requestDefaults", "context1m"],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// [Oracle CONDITIONAL] consoleApiKey는 bailian-coding-plan 전용 필드.
|
||||
// 다른 프로바이더 공통 규약으로 재사용하지 않는다.
|
||||
const consoleApiKey = data.consoleApiKey;
|
||||
if (consoleApiKey !== undefined && consoleApiKey !== null && typeof consoleApiKey !== "string") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.consoleApiKey must be a string",
|
||||
path: ["consoleApiKey"],
|
||||
});
|
||||
}
|
||||
if (typeof consoleApiKey === "string" && consoleApiKey.length > 10000) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.consoleApiKey must be at most 10000 characters",
|
||||
path: ["consoleApiKey"],
|
||||
});
|
||||
}
|
||||
|
||||
const groupTag = data.tag;
|
||||
if (
|
||||
groupTag !== undefined &&
|
||||
groupTag !== null &&
|
||||
(typeof groupTag !== "string" || groupTag.length > 100)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.tag must be a string up to 100 chars",
|
||||
path: ["tag"],
|
||||
});
|
||||
}
|
||||
|
||||
const routingTags = data.tags;
|
||||
if (routingTags !== undefined && routingTags !== null) {
|
||||
if (!Array.isArray(routingTags) || routingTags.length > 50) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.tags must be an array with at most 50 items",
|
||||
path: ["tags"],
|
||||
});
|
||||
} else if (
|
||||
routingTags.some(
|
||||
(tag) => typeof tag !== "string" || tag.trim().length === 0 || tag.trim().length > 64
|
||||
)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"providerSpecificData.tags must contain non-empty strings up to 64 characters each",
|
||||
path: ["tags"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const excludedModels = data.excludedModels ?? data.excluded_models;
|
||||
if (excludedModels !== undefined && excludedModels !== null) {
|
||||
if (typeof excludedModels === "string") {
|
||||
if (excludedModels.length > 5000) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.excludedModels string must be up to 5000 chars",
|
||||
path: ["excludedModels"],
|
||||
});
|
||||
}
|
||||
} else if (!Array.isArray(excludedModels) || excludedModels.length > 100) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerSpecificData.excludedModels must be an array with at most 100 items",
|
||||
path: ["excludedModels"],
|
||||
});
|
||||
} else if (
|
||||
excludedModels.some(
|
||||
(pattern) =>
|
||||
typeof pattern !== "string" ||
|
||||
pattern.trim().length === 0 ||
|
||||
pattern.trim().length > 200 ||
|
||||
pattern.trim() === "**"
|
||||
)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"providerSpecificData.excludedModels must contain non-empty patterns up to 200 characters",
|
||||
path: ["excludedModels"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const clientProfile = data.clientProfile;
|
||||
if (clientProfile !== undefined && clientProfile !== null) {
|
||||
const normalized = typeof clientProfile === "string" ? clientProfile.trim().toLowerCase() : "";
|
||||
if (
|
||||
typeof clientProfile !== "string" ||
|
||||
!["ide", "harness", "cli", "sdk"].includes(normalized)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message:
|
||||
"providerSpecificData.clientProfile must be ide, harness, cli, or sdk (cli/sdk map to harness)",
|
||||
path: ["clientProfile"],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ──── Provider Schemas ────
|
||||
|
||||
export const createProviderSchema = z
|
||||
.object({
|
||||
provider: z.string().min(1).max(100),
|
||||
apiKey: z.string().max(10000).optional(),
|
||||
name: z.string().min(1).max(200),
|
||||
priority: z.number().int().min(1).max(100).optional(),
|
||||
globalPriority: z.number().int().min(1).max(100).nullable().optional(),
|
||||
defaultModel: z.string().max(200).nullable().optional(),
|
||||
testStatus: z.string().max(50).optional(),
|
||||
providerSpecificData: z
|
||||
.record(z.string(), z.unknown())
|
||||
.optional()
|
||||
.superRefine((data, ctx) => {
|
||||
validateProviderSpecificData(data, ctx);
|
||||
}),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
const apiKey = typeof data.apiKey === "string" ? data.apiKey.trim() : "";
|
||||
const apiKeyOptional = providerAllowsOptionalApiKey(data.provider);
|
||||
if (!apiKeyOptional && apiKey.length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "API key is required",
|
||||
path: ["apiKey"],
|
||||
});
|
||||
}
|
||||
|
||||
const cx =
|
||||
data.providerSpecificData && typeof data.providerSpecificData === "object"
|
||||
? (data.providerSpecificData as Record<string, unknown>).cx
|
||||
: undefined;
|
||||
if (
|
||||
data.provider === "google-pse-search" &&
|
||||
(typeof cx !== "string" || cx.trim().length === 0)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Programmable Search Engine ID (cx) is required",
|
||||
path: ["providerSpecificData", "cx"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const bulkCreateProviderSchema = z
|
||||
.object({
|
||||
provider: z.string().min(1).max(100),
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
apiKey: z.string().min(1).max(10000),
|
||||
})
|
||||
)
|
||||
.min(1, "entries must contain at least 1 item")
|
||||
.max(200, "entries must contain at most 200 items"),
|
||||
priority: z.number().int().min(1).max(100).optional(),
|
||||
globalPriority: z.number().int().min(1).max(100).nullable().optional(),
|
||||
providerSpecificData: z
|
||||
.record(z.string(), z.unknown())
|
||||
.optional()
|
||||
.superRefine((data, ctx) => {
|
||||
validateProviderSpecificData(data, ctx);
|
||||
}),
|
||||
validateKeys: z.boolean().optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.provider === "google-pse-search") {
|
||||
const cx =
|
||||
data.providerSpecificData && typeof data.providerSpecificData === "object"
|
||||
? (data.providerSpecificData as Record<string, unknown>).cx
|
||||
: undefined;
|
||||
if (typeof cx !== "string" || cx.trim().length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Programmable Search Engine ID (cx) is required",
|
||||
path: ["providerSpecificData", "cx"],
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ──── Bulk Web-Session Import Schema ────
|
||||
|
||||
export const bulkWebSessionImportSchema = z.object({
|
||||
provider: z.string().min(1).max(100),
|
||||
entries: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
credential: z.string().min(1).max(64 * 1024, "Credential must be under 64 KB"),
|
||||
})
|
||||
)
|
||||
.min(1, "entries must contain at least 1 item")
|
||||
.max(50, "entries must contain at most 50 items"),
|
||||
priority: z.number().int().min(1).max(100).optional(),
|
||||
globalPriority: z.number().int().min(1).max(100).nullable().optional(),
|
||||
});
|
||||
|
||||
export const providerModelMutationSchema = z.object({
|
||||
provider: z.string().trim().min(1, "provider is required").max(120),
|
||||
modelId: z.string().trim().min(1, "modelId is required").max(240),
|
||||
modelName: z.string().trim().max(240).optional(),
|
||||
source: z.string().trim().max(80).optional(),
|
||||
apiFormat: z
|
||||
.enum([
|
||||
"chat-completions",
|
||||
"responses",
|
||||
"embeddings",
|
||||
"rerank",
|
||||
"audio-transcriptions",
|
||||
"audio-speech",
|
||||
"images-generations",
|
||||
])
|
||||
.default("chat-completions"),
|
||||
supportedEndpoints: z
|
||||
.array(
|
||||
z.enum([
|
||||
"chat",
|
||||
"embeddings",
|
||||
"rerank",
|
||||
"images",
|
||||
"audio",
|
||||
"audio-transcriptions",
|
||||
"audio-speech",
|
||||
"images-generations",
|
||||
])
|
||||
)
|
||||
.default(["chat"]),
|
||||
// #2905: optional per-model wire format override for custom models (e.g. a
|
||||
// custom opencode-go model that must use the Anthropic Messages shape).
|
||||
targetFormat: z
|
||||
.enum(["openai", "openai-responses", "claude", "gemini", "gemini-cli", "antigravity"])
|
||||
.optional(),
|
||||
normalizeToolCallId: z.boolean().optional(),
|
||||
preserveOpenAIDeveloperRole: z.boolean().nullable().optional(),
|
||||
upstreamHeaders: upstreamHeadersRecordSchema.nullable().optional(),
|
||||
/** Zod 4: `z.record(z.enum([...]), …)` requires every enum key; use `partialRecord` for sparse patches. */
|
||||
compatByProtocol: z
|
||||
.partialRecord(z.enum(["openai", "openai-responses", "claude"]), modelCompatPerProtocolSchema)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const updateModelAliasesSchema = z.object({
|
||||
aliases: z.record(z.string().trim().min(1), z.string().trim().min(1)),
|
||||
});
|
||||
|
||||
export const addModelAliasSchema = z.object({
|
||||
from: z.string().trim().min(1),
|
||||
to: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const removeModelAliasSchema = z.object({
|
||||
from: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const createProviderNodeSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1, "Name is required"),
|
||||
prefix: z.string().trim().min(1, "Prefix is required"),
|
||||
apiType: z
|
||||
.enum([
|
||||
"chat",
|
||||
"responses",
|
||||
"embeddings",
|
||||
"audio-transcriptions",
|
||||
"audio-speech",
|
||||
"images-generations",
|
||||
])
|
||||
.optional(),
|
||||
baseUrl: z.string().trim().min(1).optional(),
|
||||
type: z.enum(["openai-compatible", "anthropic-compatible"]).optional(),
|
||||
compatMode: z.enum(["cc"]).optional(),
|
||||
chatPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
|
||||
modelsPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
|
||||
customHeaders: customHeadersSchema,
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
const nodeType = value.type || "openai-compatible";
|
||||
if (nodeType === "openai-compatible" && !value.apiType) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Invalid OpenAI compatible API type",
|
||||
path: ["apiType"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const updateProviderNodeSchema = z.object({
|
||||
name: z.string().trim().min(1, "Name is required"),
|
||||
prefix: z.string().trim().min(1, "Prefix is required"),
|
||||
apiType: z
|
||||
.enum([
|
||||
"chat",
|
||||
"responses",
|
||||
"embeddings",
|
||||
"audio-transcriptions",
|
||||
"audio-speech",
|
||||
"images-generations",
|
||||
])
|
||||
.optional(),
|
||||
baseUrl: z.string().trim().min(1, "Base URL is required"),
|
||||
chatPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
|
||||
modelsPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
|
||||
customHeaders: customHeadersSchema,
|
||||
});
|
||||
|
||||
export const providerNodeValidateSchema = z.object({
|
||||
baseUrl: z.string().trim().min(1, "Base URL and API key required"),
|
||||
apiKey: z.string().trim().optional(),
|
||||
type: z.enum(["openai-compatible", "anthropic-compatible"]).optional(),
|
||||
compatMode: z.enum(["cc"]).optional(),
|
||||
chatPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
|
||||
modelsPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
|
||||
});
|
||||
|
||||
export const updateProviderConnectionSchema = z
|
||||
.object({
|
||||
name: z.string().max(200).optional(),
|
||||
priority: z.coerce.number().int().min(1).max(100).optional(),
|
||||
globalPriority: z.union([z.coerce.number().int().min(1).max(100), z.null()]).optional(),
|
||||
defaultModel: z.union([z.string().max(200), z.null()]).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
apiKey: z.string().max(10000).optional(),
|
||||
testStatus: z.string().max(50).optional(),
|
||||
lastError: z.union([z.string(), z.null()]).optional(),
|
||||
lastErrorAt: z.union([z.string(), z.null()]).optional(),
|
||||
lastErrorType: z.union([z.string(), z.null()]).optional(),
|
||||
lastErrorSource: z.union([z.string(), z.null()]).optional(),
|
||||
errorCode: z.union([z.string(), z.null()]).optional(),
|
||||
rateLimitedUntil: z.union([z.string(), z.null()]).optional(),
|
||||
lastTested: z.union([z.string(), z.null()]).optional(),
|
||||
healthCheckInterval: z.coerce.number().int().min(0).optional(),
|
||||
group: z.union([z.string().max(100), z.null()]).optional(),
|
||||
maxConcurrent: z.union([z.null(), z.coerce.number().int().min(0)]).optional(),
|
||||
// Per-window quota cutoffs. Map keys are window names (e.g. "window5h",
|
||||
// "window7d"); values are 0-100 integers, or null to clear that window's
|
||||
// override (the API route merges this into the existing map and prunes
|
||||
// null entries before persisting). The whole field set to null clears
|
||||
// every override on the connection.
|
||||
quotaWindowThresholds: z
|
||||
.union([
|
||||
z.null(),
|
||||
z.record(
|
||||
// Window keys mirror the quota names from getUsageForProvider —
|
||||
// bound for defense-in-depth so a malicious payload can't ship
|
||||
// megabyte-long keys that would bloat the DB row.
|
||||
z.string().min(1).max(64),
|
||||
z.union([z.null(), z.coerce.number().int().min(0).max(100)])
|
||||
),
|
||||
])
|
||||
.optional(),
|
||||
projectId: z.union([z.string(), z.null()]).optional(),
|
||||
// Per-connection rate limit overrides — overrides the global RequestQueueSettings
|
||||
// for this connection. Set to null to clear all overrides.
|
||||
rateLimitOverrides: z
|
||||
.union([
|
||||
z.null(),
|
||||
z.object({
|
||||
rpm: z.coerce.number().int().min(0).max(1_000_000).optional(),
|
||||
tpm: z.coerce.number().int().min(0).max(100_000_000).optional(),
|
||||
tpd: z.coerce.number().int().min(0).max(10_000_000_000).optional(),
|
||||
minTime: z.coerce.number().int().min(0).max(60_000).optional(),
|
||||
maxConcurrent: z.coerce.number().int().min(0).max(10_000).optional(),
|
||||
}),
|
||||
])
|
||||
.optional(),
|
||||
proxyEnabled: z.boolean().optional(),
|
||||
perKeyProxyEnabled: z.boolean().optional(),
|
||||
// Partial patch of per-connection provider-specific settings (e.g. quota toggles)
|
||||
providerSpecificData: z
|
||||
.record(z.string(), z.unknown())
|
||||
.optional()
|
||||
.superRefine((data, ctx) => {
|
||||
validateProviderSpecificData(data, ctx);
|
||||
}),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (Object.keys(value).length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const providersBatchTestSchema = z
|
||||
.object({
|
||||
mode: z.enum([
|
||||
"provider",
|
||||
"oauth",
|
||||
"free",
|
||||
"no-auth",
|
||||
"apikey",
|
||||
"compatible",
|
||||
"all",
|
||||
"web-cookie",
|
||||
"search",
|
||||
"audio",
|
||||
"local",
|
||||
"upstream-proxy",
|
||||
"cloud-agent",
|
||||
"ide",
|
||||
"selected",
|
||||
]),
|
||||
// Frontend may send null when mode != 'provider' — accept and treat as missing
|
||||
providerId: z.string().trim().min(1).nullable().optional(),
|
||||
// Explicit connection IDs to test — required when mode=selected
|
||||
connectionIds: z.array(z.string().trim().min(1)).max(100).nullable().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
// Treat null same as undefined
|
||||
const pid = value.providerId ?? null;
|
||||
if (value.mode === "provider" && !pid) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "providerId is required when mode=provider",
|
||||
path: ["providerId"],
|
||||
});
|
||||
}
|
||||
const ids = value.connectionIds ?? null;
|
||||
if (value.mode === "selected" && (!ids || ids.length === 0)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "connectionIds is required when mode=selected",
|
||||
path: ["connectionIds"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PATCH /api/providers — bulk activate/deactivate selected connections
|
||||
export const batchUpdateProviderConnectionsSchema = z.object({
|
||||
ids: z.array(z.string().trim().min(1)).min(1).max(100),
|
||||
isActive: z.boolean(),
|
||||
});
|
||||
|
||||
export const validateProviderApiKeySchema = z
|
||||
.object({
|
||||
provider: z.string().trim().min(1, "Provider and API key required"),
|
||||
apiKey: z.string().trim().optional(),
|
||||
validationModelId: z.string().trim().optional(),
|
||||
customUserAgent: z.string().trim().max(500).optional(),
|
||||
baseUrl: z.string().trim().url().optional(),
|
||||
region: z.string().trim().max(64).optional(),
|
||||
cx: z.string().trim().max(500).optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.provider === "google-pse-search" && !data.cx) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Programmable Search Engine ID (cx) is required",
|
||||
path: ["cx"],
|
||||
});
|
||||
}
|
||||
});
|
||||
186
src/shared/validation/schemas/proxy.ts
Normal file
186
src/shared/validation/schemas/proxy.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
|
||||
export const proxyConfigSchema = z
|
||||
.object({
|
||||
type: z
|
||||
.preprocess(
|
||||
(value) => (typeof value === "string" ? value.trim().toLowerCase() : value),
|
||||
z.enum(["http", "https", "socks5"])
|
||||
)
|
||||
.optional(),
|
||||
host: z.string().trim().min(1).optional(),
|
||||
port: z.coerce.number().int().min(1).max(65535).optional(),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const updateProxyConfigSchema = z
|
||||
.object({
|
||||
proxy: proxyConfigSchema.nullable().optional(),
|
||||
global: proxyConfigSchema.nullable().optional(),
|
||||
providers: z.record(z.string().trim().min(1), proxyConfigSchema.nullable()).optional(),
|
||||
combos: z.record(z.string().trim().min(1), proxyConfigSchema.nullable()).optional(),
|
||||
keys: z.record(z.string().trim().min(1), proxyConfigSchema.nullable()).optional(),
|
||||
level: z.enum(["global", "provider", "combo", "key"]).optional(),
|
||||
id: z.string().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
const hasPayload =
|
||||
value.proxy !== undefined ||
|
||||
value.global !== undefined ||
|
||||
value.providers !== undefined ||
|
||||
value.combos !== undefined ||
|
||||
value.keys !== undefined ||
|
||||
value.level !== undefined;
|
||||
|
||||
if (!hasPayload) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (value.level !== undefined && value.proxy === undefined) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "proxy is required when level is provided",
|
||||
path: ["proxy"],
|
||||
});
|
||||
}
|
||||
|
||||
if (value.level && value.level !== "global" && !value.id?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "id is required for provider/combo/key level updates",
|
||||
path: ["id"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const testProxySchema = z.object({
|
||||
proxy: z.object({
|
||||
type: z.string().optional(),
|
||||
host: z.string().trim().min(1, "proxy.host is required"),
|
||||
port: z.union([z.string(), z.number()]),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const inlineProxyAssignmentSchema = z
|
||||
.object({
|
||||
scope: z.enum(["global", "provider", "account", "combo", "key"]),
|
||||
scopeId: z.string().trim().nullable().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.scope !== "global" && !value.scopeId?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "scopeId is required for non-global scope",
|
||||
path: ["scopeId"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const proxyRegistryFieldsSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1, "name is required").max(120),
|
||||
type: z
|
||||
.preprocess(
|
||||
(value) => (typeof value === "string" ? value.trim().toLowerCase() : value),
|
||||
z.enum(["http", "https", "socks5", "vercel"])
|
||||
)
|
||||
.optional()
|
||||
.default("http"),
|
||||
host: z.string().trim().min(1, "host is required").max(255),
|
||||
port: z.coerce.number().int().min(1).max(65535),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
region: z.string().trim().max(64).nullable().optional(),
|
||||
notes: z.string().trim().max(1000).nullable().optional(),
|
||||
status: z.enum(["active", "inactive"]).optional().default("active"),
|
||||
source: z.enum(["manual", "oneproxy", "dashboard-custom", "vercel-relay"]).optional(),
|
||||
// Address-family egress policy (#3777): "auto" keeps the prior dual-stack behavior;
|
||||
// "ipv4"/"ipv6" pin the connection to that family (no v4 leak under an IPv6-only proxy).
|
||||
family: z.enum(["auto", "ipv4", "ipv6"]).optional().default("auto"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const createProxyRegistrySchema = proxyRegistryFieldsSchema
|
||||
.extend({
|
||||
assignment: inlineProxyAssignmentSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const updateProxyRegistrySchema = proxyRegistryFieldsSchema
|
||||
.partial()
|
||||
.extend({
|
||||
id: z.string().trim().min(1, "id is required"),
|
||||
assignment: inlineProxyAssignmentSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const bulkImportProxiesSchema = z
|
||||
.object({
|
||||
items: z
|
||||
.array(proxyRegistryFieldsSchema)
|
||||
.min(1, "At least one proxy is required")
|
||||
.max(100, "Maximum 100 proxies per import"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const proxyAssignmentSchema = z
|
||||
.object({
|
||||
scope: z.enum(["global", "provider", "account", "combo", "key"]),
|
||||
scopeId: z.string().trim().nullable().optional(),
|
||||
proxyId: z.string().trim().nullable().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.scope !== "global" && !value.scopeId?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "scopeId is required for provider/account/combo/key scope",
|
||||
path: ["scopeId"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const bulkProxyAssignmentSchema = z
|
||||
.object({
|
||||
scope: z.enum(["global", "provider", "account", "combo", "key"]),
|
||||
scopeIds: z.array(z.string().trim().min(1)).optional().default([]),
|
||||
proxyId: z.string().trim().nullable().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.scope !== "global" &&
|
||||
(!Array.isArray(value.scopeIds) || value.scopeIds.length === 0)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "scopeIds is required for provider/account/combo/key scope",
|
||||
path: ["scopeIds"],
|
||||
});
|
||||
}
|
||||
});
|
||||
88
src/shared/validation/schemas/routing.ts
Normal file
88
src/shared/validation/schemas/routing.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
import { modelIdSchema, jsonObjectSchema, resetStatsActionSchema } from "./misc.ts";
|
||||
|
||||
export const fallbackChainEntrySchema = z
|
||||
.object({
|
||||
provider: z.string().trim().min(1, "provider is required"),
|
||||
priority: z.number().int().min(1).max(100).optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
.catchall(z.unknown());
|
||||
|
||||
export const registerFallbackSchema = z.object({
|
||||
model: modelIdSchema,
|
||||
chain: z.array(fallbackChainEntrySchema).min(1, "chain must contain at least one provider"),
|
||||
});
|
||||
|
||||
export const removeFallbackSchema = z.object({
|
||||
model: modelIdSchema,
|
||||
});
|
||||
|
||||
export const updateModelAliasSchema = z.object({
|
||||
model: modelIdSchema,
|
||||
alias: z.string().trim().min(1, "Alias is required").max(200),
|
||||
});
|
||||
|
||||
export const intelligenceSyncRequestSchema = z
|
||||
.object({
|
||||
dryRun: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const taskRoutingModelMapSchema = z
|
||||
.object({
|
||||
coding: z.string().max(200).optional(),
|
||||
creative: z.string().max(200).optional(),
|
||||
analysis: z.string().max(200).optional(),
|
||||
vision: z.string().max(200).optional(),
|
||||
summarization: z.string().max(200).optional(),
|
||||
background: z.string().max(200).optional(),
|
||||
chat: z.string().max(200).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const updateTaskRoutingSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
taskModelMap: taskRoutingModelMapSchema.optional(),
|
||||
detectionEnabled: z.boolean().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.enabled === undefined &&
|
||||
value.taskModelMap === undefined &&
|
||||
value.detectionEnabled === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const taskRoutingActionSchema = z.discriminatedUnion("action", [
|
||||
resetStatsActionSchema,
|
||||
z
|
||||
.object({
|
||||
action: z.literal("detect"),
|
||||
body: jsonObjectSchema.optional(),
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
238
src/shared/validation/schemas/settings.ts
Normal file
238
src/shared/validation/schemas/settings.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import { HIDEABLE_SIDEBAR_GROUP_IDS } from "@/shared/constants/sidebarGroupVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
// ──── Settings Schemas ────
|
||||
// FASE-01: Removed .passthrough() — only explicitly listed fields are accepted
|
||||
|
||||
export const settingsFallbackStrategySchema = z.enum(ACCOUNT_FALLBACK_STRATEGY_VALUES);
|
||||
|
||||
// Single source of truth: ../settingsSchemas (the schema the runtime settings route validates
|
||||
// against). Re-exported here so this modular barrel stays in exact lockstep — a divergent local
|
||||
// copy (introduced by the #3988 lossy modularization) silently dropped 40 fields while gaining a
|
||||
// few others. The settings-schema parity test guards this; see QUALITY_GATE_PLAYBOOK Parte 6 (G2).
|
||||
export { updateSettingsSchema } from "../settingsSchemas";
|
||||
|
||||
export const legacyResilienceProfileSchema = z.object({
|
||||
transientCooldown: z.number().min(0),
|
||||
rateLimitCooldown: z.number().min(0),
|
||||
maxBackoffLevel: z.number().int().min(0),
|
||||
circuitBreakerThreshold: z.number().int().min(0),
|
||||
circuitBreakerReset: z.number().min(0),
|
||||
});
|
||||
|
||||
export const legacyResilienceDefaultsSchema = z
|
||||
.object({
|
||||
requestsPerMinute: z.number().int().min(1).optional(),
|
||||
minTimeBetweenRequests: z.number().int().min(0).optional(),
|
||||
concurrentRequests: z.number().int().min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const requestQueueSettingsSchema = z
|
||||
.object({
|
||||
autoEnableApiKeyProviders: z.boolean().optional(),
|
||||
requestsPerMinute: z.number().int().min(1).optional(),
|
||||
minTimeBetweenRequestsMs: z.number().int().min(0).optional(),
|
||||
concurrentRequests: z.number().int().min(1).optional(),
|
||||
maxWaitMs: z.number().int().min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const connectionCooldownProfileSchema = z
|
||||
.object({
|
||||
baseCooldownMs: z.number().int().min(0).optional(),
|
||||
useUpstreamRetryHints: z.boolean().optional(),
|
||||
// Issue #2100 follow-up: per-profile toggle for upstream 429 hint trust.
|
||||
// `null` is an explicit unset sentinel — PATCH handler deletes the key
|
||||
// from stored settings so the per-provider default resolves at runtime.
|
||||
// `undefined` (key omitted) means "leave existing value unchanged".
|
||||
useUpstream429BreakerHints: z.boolean().nullable().optional(),
|
||||
maxBackoffSteps: z.number().int().min(0).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const providerBreakerProfileSchema = z
|
||||
.object({
|
||||
failureThreshold: z.number().int().min(1).max(1000).optional(),
|
||||
degradationThreshold: z.number().int().min(1).max(1000).optional(),
|
||||
resetTimeoutMs: z.number().int().min(1000).optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
typeof value.failureThreshold === "number" &&
|
||||
value.failureThreshold > 1 &&
|
||||
typeof value.degradationThreshold === "number" &&
|
||||
value.degradationThreshold >= value.failureThreshold
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "degradationThreshold must be lower than failureThreshold",
|
||||
path: ["degradationThreshold"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const waitForCooldownSettingsSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
maxRetries: z.number().int().min(0).max(10).optional(),
|
||||
maxRetryWaitSec: z.number().int().min(0).max(300).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const providerCooldownSettingsSchema = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
minRetryCooldownMs: z.number().int().min(0).max(300000).optional(),
|
||||
maxRetryCooldownMs: z.number().int().min(0).max(3600000).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const updateResilienceSchema = z
|
||||
.object({
|
||||
requestQueue: requestQueueSettingsSchema.optional(),
|
||||
connectionCooldown: z
|
||||
.object({
|
||||
oauth: connectionCooldownProfileSchema.optional(),
|
||||
apikey: connectionCooldownProfileSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
providerBreaker: z
|
||||
.object({
|
||||
oauth: providerBreakerProfileSchema.optional(),
|
||||
apikey: providerBreakerProfileSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
waitForCooldown: waitForCooldownSettingsSchema.optional(),
|
||||
providerCooldown: providerCooldownSettingsSchema.optional(),
|
||||
profiles: z
|
||||
.object({
|
||||
oauth: legacyResilienceProfileSchema.optional(),
|
||||
apikey: legacyResilienceProfileSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
defaults: legacyResilienceDefaultsSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
!value.requestQueue &&
|
||||
!value.connectionCooldown &&
|
||||
!value.providerBreaker &&
|
||||
!value.waitForCooldown &&
|
||||
!value.providerCooldown &&
|
||||
!value.profiles &&
|
||||
!value.defaults
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Must provide resilience settings to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const updateRequireLoginSchema = z
|
||||
.object({
|
||||
requireLogin: z.boolean().optional(),
|
||||
password: z.string().min(4, "Password must be at least 4 characters").optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.requireLogin === undefined && !value.password) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const updateSystemPromptSchema = z
|
||||
.object({
|
||||
prompt: z.string().max(50000).optional(), // legacy compat
|
||||
prefixPrompt: z.string().max(50000).optional(),
|
||||
suffixPrompt: z.string().max(50000).optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.prompt === undefined &&
|
||||
value.prefixPrompt === undefined &&
|
||||
value.suffixPrompt === undefined &&
|
||||
value.enabled === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const updateThinkingBudgetSchema = z
|
||||
.object({
|
||||
mode: z.enum(["passthrough", "auto", "custom", "adaptive"]).optional(),
|
||||
customBudget: z.coerce.number().int().min(0).max(131072).optional(),
|
||||
effortLevel: z.enum(["none", "low", "medium", "high", "xhigh", "max"]).optional(),
|
||||
baseBudget: z.coerce.number().int().min(0).max(131072).optional(),
|
||||
complexityMultiplier: z.coerce.number().min(0).optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, ctx) => {
|
||||
if (
|
||||
value.mode === undefined &&
|
||||
value.customBudget === undefined &&
|
||||
value.effortLevel === undefined &&
|
||||
value.baseBudget === undefined &&
|
||||
value.complexityMultiplier === undefined
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No valid fields to update",
|
||||
path: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const guideSettingsSaveSchema = z
|
||||
.object({
|
||||
baseUrl: z.string().trim().min(1).optional(),
|
||||
// #3552: the CLI tool cards post `apiKey: null` in cloud mode (the real key is resolved
|
||||
// server-side from keyId), and `z.string().optional()` rejected null → 400. Normalize
|
||||
// null → undefined so validation passes and the keyId/default path is used.
|
||||
apiKey: z.preprocess((v) => (v === null ? undefined : v), z.string().optional()),
|
||||
model: z.string().trim().min(1, "Model is required").optional(),
|
||||
models: z.array(z.string().trim().min(1, "Models must be non-empty")).min(1).optional(),
|
||||
modelLabels: z.record(z.string(), z.string().trim().min(1)).optional(),
|
||||
})
|
||||
.refine((data) => !!data.model || !!data.models?.length, {
|
||||
message: "Model is required",
|
||||
path: ["model"],
|
||||
});
|
||||
|
||||
// ─── Auto-disable banned/error accounts ───────────────────────────────────
|
||||
export const updateAutoDisableAccountsSchema = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
threshold: z.number().int().min(1).max(10).optional(),
|
||||
})
|
||||
.strict();
|
||||
44
src/shared/validation/schemas/translator.ts
Normal file
44
src/shared/validation/schemas/translator.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ACCOUNT_FALLBACK_STRATEGY_VALUES,
|
||||
ROUTING_STRATEGY_VALUES,
|
||||
} from "@/shared/constants/routingStrategies";
|
||||
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
|
||||
import {
|
||||
isForbiddenUpstreamHeaderName,
|
||||
isForbiddenCustomHeaderName,
|
||||
} from "@/shared/constants/upstreamHeaders";
|
||||
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
|
||||
|
||||
import { nonEmptyJsonRecordSchema } from "./misc.ts";
|
||||
|
||||
export const translatorDetectSchema = z.object({
|
||||
body: nonEmptyJsonRecordSchema,
|
||||
});
|
||||
|
||||
export const translatorSendSchema = z.object({
|
||||
provider: z.string().trim().min(1, "Provider is required"),
|
||||
body: nonEmptyJsonRecordSchema,
|
||||
});
|
||||
|
||||
export const translatorTranslateSchema = z
|
||||
.object({
|
||||
step: z.union([z.number().int().min(1).max(4), z.literal("direct")]),
|
||||
provider: z.string().trim().min(1).optional(),
|
||||
body: nonEmptyJsonRecordSchema,
|
||||
sourceFormat: z.string().optional(),
|
||||
targetFormat: z.string().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.step !== "direct" && !value.provider) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Step and provider are required",
|
||||
path: ["provider"],
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -8,6 +8,7 @@
|
||||
import { z } from "zod";
|
||||
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
|
||||
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
|
||||
import { HIDEABLE_SIDEBAR_GROUP_IDS } from "@/shared/constants/sidebarGroupVisibility";
|
||||
import { HIDEABLE_SIDEBAR_ITEM_IDS, SIDEBAR_SECTIONS } from "@/shared/constants/sidebarVisibility";
|
||||
import { ACCOUNT_FALLBACK_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";
|
||||
import { RESPONSES_PREVIOUS_RESPONSE_ID_MODES } from "@/shared/constants/responsesPreviousResponseId";
|
||||
@@ -42,7 +43,6 @@ export const updateSettingsSchema = z.object({
|
||||
pinProviderQuotaToHome: z.boolean().optional(),
|
||||
showQuickStartOnHome: z.boolean().optional(),
|
||||
showProviderTopologyOnHome: z.boolean().optional(),
|
||||
showTokenSaverOnEndpoint: z.boolean().optional(),
|
||||
localOnlyManageScopeBypassEnabled: z.boolean().optional(),
|
||||
// Layer 1 of the spawn-capable guard (Hard Rules #15/#17): reject any bypass
|
||||
// prefix that reaches a SPAWN_CAPABLE_PREFIXES path at PATCH time, with the
|
||||
@@ -71,6 +71,7 @@ export const updateSettingsSchema = z.object({
|
||||
customBannedSignals: z.array(z.string().max(200)).optional(),
|
||||
debugMode: z.boolean().optional(),
|
||||
hiddenSidebarItems: z.array(z.enum(HIDEABLE_SIDEBAR_ITEM_IDS)).optional(),
|
||||
hiddenSidebarGroupLabels: z.array(z.enum(HIDEABLE_SIDEBAR_GROUP_IDS)).optional(),
|
||||
sidebarSectionOrder: z
|
||||
.array(z.enum(SIDEBAR_SECTIONS.map((s) => s.id) as [string, ...string[]]))
|
||||
.optional(),
|
||||
@@ -332,8 +333,8 @@ export const updateSettingsSchema = z.object({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const databaseSettingsSchema = z.object(
|
||||
{
|
||||
export const databaseSettingsSchema = z
|
||||
.object({
|
||||
// Logs settings
|
||||
logs: z.object({
|
||||
detailedLogsEnabled: z.boolean(),
|
||||
@@ -397,7 +398,8 @@ export const databaseSettingsSchema = z.object(
|
||||
}),
|
||||
|
||||
// Skip location and stats as they're read-only
|
||||
}).strict();
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type DatabaseSettingsSchema = z.infer<typeof databaseSettingsSchema>;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user