Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **feat(oauth):** per-connection Claude OAuth raw passthrough: skip CLI emulation, fingerprint rewrite, and CCH body signing when `providerSpecificData.rawPassthrough` is true. Dashboard toggle for Claude OAuth connections; nested aliases are stripped on save. ([#14053](https://github.com/diegosouzapw/OmniRoute/pull/14053))
39 changes: 33 additions & 6 deletions open-sse/executors/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ import {
} from "../services/tokenRefresh.ts";
import type { ProviderRequestDefaults } from "../services/providerRequestDefaults.ts";
import { signRequestBody } from "../services/claudeCodeCCH.ts";
import {
applyFinalClaudeRawPassthroughHeaders,
isConnectionRawPassthrough,
} from "../utils/cacheControlPolicy.ts";
import { normalizeCacheControlTtl } from "../services/claudeCodeConstraints.ts";
import {
appendAnthropicBetaHeader,
Expand Down Expand Up @@ -214,6 +218,10 @@ export type ExecuteInput = {
* `context_management.clear_tool_uses` strategy so the provider clears stale
* tool-use blocks server-side. Honored only on the genuine `claude` path. */
contextEditing?: { enabled: boolean } | null;
/** chatCore-computed marker: client spoke and expects the native Claude
* Messages format (no translation). Combined with the per-connection
* `rawPassthrough` switch to decide whether the CLI cloak is skipped. */
isClaudePassthrough?: boolean;
};

export type CountTokensInput = {
Expand Down Expand Up @@ -724,6 +732,7 @@ export class BaseExecutor {
skipUpstreamRetry = false,
onCredentialsRefreshed,
contextEditing,
isClaudePassthrough,
} = input;
assertValidationCredentials(input.validationDispatch, credentials);
const fallbackCount = this.getFallbackCount();
Expand Down Expand Up @@ -999,7 +1008,18 @@ export class BaseExecutor {
activeCredentials.accessToken.startsWith("sk-ant-oat") &&
!activeCredentials?.apiKey;

// #13893 raw passthrough: four-condition AND gate (spec §3.3). All of
// native-format client, genuine `claude` provider, official OAuth token
// and the per-connection opt-in flag must hold; otherwise the standard
// CLI cloak pipeline below runs unchanged.
const isRawPassthrough =
isClaudePassthrough === true &&
this.provider === "claude" &&
hasClaudeOAuthToken &&
isConnectionRawPassthrough(requestCredentials?.providerSpecificData);

if (
!isRawPassthrough &&
((this.provider === "claude" && (isClaudeCodeClient || hasClaudeOAuthToken)) ||
usesClaudeCodeProtocol) &&
typeof transformedBody === "object" &&
Expand Down Expand Up @@ -1405,8 +1425,9 @@ export class BaseExecutor {
let bodyString = JSON.stringify(transformedBody);

const shouldFingerprint =
isCliCompatEnabled(fingerprintProvider) ||
(this.provider === "claude" && (isClaudeCodeClient || hasClaudeOAuthToken));
!isRawPassthrough &&
(isCliCompatEnabled(fingerprintProvider) ||
(this.provider === "claude" && (isClaudeCodeClient || hasClaudeOAuthToken)));
if (shouldFingerprint) {
const fingerprinted = applyFingerprint(fingerprintProvider, headers, transformedBody);
finalHeaders = fingerprinted.headers;
Expand All @@ -1415,11 +1436,17 @@ export class BaseExecutor {

// CCH signing — replaces the cch=00000 placeholder in the billing
// header with an xxHash64 integrity token over the serialized body.
if (usesClaudeCodeProtocol || this.provider === "claude") {
// #13893: skipped entirely in raw passthrough mode (spec §3.3 rule 4).
const shouldSignBody =
!isRawPassthrough && (usesClaudeCodeProtocol || this.provider === "claude");
if (shouldSignBody) {
bodyString = await signRequestBody(bodyString);
}

mergeUpstreamExtraHeaders(finalHeaders, upstreamExtraHeaders);
if (isRawPassthrough) {
applyFinalClaudeRawPassthroughHeaders(finalHeaders, clientHeaders);
}
if (this.provider === "cline" || this.provider === "clinepass") {
applyClineProtocolHeaders(finalHeaders, {
taskId: headers["X-Task-ID"],
Expand Down Expand Up @@ -1515,7 +1542,7 @@ export class BaseExecutor {
contextEditingDisabled = true;
delete (transformedBody as Record<string, unknown>).context_management;
let retryBody = JSON.stringify(transformedBody);
if (usesClaudeCodeProtocol || this.provider === "claude") {
if (shouldSignBody) {
retryBody = await signRequestBody(retryBody);
}
log?.debug?.(
Expand Down Expand Up @@ -1554,7 +1581,7 @@ export class BaseExecutor {
thinkingBudgetClampedMax = upstreamMax;
if (clampNestedThinkingBudget(transformedBody, upstreamMax)) {
let retryBody = JSON.stringify(transformedBody);
if (usesClaudeCodeProtocol || this.provider === "claude") {
if (shouldSignBody) {
retryBody = await signRequestBody(retryBody);
}
log?.info?.(
Expand All @@ -1568,7 +1595,7 @@ export class BaseExecutor {

const serializeRetryBody = async (b: unknown) => {
let retryBody = JSON.stringify(b);
if (usesClaudeCodeProtocol || this.provider === "claude") {
if (shouldSignBody) {
retryBody = await signRequestBody(retryBody);
}
return retryBody;
Expand Down
1 change: 1 addition & 0 deletions open-sse/handlers/chatCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3024,6 +3024,7 @@ async function handleChatCoreInner({
clientResponseFormat,
connectionId,
contextEditingEnabled,
isClaudePassthrough,
correlationId,
credentials,
dedupEnabled,
Expand Down
4 changes: 4 additions & 0 deletions open-sse/handlers/chatCore/executeProviderRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export type ExecuteProviderRequestDeps = {
clientResponseFormat: string | null | undefined;
connectionId: string | null | undefined;
contextEditingEnabled?: boolean;
isClaudePassthrough?: boolean;
correlationId: string | null | undefined;
credentials: Record<string, unknown> | null | undefined;
dedupEnabled: boolean;
Expand Down Expand Up @@ -162,6 +163,7 @@ export async function executeProviderRequest(
clientResponseFormat,
connectionId,
contextEditingEnabled,
isClaudePassthrough,
correlationId,
credentials,
dedupEnabled,
Expand Down Expand Up @@ -351,6 +353,7 @@ export async function executeProviderRequest(
onCredentialsRefreshed,
skipUpstreamRetry,
contextEditing: { enabled: contextEditingEnabled },
isClaudePassthrough,
correlationId,
})
),
Expand Down Expand Up @@ -557,6 +560,7 @@ export async function executeProviderRequest(
onCredentialsRefreshed,
skipUpstreamRetry,
contextEditing: { enabled: contextEditingEnabled },
isClaudePassthrough,
correlationId,
})
),
Expand Down
150 changes: 150 additions & 0 deletions open-sse/utils/cacheControlPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,25 @@ export function resolveConnectionCacheOverride(
return Object.keys(result).length > 0 ? result : null;
}

/**
* Per-connection Claude OAuth raw-passthrough hatch (#13893).
*
* Same bag as `resolveConnectionCacheOverride`: `providerSpecificData`.
* Default off. Only an own-property top-level boolean counts; nested
* `passthrough.raw` aliases never arm the hatch.
*/
export function isConnectionRawPassthrough(providerSpecificData: unknown): boolean {
if (
!providerSpecificData ||
typeof providerSpecificData !== "object" ||
Array.isArray(providerSpecificData)
) {
return false;
}
const record = providerSpecificData as Record<string, unknown>;
return Object.hasOwn(record, "rawPassthrough") && record.rawPassthrough === true;
}

/**
* Whether `cache_control` markers should be PASSED THROUGH the OpenAI-format
* translation for this provider (vs. stripped). Used to gate the request-side
Expand Down Expand Up @@ -434,3 +453,134 @@ export function updateCacheTokenMetrics({
metrics.lastUpdated = new Date().toISOString();
return metrics;
}

/**
* Persist the dashboard toggle as a top-level boolean (#13893).
* Nested `passthrough.raw` aliases are stripped on save so an import cannot
* re-arm the hatch after the operator turns it off.
*/
export function applyClaudeRawPassthroughSave(
providerSpecificData: Record<string, unknown>,
rawPassthrough: boolean
): void {
providerSpecificData.rawPassthrough = rawPassthrough;
if (
providerSpecificData.passthrough &&
typeof providerSpecificData.passthrough === "object" &&
!Array.isArray(providerSpecificData.passthrough)
) {
const pt = { ...(providerSpecificData.passthrough as Record<string, unknown>) };
delete pt.raw;
delete pt.rawPassthrough;
if (Object.keys(pt).length === 0) {
delete providerSpecificData.passthrough;
} else {
providerSpecificData.passthrough = pt;
}
}
}

/**
* Final outgoing-header sanitization for raw passthrough mode (spec §3.3 rule 1).
*
* Strips CLI-emulation leftovers (x-app, anthropic-dangerous-direct-browser-access,
* x-stainless-*), RFC 9110 hop-by-hop fields (static list + the client's dynamic
* Connection header nominations), and merges lawful client business headers with
* case-variant deduplication.
*
* Gateway auth headers (authorization, x-api-key, cookie, etc.) cannot be
* nominated off the Connection list (spec §3.3 rule 1, R5 hardening D-01).
*/
export function applyFinalClaudeRawPassthroughHeaders(
headers: Record<string, string>,
clientHeaders?: Record<string, string> | null
): void {
// 0. Gateway-owned credential/sensitive headers: a client Connection nomination
// must never strip these.
const gatewayAuthHeaders = new Set([
"authorization",
"x-api-key",
"x-goog-api-key",
"api-key",
"cookie",
]);

// 1. Parse the client Connection header for dynamic hop-by-hop fields (RFC 9110 §7.6.1).
const dynamicHopTokens = new Set<string>();
if (clientHeaders && typeof clientHeaders === "object") {
for (const [k, v] of Object.entries(clientHeaders)) {
if (k.toLowerCase() === "connection" && typeof v === "string") {
for (const token of v.split(",")) {
const trimmed = token.trim().toLowerCase();
if (trimmed && !gatewayAuthHeaders.has(trimmed)) {
dynamicHopTokens.add(trimmed);
}
}
}
}
}

// 2. Static hop-by-hop and transport-framing headers (RFC 9110 / RFC 7230).
const staticHopByHop = new Set([
"connection",
"proxy-connection",
"keep-alive",
"transfer-encoding",
"te",
"trailer",
"upgrade",
"proxy-authenticate",
"proxy-authorization",
"host",
"content-length",
"content-encoding",
]);

// 3. Strip CLI-emulation markers and hop-by-hop fields from the existing header set.
for (const key of Object.keys(headers)) {
const lower = key.toLowerCase();
if (
lower === "x-app" ||
lower === "anthropic-dangerous-direct-browser-access" ||
lower.startsWith("x-stainless-") ||
dynamicHopTokens.has(lower) ||
staticHopByHop.has(lower)
) {
delete headers[key];
}
}

// 4. Merge client business headers (exclusive overwrite with case-variant dedupe).
if (clientHeaders && typeof clientHeaders === "object") {
for (const [k, v] of Object.entries(clientHeaders)) {
if (typeof v !== "string") continue;
const lower = k.toLowerCase();

// Never forward client local auth, hop-by-hop fields, or gateway-internal prefixes.
if (
dynamicHopTokens.has(lower) ||
staticHopByHop.has(lower) ||
gatewayAuthHeaders.has(lower) ||
lower.startsWith("x-omniroute-")
) {
continue;
}

// Remove existing case-variant keys so the underlying runtime cannot comma-splice duplicates (#1454).
for (const existingKey of Object.keys(headers)) {
if (existingKey.toLowerCase() === lower) {
delete headers[existingKey];
}
}

headers[k] = v;
}
}

// 5. Anthropic requires anthropic-version on /v1/messages. If client didn't supply one,
// default to 2023-06-01 so the request doesn't 400 upstream.
const hasVersion = Object.keys(headers).some((k) => k.toLowerCase() === "anthropic-version");
if (!hasVersion) {
headers["anthropic-version"] = "2023-06-01";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type ClaudeConnectionFieldsProps = {
blockExtraUsage: boolean;
lowPriorityMode: boolean;
autoLimitReset: boolean;
rawPassthrough?: boolean;
};
/** The usage-wall options only exist for subscription (OAuth) connections. */
showUsageWallOptions: boolean;
Expand Down Expand Up @@ -44,6 +45,19 @@ export default function ClaudeConnectionFields(props: ClaudeConnectionFieldsProp
label={t("claudeAutoLimitResetLabel")}
description={t("claudeAutoLimitResetDescription")}
/>
<div className="flex flex-col gap-2">
<Toggle
checked={props.values.rawPassthrough === true}
onChange={(checked) => props.onChange({ rawPassthrough: checked })}
label={t("rawClaudePassthroughLabel")}
description={t("rawClaudePassthroughDescription")}
/>
{props.values.rawPassthrough && (
<p className="text-xs text-amber-500/90 dark:text-amber-400/90">
{t("rawClaudePassthroughWarning")}
</p>
)}
</div>
</>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { isClaudeExtraUsageBlockEnabled } from "@/lib/providers/claudeExtraUsage";
import {
applyClaudeRawPassthroughSave,
isConnectionRawPassthrough,
} from "@omniroute/open-sse/utils/cacheControlPolicy.ts";

export type ClaudeConnectionFieldValues = {
blockExtraUsage: boolean;
lowPriorityMode: boolean;
autoLimitReset: boolean;
rawPassthrough: boolean;
};

/**
Expand All @@ -19,16 +24,19 @@ export function claudeConnectionFieldValues(
blockExtraUsage: isClaudeExtraUsageBlockEnabled(provider, providerSpecificData),
lowPriorityMode: providerSpecificData?.lowPriorityMode === true,
autoLimitReset: providerSpecificData?.autoLimitReset === true,
rawPassthrough: isConnectionRawPassthrough(providerSpecificData),
};
}

/** The same three fields on their way back into `providerSpecificData` on save. */
/** The same fields on their way back into `providerSpecificData` on save. */
export function claudeConnectionFieldPatch(
values: ClaudeConnectionFieldValues
): ClaudeConnectionFieldValues {
return {
): Record<string, unknown> {
const patch: Record<string, unknown> = {
blockExtraUsage: values.blockExtraUsage,
lowPriorityMode: values.lowPriorityMode,
autoLimitReset: values.autoLimitReset,
};
applyClaudeRawPassthroughSave(patch, values.rawPassthrough === true);
return patch;
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type FormData = QuotaScrapingFieldValues &
newApiAggregatorBalance: boolean;
newApiUserId: string;
passthroughModels: boolean;
rawPassthrough?: boolean;
quotaPerUnit: string;
region: string;
routingTags: string;
Expand Down
5 changes: 4 additions & 1 deletion src/i18n/messages/am.json
Original file line number Diff line number Diff line change
Expand Up @@ -6739,7 +6739,10 @@
"rateLimitOverridesModelConcurrencyLabel": "Per-model concurrency caps",
"rateLimitOverridesModelConcurrencyPlaceholder": "glm-5=1\nglm-4.7=3",
"rateLimitOverridesModelConcurrencyHint": "Optional: one model=cap per line, matched against the exact upstream model id. Queues excess requests locally; blank means no per-model cap.",
"rateLimitOverridesModelConcurrencyInvalid": "Invalid per-model concurrency entry \"{entry}\" — use model=cap with a whole number from 1 to {max}."
"rateLimitOverridesModelConcurrencyInvalid": "Invalid per-model concurrency entry \"{entry}\" — use model=cap with a whole number from 1 to {max}.",
"rawClaudePassthroughLabel": "Raw Request Passthrough",
"rawClaudePassthroughDescription": "Forward client requests directly without CLI emulation or cache header modification.",
"rawClaudePassthroughWarning": "Notice: This mode disables request rewriting. It does not alter credential permissions, terms of service, or billing policies. Requests may be rejected by the provider, and any additional usage fees depend on your account plan. Third-party integrations should use authorized API credentials."
},
"settings": {
"title": "ቅንብሮች",
Expand Down
Loading
Loading