mirror of
https://github.com/fawney19/Aether.git
synced 2026-10-08 10:27:46 +08:00
refactor(workspace): enforce layered crate boundaries
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
use super::super::auth::resolve_local_standard_auth;
|
||||
use super::super::snapshot::GatewayProviderTransportSnapshot;
|
||||
use super::super::supports_local_oauth_request_auth_resolution;
|
||||
|
||||
pub fn supports_local_claude_code_auth(transport: &GatewayProviderTransportSnapshot) -> bool {
|
||||
resolve_local_standard_auth(transport).is_some_and(|(_, value)| !value.trim().is_empty())
|
||||
|| supports_local_oauth_request_auth_resolution(transport)
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
use aether_contracts::{
|
||||
TRANSPORT_BACKEND_REQWEST_RUSTLS, TRANSPORT_HTTP_MODE_AUTO, TRANSPORT_POOL_SCOPE_KEY,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
// Chrome impersonate profiles
|
||||
const CHROME_IMPERSONATE_PROFILES: &[&str] = &[
|
||||
"chrome110",
|
||||
"chrome116",
|
||||
"chrome119",
|
||||
"chrome120",
|
||||
"chrome123",
|
||||
"chrome124",
|
||||
"chrome131",
|
||||
"chrome133",
|
||||
];
|
||||
|
||||
const CHROME_VERSIONS: &[(&str, &str)] = &[
|
||||
("chrome110", "110.0.5481.177"),
|
||||
("chrome116", "116.0.5845.188"),
|
||||
("chrome119", "119.0.6045.214"),
|
||||
("chrome120", "120.0.6099.216"),
|
||||
("chrome123", "123.0.6312.122"),
|
||||
("chrome124", "124.0.6367.243"),
|
||||
("chrome131", "131.0.6778.265"),
|
||||
("chrome133", "133.0.6943.142"),
|
||||
];
|
||||
|
||||
// (os, arch, platform_token, platform_info)
|
||||
const PLATFORM_VARIANTS: &[(&str, &str, &str, &str)] = &[
|
||||
("Linux", "x64", "X11; Linux x86_64", "Linux x86_64"),
|
||||
("Linux", "arm64", "X11; Linux arm64", "Linux arm64"),
|
||||
(
|
||||
"Windows",
|
||||
"x64",
|
||||
"Windows NT 10.0; Win64; x64",
|
||||
"Windows x64",
|
||||
),
|
||||
(
|
||||
"MacOS",
|
||||
"x64",
|
||||
"Macintosh; Intel Mac OS X 10_15_7",
|
||||
"Darwin x64",
|
||||
),
|
||||
(
|
||||
"MacOS",
|
||||
"arm64",
|
||||
"Macintosh; ARM Mac OS X 14_0_0",
|
||||
"Darwin arm64",
|
||||
),
|
||||
];
|
||||
|
||||
const STAINLESS_PACKAGE_VERSIONS: &[&str] = &["0.68.0", "0.69.0", "0.70.0", "0.71.0"];
|
||||
const NODE_VERSIONS: &[&str] = &["v20.18.1", "v22.12.0", "v22.14.0", "v24.13.0"];
|
||||
const ELECTRON_VERSIONS: &[&str] = &["35.5.1", "36.7.1", "37.3.0", "38.7.0", "39.2.3"];
|
||||
const STAINLESS_TIMEOUTS: &[&str] = &["600", "900"];
|
||||
const CLAUDE_CODE_TRANSPORT_PROFILE_ID: &str = "claude_code_nodejs";
|
||||
|
||||
/// Deterministic hash-based index picker, compatible with Python implementation.
|
||||
/// Each `slot` produces a different selection from the same seed.
|
||||
struct SeededPicker {
|
||||
seed_bytes: [u8; 32],
|
||||
}
|
||||
|
||||
impl SeededPicker {
|
||||
fn new(seed: &str) -> Self {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(seed.as_bytes());
|
||||
Self {
|
||||
seed_bytes: hasher.finalize().into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick an index from `[0, len)` using a specific slot.
|
||||
/// Different slots produce independent-looking selections from the same seed.
|
||||
fn pick(&self, slot: u8, len: usize) -> usize {
|
||||
if len == 0 {
|
||||
return 0;
|
||||
}
|
||||
// Hash seed_bytes + slot to get a new digest, take first 8 bytes as u64
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(self.seed_bytes);
|
||||
hasher.update([slot]);
|
||||
let hash = hasher.finalize();
|
||||
let value = u64::from_be_bytes(hash[..8].try_into().unwrap());
|
||||
(value % len as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
fn chrome_version_for_profile(profile: &str) -> &'static str {
|
||||
for (p, v) in CHROME_VERSIONS {
|
||||
if p.eq_ignore_ascii_case(profile) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
"120.0.6099.216"
|
||||
}
|
||||
|
||||
fn build_user_agent(platform_token: &str, chrome_version: &str, electron_version: &str) -> String {
|
||||
format!(
|
||||
"Mozilla/5.0 ({platform_token}) AppleWebKit/537.36 (KHTML, like Gecko) \
|
||||
Chrome/{chrome_version} Electron/{electron_version} Safari/537.36"
|
||||
)
|
||||
}
|
||||
|
||||
fn resolve_platform_token(os: &str, arch: &str) -> &'static str {
|
||||
let os_lower = os.to_ascii_lowercase();
|
||||
let arch_lower = arch.to_ascii_lowercase();
|
||||
|
||||
if os_lower.starts_with("win") {
|
||||
return "Windows NT 10.0; Win64; x64";
|
||||
}
|
||||
if matches!(os_lower.as_str(), "darwin" | "mac" | "macos") {
|
||||
return if matches!(arch_lower.as_str(), "arm64" | "aarch64") {
|
||||
"Macintosh; ARM Mac OS X 14_0_0"
|
||||
} else {
|
||||
"Macintosh; Intel Mac OS X 10_15_7"
|
||||
};
|
||||
}
|
||||
if matches!(arch_lower.as_str(), "arm64" | "aarch64") {
|
||||
"X11; Linux arm64"
|
||||
} else {
|
||||
"X11; Linux x86_64"
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a complete Claude Code transport fingerprint from a seed.
|
||||
pub fn generate_fingerprint(seed: &str) -> Value {
|
||||
wrap_header_fingerprint(generate_header_fingerprint(seed))
|
||||
}
|
||||
|
||||
fn generate_header_fingerprint(seed: &str) -> Value {
|
||||
let picker = SeededPicker::new(seed);
|
||||
|
||||
let impersonate =
|
||||
CHROME_IMPERSONATE_PROFILES[picker.pick(0, CHROME_IMPERSONATE_PROFILES.len())];
|
||||
let chrome_version = chrome_version_for_profile(impersonate);
|
||||
let node_version = NODE_VERSIONS[picker.pick(1, NODE_VERSIONS.len())];
|
||||
let electron_version = ELECTRON_VERSIONS[picker.pick(2, ELECTRON_VERSIONS.len())];
|
||||
let platform = PLATFORM_VARIANTS[picker.pick(3, PLATFORM_VARIANTS.len())];
|
||||
let (stainless_os, stainless_arch, platform_token, platform_info) = platform;
|
||||
let stainless_package_version =
|
||||
STAINLESS_PACKAGE_VERSIONS[picker.pick(4, STAINLESS_PACKAGE_VERSIONS.len())];
|
||||
let stainless_timeout = STAINLESS_TIMEOUTS[picker.pick(5, STAINLESS_TIMEOUTS.len())];
|
||||
|
||||
let vscode_session_id = Uuid::new_v5(
|
||||
&Uuid::NAMESPACE_URL,
|
||||
format!("aether:fingerprint:{seed}").as_bytes(),
|
||||
)
|
||||
.simple()
|
||||
.to_string();
|
||||
|
||||
let user_agent = build_user_agent(platform_token, chrome_version, electron_version);
|
||||
|
||||
serde_json::json!({
|
||||
"impersonate": impersonate,
|
||||
"stainless_package_version": stainless_package_version,
|
||||
"stainless_os": stainless_os,
|
||||
"stainless_arch": stainless_arch,
|
||||
"stainless_runtime_version": node_version,
|
||||
"stainless_timeout": stainless_timeout,
|
||||
"node_version": node_version,
|
||||
"chrome_version": chrome_version,
|
||||
"electron_version": electron_version,
|
||||
"vscode_session_id": vscode_session_id,
|
||||
"platform_info": platform_info,
|
||||
"user_agent": user_agent,
|
||||
})
|
||||
}
|
||||
|
||||
fn wrap_header_fingerprint(header_fingerprint: Value) -> Value {
|
||||
serde_json::json!({
|
||||
"transport_profile": {
|
||||
"profile_id": CLAUDE_CODE_TRANSPORT_PROFILE_ID,
|
||||
"backend": TRANSPORT_BACKEND_REQWEST_RUSTLS,
|
||||
"http_mode": TRANSPORT_HTTP_MODE_AUTO,
|
||||
"pool_scope": TRANSPORT_POOL_SCOPE_KEY,
|
||||
"header_fingerprint": header_fingerprint,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn header_fingerprint_from_fingerprint(fingerprint: &Value) -> Option<&Map<String, Value>> {
|
||||
fingerprint
|
||||
.get("transport_profile")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|profile| profile.get("header_fingerprint"))
|
||||
.and_then(Value::as_object)
|
||||
}
|
||||
|
||||
/// Generate a random (non-deterministic) fingerprint.
|
||||
pub fn generate_random_fingerprint() -> Value {
|
||||
let random_seed = Uuid::new_v4().to_string();
|
||||
generate_fingerprint(&random_seed)
|
||||
}
|
||||
|
||||
/// Sanitize an existing fingerprint JSON, filling missing fields with
|
||||
/// deterministic fallbacks derived from `key_id`.
|
||||
pub fn sanitize_fingerprint(raw: &Value, key_id: &str) -> Value {
|
||||
let generated = generate_header_fingerprint(key_id);
|
||||
let gen_map = generated.as_object().unwrap();
|
||||
let raw_map = header_fingerprint_from_fingerprint(raw);
|
||||
|
||||
let mut out = Map::new();
|
||||
|
||||
// Start with generated values, then overlay non-empty raw values
|
||||
for (key, gen_value) in gen_map {
|
||||
let value = raw_map
|
||||
.and_then(|raw_map| raw_map.get(key))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(|v| Value::String(v.to_string()))
|
||||
.unwrap_or_else(|| gen_value.clone());
|
||||
out.insert(key.clone(), value);
|
||||
}
|
||||
|
||||
// Normalize impersonate to known profile
|
||||
let impersonate = out
|
||||
.get("impersonate")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let is_known = CHROME_IMPERSONATE_PROFILES
|
||||
.iter()
|
||||
.any(|p| p.eq_ignore_ascii_case(&impersonate));
|
||||
if !is_known {
|
||||
out.insert("impersonate".to_string(), gen_map["impersonate"].clone());
|
||||
}
|
||||
|
||||
// Ensure chrome_version matches impersonate profile
|
||||
let profile = out
|
||||
.get("impersonate")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let chrome_version = chrome_version_for_profile(profile);
|
||||
out.insert(
|
||||
"chrome_version".to_string(),
|
||||
Value::String(chrome_version.to_string()),
|
||||
);
|
||||
|
||||
// Rebuild user_agent if missing
|
||||
let has_ua = out
|
||||
.get("user_agent")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|v| !v.is_empty());
|
||||
if !has_ua {
|
||||
let os = out
|
||||
.get("stainless_os")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Linux");
|
||||
let arch = out
|
||||
.get("stainless_arch")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("x64");
|
||||
let electron = out
|
||||
.get("electron_version")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("38.7.0");
|
||||
let platform_token = resolve_platform_token(os, arch);
|
||||
out.insert(
|
||||
"user_agent".to_string(),
|
||||
Value::String(build_user_agent(platform_token, chrome_version, electron)),
|
||||
);
|
||||
}
|
||||
|
||||
wrap_header_fingerprint(Value::Object(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deterministic_generation_from_seed() {
|
||||
let fp1 = generate_fingerprint("key-abc-123");
|
||||
let fp2 = generate_fingerprint("key-abc-123");
|
||||
assert_eq!(fp1, fp2, "same seed should produce identical fingerprint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_seeds_produce_different_fingerprints() {
|
||||
let fp1 = generate_fingerprint("key-1");
|
||||
let fp2 = generate_fingerprint("key-2");
|
||||
// At least one field should differ (statistically near-certain)
|
||||
assert_ne!(fp1, fp2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_fingerprint_has_all_fields() {
|
||||
let fp = generate_fingerprint("test-key");
|
||||
let expected_keys = [
|
||||
"impersonate",
|
||||
"stainless_package_version",
|
||||
"stainless_os",
|
||||
"stainless_arch",
|
||||
"stainless_runtime_version",
|
||||
"stainless_timeout",
|
||||
"node_version",
|
||||
"chrome_version",
|
||||
"electron_version",
|
||||
"vscode_session_id",
|
||||
"platform_info",
|
||||
"user_agent",
|
||||
];
|
||||
let map = header_fingerprint_from_fingerprint(&fp).unwrap();
|
||||
for key in expected_keys {
|
||||
assert!(map.contains_key(key), "missing field: {key}");
|
||||
let value = map[key].as_str().unwrap();
|
||||
assert!(!value.is_empty(), "empty field: {key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_preserves_user_overrides() {
|
||||
let raw = serde_json::json!({
|
||||
"transport_profile": {
|
||||
"profile_id": "claude_code_nodejs",
|
||||
"header_fingerprint": {
|
||||
"stainless_os": "MacOS",
|
||||
"stainless_arch": "arm64",
|
||||
"stainless_timeout": "900",
|
||||
"user_agent": "Custom-Agent/1.0"
|
||||
}
|
||||
}
|
||||
});
|
||||
let sanitized = sanitize_fingerprint(&raw, "test-key");
|
||||
let map = header_fingerprint_from_fingerprint(&sanitized).unwrap();
|
||||
assert_eq!(map["stainless_os"].as_str(), Some("MacOS"));
|
||||
assert_eq!(map["stainless_arch"].as_str(), Some("arm64"));
|
||||
assert_eq!(map["stainless_timeout"].as_str(), Some("900"));
|
||||
assert_eq!(map["user_agent"].as_str(), Some("Custom-Agent/1.0"));
|
||||
// Other fields should be filled from generation
|
||||
assert!(map.contains_key("impersonate"));
|
||||
assert!(map.contains_key("stainless_package_version"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_fills_missing_fields_from_seed() {
|
||||
let raw = serde_json::json!({});
|
||||
let sanitized = sanitize_fingerprint(&raw, "test-key");
|
||||
let generated = generate_header_fingerprint("test-key");
|
||||
// All fields should match generated since raw is empty
|
||||
let s = header_fingerprint_from_fingerprint(&sanitized).unwrap();
|
||||
let g = generated.as_object().unwrap();
|
||||
for key in g.keys() {
|
||||
assert!(s.contains_key(key), "sanitized missing key: {key}");
|
||||
assert!(
|
||||
!s[key].as_str().unwrap().is_empty(),
|
||||
"sanitized empty key: {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_normalizes_unknown_impersonate_profile() {
|
||||
let raw = serde_json::json!({
|
||||
"transport_profile": {
|
||||
"profile_id": "claude_code_nodejs",
|
||||
"header_fingerprint": {
|
||||
"impersonate": "firefox99"
|
||||
}
|
||||
}
|
||||
});
|
||||
let sanitized = sanitize_fingerprint(&raw, "test-key");
|
||||
let profile = header_fingerprint_from_fingerprint(&sanitized).unwrap()["impersonate"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert!(
|
||||
CHROME_IMPERSONATE_PROFILES
|
||||
.iter()
|
||||
.any(|p| p.eq_ignore_ascii_case(profile)),
|
||||
"should normalize to known profile, got: {profile}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fingerprint_differs_each_call() {
|
||||
let fp1 = generate_random_fingerprint();
|
||||
let fp2 = generate_random_fingerprint();
|
||||
assert_ne!(fp1, fp2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
mod auth;
|
||||
mod fingerprint;
|
||||
mod policy;
|
||||
mod request;
|
||||
mod url;
|
||||
|
||||
pub use auth::supports_local_claude_code_auth;
|
||||
pub use fingerprint::{
|
||||
generate_fingerprint, generate_random_fingerprint, header_fingerprint_from_fingerprint,
|
||||
sanitize_fingerprint,
|
||||
};
|
||||
pub use policy::{
|
||||
local_claude_code_transport_unsupported_reason_with_network,
|
||||
supports_local_claude_code_transport_with_network,
|
||||
};
|
||||
pub use request::{build_claude_code_passthrough_headers, sanitize_claude_code_request_body};
|
||||
pub use url::build_claude_code_messages_url;
|
||||
@@ -0,0 +1,162 @@
|
||||
use super::super::snapshot::GatewayProviderTransportSnapshot;
|
||||
use super::super::{
|
||||
body_rules_are_locally_supported, header_rules_are_locally_supported,
|
||||
resolve_transport_profile, supports_local_oauth_request_auth_resolution,
|
||||
transport_profile_is_configured, transport_proxy_is_locally_supported,
|
||||
};
|
||||
use super::auth::supports_local_claude_code_auth;
|
||||
|
||||
pub fn local_claude_code_transport_unsupported_reason_with_network(
|
||||
transport: &GatewayProviderTransportSnapshot,
|
||||
api_format: &str,
|
||||
) -> Option<&'static str> {
|
||||
if !transport.provider.is_active || !transport.endpoint.is_active || !transport.key.is_active {
|
||||
return if !transport.provider.is_active {
|
||||
Some("provider_inactive")
|
||||
} else if !transport.endpoint.is_active {
|
||||
Some("endpoint_inactive")
|
||||
} else {
|
||||
Some("key_inactive")
|
||||
};
|
||||
}
|
||||
if !transport
|
||||
.provider
|
||||
.provider_type
|
||||
.trim()
|
||||
.eq_ignore_ascii_case("claude_code")
|
||||
{
|
||||
return Some("transport_provider_type_unsupported");
|
||||
}
|
||||
if !transport
|
||||
.endpoint
|
||||
.api_format
|
||||
.trim()
|
||||
.eq_ignore_ascii_case(api_format.trim())
|
||||
{
|
||||
return Some("transport_api_format_mismatch");
|
||||
}
|
||||
if !header_rules_are_locally_supported(transport.endpoint.header_rules.as_ref()) {
|
||||
return Some("transport_header_rules_unsupported");
|
||||
}
|
||||
if !body_rules_are_locally_supported(transport.endpoint.body_rules.as_ref()) {
|
||||
return Some("transport_body_rules_unsupported");
|
||||
}
|
||||
if transport.key.decrypted_auth_config.is_some()
|
||||
&& !supports_local_oauth_request_auth_resolution(transport)
|
||||
{
|
||||
return Some("transport_oauth_resolution_unsupported");
|
||||
}
|
||||
if !supports_local_claude_code_auth(transport) {
|
||||
return Some("transport_auth_unavailable");
|
||||
}
|
||||
if !transport_proxy_is_locally_supported(transport) {
|
||||
return Some("transport_proxy_unsupported");
|
||||
}
|
||||
if transport_profile_is_configured(transport) && resolve_transport_profile(transport).is_none()
|
||||
{
|
||||
return Some("transport_profile_unsupported");
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn supports_local_claude_code_transport_with_network(
|
||||
transport: &GatewayProviderTransportSnapshot,
|
||||
api_format: &str,
|
||||
) -> bool {
|
||||
local_claude_code_transport_unsupported_reason_with_network(transport, api_format).is_none()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::super::super::snapshot::{
|
||||
GatewayProviderTransportEndpoint, GatewayProviderTransportKey,
|
||||
GatewayProviderTransportProvider, GatewayProviderTransportSnapshot,
|
||||
};
|
||||
use super::{
|
||||
local_claude_code_transport_unsupported_reason_with_network,
|
||||
supports_local_claude_code_transport_with_network,
|
||||
};
|
||||
|
||||
fn sample_transport() -> GatewayProviderTransportSnapshot {
|
||||
GatewayProviderTransportSnapshot {
|
||||
provider: GatewayProviderTransportProvider {
|
||||
id: "provider-1".to_string(),
|
||||
name: "Claude Code".to_string(),
|
||||
provider_type: "claude_code".to_string(),
|
||||
website: None,
|
||||
is_active: true,
|
||||
keep_priority_on_conversion: false,
|
||||
enable_format_conversion: false,
|
||||
concurrent_limit: None,
|
||||
max_retries: None,
|
||||
proxy: None,
|
||||
request_timeout_secs: None,
|
||||
stream_first_byte_timeout_secs: None,
|
||||
config: None,
|
||||
},
|
||||
endpoint: GatewayProviderTransportEndpoint {
|
||||
id: "endpoint-1".to_string(),
|
||||
provider_id: "provider-1".to_string(),
|
||||
api_format: "claude:messages".to_string(),
|
||||
api_family: Some("claude".to_string()),
|
||||
endpoint_kind: Some("cli".to_string()),
|
||||
is_active: true,
|
||||
base_url: "https://api.anthropic.com".to_string(),
|
||||
header_rules: None,
|
||||
body_rules: None,
|
||||
max_retries: None,
|
||||
custom_path: None,
|
||||
config: None,
|
||||
format_acceptance_config: None,
|
||||
proxy: None,
|
||||
},
|
||||
key: GatewayProviderTransportKey {
|
||||
id: "key-1".to_string(),
|
||||
provider_id: "provider-1".to_string(),
|
||||
name: "key".to_string(),
|
||||
auth_type: "bearer".to_string(),
|
||||
is_active: true,
|
||||
api_formats: Some(vec!["claude:messages".to_string()]),
|
||||
auth_type_by_format: None,
|
||||
allow_auth_channel_mismatch_formats: None,
|
||||
|
||||
allowed_models: None,
|
||||
capabilities: None,
|
||||
rate_multipliers: None,
|
||||
global_priority_by_format: None,
|
||||
expires_at_unix_secs: None,
|
||||
proxy: None,
|
||||
fingerprint: Some(json!({"transport_profile":"chrome_136"})),
|
||||
upstream_metadata: None,
|
||||
decrypted_api_key: "sk-ant-123".to_string(),
|
||||
decrypted_auth_config: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_claude_code_transport_when_auth_and_profile_are_valid() {
|
||||
assert!(supports_local_claude_code_transport_with_network(
|
||||
&sample_transport(),
|
||||
"claude:messages"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_auth_unavailable_for_claude_code_without_local_auth() {
|
||||
let mut transport = sample_transport();
|
||||
transport.key.auth_type = "api_key".to_string();
|
||||
transport.key.decrypted_api_key = "__placeholder__".to_string();
|
||||
|
||||
assert_eq!(
|
||||
local_claude_code_transport_unsupported_reason_with_network(
|
||||
&transport,
|
||||
"claude:messages"
|
||||
),
|
||||
Some("transport_auth_unavailable")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::super::auth::build_openai_passthrough_headers;
|
||||
use super::fingerprint::header_fingerprint_from_fingerprint;
|
||||
|
||||
const DEFAULT_ANTHROPIC_VERSION: &str = "2023-06-01";
|
||||
const DEFAULT_ACCEPT: &str = "application/json";
|
||||
const STREAM_HELPER_METHOD: &str = "stream";
|
||||
const DUMMY_THINKING_SIGNATURE: &str = "skip_thought_signature_validator";
|
||||
const REQUIRED_BETA_TOKENS: &[&str] = &[
|
||||
"claude-code-20250219",
|
||||
"oauth-2025-04-20",
|
||||
"interleaved-thinking-2025-05-14",
|
||||
];
|
||||
const EXCLUDED_BETA_TOKENS: &[&str] = &["context-1m-2025-08-07"];
|
||||
|
||||
/// Fingerprint field -> HTTP header mapping.
|
||||
/// Every stainless / identity dimension that can vary per-key is listed here.
|
||||
const FINGERPRINT_HEADER_MAP: &[(&str, &str)] = &[
|
||||
("stainless_package_version", "x-stainless-package-version"),
|
||||
("stainless_os", "x-stainless-os"),
|
||||
("stainless_arch", "x-stainless-arch"),
|
||||
("stainless_runtime_version", "x-stainless-runtime-version"),
|
||||
("stainless_timeout", "x-stainless-timeout"),
|
||||
("user_agent", "user-agent"),
|
||||
];
|
||||
|
||||
pub fn build_claude_code_passthrough_headers(
|
||||
headers: &http::HeaderMap,
|
||||
auth_header: &str,
|
||||
auth_value: &str,
|
||||
extra_headers: &BTreeMap<String, String>,
|
||||
stream: bool,
|
||||
fingerprint: Option<&Value>,
|
||||
) -> BTreeMap<String, String> {
|
||||
let mut out = build_openai_passthrough_headers(
|
||||
headers,
|
||||
auth_header,
|
||||
auth_value,
|
||||
extra_headers,
|
||||
Some("application/json"),
|
||||
);
|
||||
|
||||
// -- Anthropic protocol headers --
|
||||
out.insert("accept".to_string(), DEFAULT_ACCEPT.to_string());
|
||||
out.insert(
|
||||
"anthropic-version".to_string(),
|
||||
DEFAULT_ANTHROPIC_VERSION.to_string(),
|
||||
);
|
||||
// Read incoming anthropic-beta directly from the original HeaderMap because the
|
||||
// upstream passthrough filter now strips `anthropic-*` headers to avoid leaking
|
||||
// them to non-Anthropic upstreams.
|
||||
let incoming_anthropic_beta = headers
|
||||
.get("anthropic-beta")
|
||||
.and_then(|value| value.to_str().ok());
|
||||
out.insert(
|
||||
"anthropic-beta".to_string(),
|
||||
merge_anthropic_beta_tokens(incoming_anthropic_beta),
|
||||
);
|
||||
out.insert(
|
||||
"anthropic-dangerous-direct-browser-access".to_string(),
|
||||
"true".to_string(),
|
||||
);
|
||||
out.insert("x-app".to_string(), "cli".to_string());
|
||||
|
||||
// -- Stainless SDK identity headers --
|
||||
// Fixed values: these don't vary per fingerprint.
|
||||
out.insert("x-stainless-lang".to_string(), "js".to_string());
|
||||
out.insert("x-stainless-runtime".to_string(), "node".to_string());
|
||||
out.insert("x-stainless-retry-count".to_string(), "0".to_string());
|
||||
|
||||
// Defaults for fingerprint-overridable fields (used when no fingerprint is present).
|
||||
out.insert(
|
||||
"x-stainless-package-version".to_string(),
|
||||
"0.70.0".to_string(),
|
||||
);
|
||||
out.insert("x-stainless-os".to_string(), "Linux".to_string());
|
||||
out.insert("x-stainless-arch".to_string(), "arm64".to_string());
|
||||
out.insert(
|
||||
"x-stainless-runtime-version".to_string(),
|
||||
"v24.13.0".to_string(),
|
||||
);
|
||||
out.insert("x-stainless-timeout".to_string(), "600".to_string());
|
||||
|
||||
if stream {
|
||||
out.insert(
|
||||
"x-stainless-helper-method".to_string(),
|
||||
STREAM_HELPER_METHOD.to_string(),
|
||||
);
|
||||
} else {
|
||||
out.remove("x-stainless-helper-method");
|
||||
}
|
||||
|
||||
// Override from the formal transport profile header fingerprint.
|
||||
if let Some(fp) = fingerprint.and_then(header_fingerprint_from_fingerprint) {
|
||||
for &(fp_key, header_key) in FINGERPRINT_HEADER_MAP {
|
||||
if let Some(value) = fp
|
||||
.get(fp_key)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
out.insert(header_key.to_string(), value.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn sanitize_claude_code_request_body(body: &mut Value) {
|
||||
let Some(body_object) = body.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
let thinking_enabled = body_object
|
||||
.get("thinking")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|thinking| thinking.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| matches!(value.to_ascii_lowercase().as_str(), "enabled" | "adaptive"));
|
||||
|
||||
let Some(messages) = body_object
|
||||
.get_mut("messages")
|
||||
.and_then(Value::as_array_mut)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
for message in messages {
|
||||
let Some(message_object) = message.as_object_mut() else {
|
||||
continue;
|
||||
};
|
||||
let role = message_object
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let Some(content) = message_object
|
||||
.get_mut("content")
|
||||
.and_then(Value::as_array_mut)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let mut filtered = Vec::with_capacity(content.len());
|
||||
for block in std::mem::take(content) {
|
||||
let Value::Object(block_object) = block else {
|
||||
filtered.push(block);
|
||||
continue;
|
||||
};
|
||||
if keep_claude_code_block(&block_object, &role, thinking_enabled) {
|
||||
filtered.push(Value::Object(block_object));
|
||||
}
|
||||
}
|
||||
*content = filtered;
|
||||
}
|
||||
}
|
||||
|
||||
fn keep_claude_code_block(
|
||||
block_object: &Map<String, Value>,
|
||||
role: &str,
|
||||
thinking_enabled: bool,
|
||||
) -> bool {
|
||||
let block_type = block_object
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.unwrap_or_default();
|
||||
if matches!(block_type, "thinking" | "redacted_thinking") {
|
||||
let signature = block_object
|
||||
.get("signature")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.unwrap_or_default();
|
||||
return thinking_enabled
|
||||
&& role.eq_ignore_ascii_case("assistant")
|
||||
&& !signature.is_empty()
|
||||
&& signature != DUMMY_THINKING_SIGNATURE;
|
||||
}
|
||||
if block_type.is_empty() && block_object.contains_key("thinking") {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn merge_anthropic_beta_tokens(incoming: Option<&str>) -> String {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut merged = Vec::new();
|
||||
|
||||
for token in REQUIRED_BETA_TOKENS {
|
||||
append_beta_token(&mut seen, &mut merged, token);
|
||||
}
|
||||
for token in incoming.unwrap_or_default().split(',') {
|
||||
let token = token.trim();
|
||||
if EXCLUDED_BETA_TOKENS
|
||||
.iter()
|
||||
.any(|excluded| token.eq_ignore_ascii_case(excluded))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
append_beta_token(&mut seen, &mut merged, token);
|
||||
}
|
||||
|
||||
merged.join(",")
|
||||
}
|
||||
|
||||
fn append_beta_token(seen: &mut BTreeSet<String>, merged: &mut Vec<String>, token: &str) {
|
||||
let normalized = token.trim();
|
||||
if normalized.is_empty() {
|
||||
return;
|
||||
}
|
||||
let key = normalized.to_ascii_lowercase();
|
||||
if seen.insert(key) {
|
||||
merged.push(normalized.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{build_claude_code_passthrough_headers, sanitize_claude_code_request_body};
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn claude_code_headers_use_transport_profile_header_fingerprint_and_merge_required_betas() {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
"anthropic-beta",
|
||||
http::HeaderValue::from_static("context-1m-2025-08-07,custom-beta"),
|
||||
);
|
||||
headers.insert(
|
||||
"user-agent",
|
||||
http::HeaderValue::from_static("Claude-Code/Test"),
|
||||
);
|
||||
let built = build_claude_code_passthrough_headers(
|
||||
&headers,
|
||||
"authorization",
|
||||
"Bearer upstream-token",
|
||||
&BTreeMap::new(),
|
||||
true,
|
||||
Some(&json!({
|
||||
"transport_profile": {
|
||||
"profile_id": "claude_code_nodejs",
|
||||
"header_fingerprint": {
|
||||
"user_agent":"Claude-Code/9.9",
|
||||
"stainless_package_version":"1.0.5",
|
||||
"stainless_runtime_version":"v22.12.0",
|
||||
"stainless_timeout":"900"
|
||||
}
|
||||
}
|
||||
})),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
built.get("anthropic-beta").map(String::as_str),
|
||||
Some(
|
||||
"claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,custom-beta"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("anthropic-version").map(String::as_str),
|
||||
Some("2023-06-01")
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("accept").map(String::as_str),
|
||||
Some("application/json")
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("x-stainless-helper-method").map(String::as_str),
|
||||
Some("stream")
|
||||
);
|
||||
assert_eq!(built.get("x-app").map(String::as_str), Some("cli"));
|
||||
assert_eq!(
|
||||
built.get("x-stainless-package-version").map(String::as_str),
|
||||
Some("1.0.5")
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("x-stainless-runtime-version").map(String::as_str),
|
||||
Some("v22.12.0")
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("x-stainless-timeout").map(String::as_str),
|
||||
Some("900")
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("user-agent").map(String::as_str),
|
||||
Some("Claude-Code/9.9")
|
||||
);
|
||||
assert_eq!(
|
||||
built.get("authorization").map(String::as_str),
|
||||
Some("Bearer upstream-token")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_code_body_sanitizer_drops_invalid_thinking_blocks() {
|
||||
let mut body = json!({
|
||||
"thinking": {"type":"enabled"},
|
||||
"messages": [{
|
||||
"role":"assistant",
|
||||
"content":[
|
||||
{"type":"thinking","thinking":"keep","signature":"sig_valid"},
|
||||
{"type":"thinking","thinking":"drop-empty","signature":""},
|
||||
{"type":"redacted_thinking","data":"keep-redacted","signature":"sig_redacted"},
|
||||
{"type":"redacted_thinking","data":"drop-no-signature"},
|
||||
{"thinking":"drop-no-type"},
|
||||
{"type":"text","text":"ok"}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
sanitize_claude_code_request_body(&mut body);
|
||||
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"],
|
||||
json!([
|
||||
{"type":"thinking","thinking":"keep","signature":"sig_valid"},
|
||||
{"type":"redacted_thinking","data":"keep-redacted","signature":"sig_redacted"},
|
||||
{"type":"text","text":"ok"}
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use url::form_urlencoded;
|
||||
|
||||
pub fn build_claude_code_messages_url(upstream_base_url: &str, query: Option<&str>) -> String {
|
||||
let (trimmed_base_url, base_query) = split_query(upstream_base_url.trim());
|
||||
let trimmed_base_url = trimmed_base_url.trim_end_matches('/');
|
||||
let mut url =
|
||||
if trimmed_base_url.ends_with("/v1/messages") || trimmed_base_url.ends_with("/messages") {
|
||||
trimmed_base_url.to_string()
|
||||
} else if trimmed_base_url.ends_with("/v1") {
|
||||
format!("{trimmed_base_url}/messages")
|
||||
} else {
|
||||
format!("{trimmed_base_url}/v1/messages")
|
||||
};
|
||||
append_merged_query(&mut url, base_query, query);
|
||||
url
|
||||
}
|
||||
|
||||
fn split_query(value: &str) -> (&str, Option<&str>) {
|
||||
value
|
||||
.split_once('?')
|
||||
.map(|(base, query)| (base, Some(query)))
|
||||
.unwrap_or((value, None))
|
||||
}
|
||||
|
||||
fn append_merged_query(url: &mut String, base_query: Option<&str>, request_query: Option<&str>) {
|
||||
let Some(query) = merge_query_layers(base_query, request_query) else {
|
||||
return;
|
||||
};
|
||||
if url.contains('?') {
|
||||
url.push('&');
|
||||
} else {
|
||||
url.push('?');
|
||||
}
|
||||
url.push_str(&query);
|
||||
}
|
||||
|
||||
fn merge_query_layers(base_query: Option<&str>, request_query: Option<&str>) -> Option<String> {
|
||||
let mut merged = BTreeMap::new();
|
||||
for source in [base_query, request_query] {
|
||||
let Some(source) = source.map(str::trim).filter(|value| !value.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
for (key, value) in form_urlencoded::parse(source.as_bytes()) {
|
||||
merged.insert(key.into_owned(), value.into_owned());
|
||||
}
|
||||
}
|
||||
if merged.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut serializer = form_urlencoded::Serializer::new(String::new());
|
||||
for (key, value) in merged {
|
||||
serializer.append_pair(&key, &value);
|
||||
}
|
||||
Some(serializer.finish())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::build_claude_code_messages_url;
|
||||
|
||||
#[test]
|
||||
fn keeps_existing_messages_suffix_without_duplication() {
|
||||
assert_eq!(
|
||||
build_claude_code_messages_url("https://api.anthropic.com/v1/messages", None),
|
||||
"https://api.anthropic.com/v1/messages"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appends_messages_and_merges_query() {
|
||||
assert_eq!(
|
||||
build_claude_code_messages_url(
|
||||
"https://api.anthropic.com/v1?beta=true",
|
||||
Some("foo=bar"),
|
||||
),
|
||||
"https://api.anthropic.com/v1/messages?beta=true&foo=bar"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user