mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-26 00:00:52 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05c3457ca7 | ||
|
|
d7761910bb | ||
|
|
866e812ce0 | ||
|
|
23a4fa42c4 | ||
|
|
f8a7a45b34 | ||
|
|
d777945c93 | ||
|
|
3e747cb233 | ||
|
|
ee5f42ee8e |
@@ -48,6 +48,8 @@ pub enum PrivacyAction {
|
||||
SetValue,
|
||||
RenameKey,
|
||||
RemoveField,
|
||||
AnonymizeProject,
|
||||
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
|
||||
AnonymizeWorkspace,
|
||||
}
|
||||
|
||||
|
||||
@@ -86,6 +86,8 @@ pub enum PrivacyAction {
|
||||
SetValue,
|
||||
RenameKey,
|
||||
RemoveField,
|
||||
AnonymizeProject,
|
||||
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
|
||||
AnonymizeWorkspace,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use crate::{
|
||||
credential::{CredentialService, oauth::error},
|
||||
profile::ReleaseService,
|
||||
transport::{Catalog, CloudCodeClient, unsent},
|
||||
};
|
||||
use gateway_admin::{
|
||||
@@ -29,7 +28,6 @@ pub(crate) struct CatalogService {
|
||||
kind: gateway_core::routing::ProviderKind,
|
||||
accounts: Arc<dyn gateway_core::account::ProviderAccountStore>,
|
||||
registration: String,
|
||||
pub(crate) release: Arc<ReleaseService>,
|
||||
pub(crate) origin: url::Url,
|
||||
pub(crate) generation: AtomicU64,
|
||||
observed:
|
||||
@@ -109,7 +107,6 @@ impl CatalogService {
|
||||
credentials: Arc<CredentialService>,
|
||||
registration: String,
|
||||
origin: url::Url,
|
||||
release: Arc<ReleaseService>,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
@@ -117,7 +114,6 @@ impl CatalogService {
|
||||
credentials,
|
||||
registration,
|
||||
origin,
|
||||
release,
|
||||
generation: AtomicU64::new(0),
|
||||
observed: Mutex::default(),
|
||||
refresh_cursor: AtomicUsize::new(0),
|
||||
@@ -222,12 +218,9 @@ impl CatalogService {
|
||||
.credentials
|
||||
.material(¤t)
|
||||
.map_err(|e| error(AdminKind::CredentialRefreshRequired).with_source(e))?;
|
||||
let client = CloudCodeClient::new(
|
||||
&self.origin,
|
||||
current.account.outbound_proxy(),
|
||||
&crate::profile::default_profile(&self.release),
|
||||
)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let profile = self.credentials.request_profile().await?;
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client
|
||||
.catalog(&material.access_token)
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::document::Document;
|
||||
use crate::{
|
||||
credential::catalog::CatalogService,
|
||||
credential::{CredentialService, oauth::error},
|
||||
profile::ReleaseService,
|
||||
transport::CloudCodeClient,
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
@@ -35,7 +34,6 @@ pub(crate) struct QuotaService {
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
credentials: Arc<CredentialService>,
|
||||
catalog: Arc<CatalogService>,
|
||||
release: Arc<ReleaseService>,
|
||||
origin: url::Url,
|
||||
cursor: AtomicUsize,
|
||||
}
|
||||
@@ -107,7 +105,6 @@ impl QuotaService {
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
credentials: Arc<CredentialService>,
|
||||
catalog: Arc<CatalogService>,
|
||||
release: Arc<ReleaseService>,
|
||||
origin: url::Url,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -115,7 +112,6 @@ impl QuotaService {
|
||||
accounts,
|
||||
credentials,
|
||||
catalog,
|
||||
release,
|
||||
origin,
|
||||
cursor: AtomicUsize::new(0),
|
||||
}
|
||||
@@ -153,12 +149,9 @@ impl QuotaService {
|
||||
.credentials
|
||||
.material(¤t)
|
||||
.map_err(|e| error(Kind::CredentialRefreshRequired).with_source(e))?;
|
||||
let client = CloudCodeClient::new(
|
||||
&self.origin,
|
||||
current.account.outbound_proxy(),
|
||||
&crate::profile::default_profile(&self.release),
|
||||
)
|
||||
.map_err(upstream)?;
|
||||
let profile = self.credentials.request_profile().await?;
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(upstream)?;
|
||||
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
|
||||
let observed_at = SystemTime::now();
|
||||
let info = client
|
||||
|
||||
@@ -32,14 +32,12 @@ pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigErr
|
||||
credentials.clone(),
|
||||
oauth.registration(),
|
||||
origin.clone(),
|
||||
release.clone(),
|
||||
));
|
||||
let quota = Arc::new(credential::quota::QuotaService::new(
|
||||
kind.clone(),
|
||||
ports.accounts(),
|
||||
credentials.clone(),
|
||||
catalog.clone(),
|
||||
release.clone(),
|
||||
origin.clone(),
|
||||
));
|
||||
let core = Arc::new(provider::AntigravityProvider::new(
|
||||
|
||||
@@ -15,6 +15,37 @@ async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Dura
|
||||
Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary().loaded.lock().unwrap().account.clone();
|
||||
for (version, changelist) in [("1.5.14", ""), ("1.5.15", "; cl=1027820220")] {
|
||||
*f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
|
||||
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}),
|
||||
));
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
f.quota.refresh(account.id()).await.unwrap();
|
||||
f.catalog.account_models(account.id(), true).await.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 5);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
format!(
|
||||
"antigravity/cli/{version} (aidev_client; os_type=linux; arch=amd64{changelist}; auth_method=consumer)"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
*f.store.request_profile.lock().unwrap() =
|
||||
Some(crate::profile::object(json!({"client":"unsupported"})));
|
||||
assert!(f.quota.refresh(account.id()).await.is_err());
|
||||
assert!(f.catalog.account_models(account.id(), true).await.is_err());
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 10);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -226,14 +226,12 @@ impl Fixture {
|
||||
credentials.clone(),
|
||||
oauth.registration(),
|
||||
origin.clone(),
|
||||
release.clone(),
|
||||
));
|
||||
let quota = Arc::new(crate::credential::quota::QuotaService::new(
|
||||
kind.clone(),
|
||||
store.clone(),
|
||||
credentials.clone(),
|
||||
catalog.clone(),
|
||||
release.clone(),
|
||||
origin.clone(),
|
||||
));
|
||||
let provider = Arc::new(AntigravityProvider::new(
|
||||
|
||||
@@ -144,6 +144,7 @@ pub(super) fn map_oauth_error(error: CodexOAuthAdminError) -> ProviderAdminError
|
||||
}) => (Kind::Unavailable, "无法连接授权服务,请检查出站连接"),
|
||||
Error::Exchange(Exchange::Unavailable) => (Kind::Unavailable, "授权服务暂不可用"),
|
||||
Error::StorageUnavailable => (Kind::Unavailable, "授权状态存储暂不可用"),
|
||||
Error::Profile(_) => (Kind::Unavailable, "授权客户端身份暂不可用"),
|
||||
};
|
||||
provider_admin_error(kind)
|
||||
.with_public_message(message)
|
||||
@@ -169,6 +170,7 @@ pub(super) const fn oauth_error_code(error: &CodexOAuthAdminError) -> &'static s
|
||||
}) => "connect_failed",
|
||||
CodexOAuthAdminError::Exchange(Exchange::Ambiguous { .. }) => "ambiguous",
|
||||
CodexOAuthAdminError::StorageUnavailable => "storage_unavailable",
|
||||
CodexOAuthAdminError::Profile(_) => "profile_unavailable",
|
||||
CodexOAuthAdminError::Credential => "credential",
|
||||
}
|
||||
}
|
||||
@@ -179,7 +181,7 @@ pub(super) fn map_quota_error(error: CodexCredentialQuotaError) -> ProviderAdmin
|
||||
let (kind, public_message, upstream_message) = match error {
|
||||
Error::Profile(source) => {
|
||||
return provider_admin_error(Kind::Unavailable)
|
||||
.with_public_message("预热客户端身份不可用")
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
Error::InvalidCredentialData => (Kind::Invalid, "凭据或额度数据无效", None),
|
||||
|
||||
@@ -15,6 +15,7 @@ use gateway_admin::model::{
|
||||
use gateway_core::account::{
|
||||
LoadedCredential, NewProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
};
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sha2::{Digest, Sha256};
|
||||
use subtle::ConstantTimeEq as _;
|
||||
@@ -32,13 +33,12 @@ use super::token_client::{
|
||||
OFFICIAL_CODEX_OAUTH_CLIENT_ID, OFFICIAL_CODEX_REDIRECT_URI,
|
||||
};
|
||||
use super::types::{parse_access_token_expiration, parse_chatgpt_jwt_claims};
|
||||
use crate::profile::CodexWireProfileState;
|
||||
use crate::profile::{CodexWireProfile, CodexWireProfileState};
|
||||
|
||||
const AUTHORIZATION_ENDPOINT: &str = "https://auth.openai.com/oauth/authorize";
|
||||
const DESKTOP_AUTH_ENDPOINT: &str = "https://chatgpt.com/codex/desktop-auth";
|
||||
const AUTHORIZATION_SCOPE: &str =
|
||||
"openid profile email offline_access api.connectors.read api.connectors.invoke";
|
||||
const AUTHORIZATION_ORIGINATOR: &str = "Codex Desktop";
|
||||
const STREAMLINED_LOGIN_QUERY: &str = "codex_streamlined_login";
|
||||
const NO_UNIVERSAL_LINKS_QUERY: &str = "no_universal_links";
|
||||
const SURFACE_STABLE_ID_DOMAIN: &[u8] = b"openai/codex-desktop/surface-stable-id/v1\0";
|
||||
@@ -336,6 +336,8 @@ pub enum CodexOAuthAdminError {
|
||||
Exchange(#[source] AuthorizationCodeExchangeError),
|
||||
#[error("Codex OAuth pending storage is unavailable")]
|
||||
StorageUnavailable,
|
||||
#[error("Codex OAuth client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Codex OAuth account mutation failed")]
|
||||
Credential,
|
||||
}
|
||||
@@ -360,6 +362,7 @@ pub struct CodexOAuthAdminService {
|
||||
credentials: CodexCredentialAdmin,
|
||||
oauth_client_id: String,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
struct CodexOAuthAuthorizationCommitGuard {
|
||||
@@ -408,6 +411,7 @@ impl CodexOAuthAdminService {
|
||||
store: Arc<dyn ProviderAccountStore>,
|
||||
credentials: CodexCredentialAdmin,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
pending,
|
||||
@@ -416,6 +420,7 @@ impl CodexOAuthAdminService {
|
||||
credentials,
|
||||
oauth_client_id: OFFICIAL_CODEX_OAUTH_CLIENT_ID.to_owned(),
|
||||
profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -603,9 +608,12 @@ impl CodexOAuthAdminService {
|
||||
mutation,
|
||||
})
|
||||
.map_err(map_pending_error)?;
|
||||
let profile = self.profile.snapshot();
|
||||
let authorization_url =
|
||||
authorization_url(&pending, &self.oauth_client_id, &profile.desktop_version)?;
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexOAuthAdminError::Profile)?;
|
||||
let authorization_url = authorization_url(&pending, &self.oauth_client_id, &profile)?;
|
||||
self.pending
|
||||
.create(&pending)
|
||||
.await
|
||||
@@ -736,11 +744,8 @@ fn derive_surface_stable_id(installation_id: &str) -> Result<String, CodexOAuthA
|
||||
fn authorization_url(
|
||||
pending: &CodexPendingAuthorization,
|
||||
oauth_client_id: &str,
|
||||
desktop_version: &str,
|
||||
profile: &CodexWireProfile,
|
||||
) -> Result<String, CodexOAuthAdminError> {
|
||||
if !valid_text(desktop_version) {
|
||||
return Err(CodexOAuthAdminError::InvalidInput);
|
||||
}
|
||||
let mut inner =
|
||||
Url::parse(AUTHORIZATION_ENDPOINT).map_err(|_| CodexOAuthAdminError::InvalidInput)?;
|
||||
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(
|
||||
@@ -759,8 +764,11 @@ fn authorization_url(
|
||||
.append_pair("scope", AUTHORIZATION_SCOPE)
|
||||
.append_pair("id_token_add_organizations", "true")
|
||||
.append_pair("codex_cli_simplified_flow", "true")
|
||||
.append_pair("originator", AUTHORIZATION_ORIGINATOR)
|
||||
.append_pair("codex_app_version", desktop_version)
|
||||
.append_pair("originator", &profile.originator);
|
||||
if !profile.desktop_version.is_empty() {
|
||||
query.append_pair("codex_app_version", &profile.desktop_version);
|
||||
}
|
||||
query
|
||||
.append_pair("source_surface_stable_id", &stable_id)
|
||||
.append_pair("codex_origin_stable_id", &stable_id)
|
||||
.append_pair(STREAMLINED_LOGIN_QUERY, "true");
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::Mutex,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant, SystemTime},
|
||||
};
|
||||
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use reqwest::Client;
|
||||
use secrecy::{ExposeSecret as _, SecretString};
|
||||
use thiserror::Error;
|
||||
@@ -108,6 +109,7 @@ struct CachedProfileAvatarSource {
|
||||
pub struct CodexCredentialProfileService {
|
||||
repository: CodexCredentialRepository,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
http: Client,
|
||||
base_url: String,
|
||||
avatar_sources: Mutex<HashMap<String, CachedProfileAvatarSource>>,
|
||||
@@ -120,16 +122,34 @@ impl CodexCredentialProfileService {
|
||||
profile: CodexWireProfileState,
|
||||
http: Client,
|
||||
base_url: String,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
profile,
|
||||
http,
|
||||
base_url,
|
||||
runtime_policy,
|
||||
avatar_sources: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn global_profile_client(
|
||||
&self,
|
||||
) -> Result<CodexBackendClient, CodexProfileStatisticsError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| CodexProfileStatisticsError::TransportUnavailable)?;
|
||||
Ok(CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile))
|
||||
}
|
||||
|
||||
/// 订阅只按需读取;不缓存、不刷新凭据,也不更新额度状态
|
||||
pub async fn subscription(
|
||||
&self,
|
||||
@@ -141,23 +161,21 @@ impl CodexCredentialProfileService {
|
||||
return Ok(None);
|
||||
};
|
||||
let request_id = format!("subscription_{}", Uuid::now_v7().simple());
|
||||
let subscription = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.for_account(&account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_subscription(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
Some(&upstream_account_id),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
&upstream_account_id,
|
||||
)
|
||||
.await;
|
||||
let subscription = self
|
||||
.global_profile_client()
|
||||
.await?
|
||||
.for_account(&account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_subscription(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
Some(&upstream_account_id),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
&upstream_account_id,
|
||||
)
|
||||
.await;
|
||||
// 请求期间重新授权、换绑或删除账号时,丢弃旧身份的结果
|
||||
let current = self
|
||||
.repository
|
||||
@@ -183,32 +201,35 @@ impl CodexCredentialProfileService {
|
||||
) -> Result<CodexProfileStatistics, CodexProfileStatisticsError> {
|
||||
let (authorization, upstream_account_id, account) =
|
||||
self.account_authentication(account_id).await?;
|
||||
self.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account)
|
||||
.await
|
||||
let client = self.global_profile_client().await?;
|
||||
self.fetch_profile_statistics(
|
||||
&client,
|
||||
&authorization,
|
||||
upstream_account_id.as_deref(),
|
||||
&account,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fetch_profile_statistics(
|
||||
&self,
|
||||
client: &CodexBackendClient,
|
||||
authorization: &SecretString,
|
||||
upstream_account_id: Option<&str>,
|
||||
account: &gateway_core::account::ProviderAccount,
|
||||
) -> Result<CodexProfileStatistics, CodexProfileStatisticsError> {
|
||||
let request_id = format!("profile_statistics_{}", Uuid::now_v7().simple());
|
||||
let statistics = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.for_account(account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_profile_statistics(CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
upstream_account_id,
|
||||
&request_id,
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
let statistics = client
|
||||
.for_account(account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_profile_statistics(CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
upstream_account_id,
|
||||
&request_id,
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
self.remember_avatar_source(
|
||||
crate::request_identity::oauth_identity_key(account),
|
||||
statistics.image_url.as_deref(),
|
||||
@@ -268,12 +289,18 @@ impl CodexCredentialProfileService {
|
||||
) -> Result<CodexProfileAvatar, CodexProfileAvatarError> {
|
||||
let (authorization, upstream_account_id, account) =
|
||||
self.account_authentication(account_id).await?;
|
||||
let client = self.global_profile_client().await?;
|
||||
let source = match self
|
||||
.cached_avatar_source(&crate::request_identity::oauth_identity_key(&account))
|
||||
{
|
||||
Some(source) => source,
|
||||
None => self
|
||||
.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account)
|
||||
.fetch_profile_statistics(
|
||||
&client,
|
||||
&authorization,
|
||||
upstream_account_id.as_deref(),
|
||||
&account,
|
||||
)
|
||||
.await?
|
||||
.image_url
|
||||
.ok_or(CodexProfileAvatarError::Missing)?,
|
||||
@@ -290,7 +317,7 @@ impl CodexCredentialProfileService {
|
||||
fetch_profile_avatar(
|
||||
&http,
|
||||
&self.base_url,
|
||||
&self.profile.snapshot(),
|
||||
&client.profile_state().snapshot(),
|
||||
&source,
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
|
||||
@@ -231,17 +231,7 @@ impl CodexCredentialQuotaService {
|
||||
.await?;
|
||||
return Ok(None);
|
||||
};
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile);
|
||||
let client = self.global_profile_client().await?;
|
||||
// 先持久化领取再发请求;超时、取消或重启后不重放结果不明的推理
|
||||
// 通用窗口共享请求用量,同批到期窗口只发一次轻量请求
|
||||
for (key, _, reset) in &due {
|
||||
|
||||
@@ -145,7 +145,7 @@ pub struct CodexWarmupSummary {
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CodexCredentialQuotaError {
|
||||
#[error("Codex warmup client profile is unavailable")]
|
||||
#[error("Codex quota client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Codex quota response is invalid")]
|
||||
InvalidCredentialData,
|
||||
|
||||
@@ -126,11 +126,10 @@ impl CodexCredentialQuotaService {
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<CodexRateLimitResetCredits, CodexResetCreditsError> {
|
||||
let account = self.reset_credit_account(account_id).await?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self
|
||||
.global_profile_client()
|
||||
.await
|
||||
.map_err(|_| CodexResetCreditsError::TransportUnavailable)?;
|
||||
let credential = self
|
||||
.repository
|
||||
.load_runtime_credential(&account)
|
||||
@@ -157,11 +156,10 @@ impl CodexCredentialQuotaService {
|
||||
let entry = self.reset_consume_locks.entry(account_id);
|
||||
let _guard = entry.lock().await;
|
||||
let account = self.reset_credit_account(account_id).await?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self
|
||||
.global_profile_client()
|
||||
.await
|
||||
.map_err(|_| CodexResetCreditsError::TransportUnavailable)?;
|
||||
let credential = self
|
||||
.repository
|
||||
.load_runtime_credential(&account)
|
||||
|
||||
@@ -35,6 +35,22 @@ fn upstream_error_status(error: &CodexClientError) -> Option<u16> {
|
||||
}
|
||||
|
||||
impl CodexCredentialQuotaService {
|
||||
pub(super) async fn global_profile_client(
|
||||
&self,
|
||||
) -> Result<CodexBackendClient, CodexCredentialQuotaError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
Ok(CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile))
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
repository: CodexCredentialRepository,
|
||||
profile: CodexWireProfileState,
|
||||
@@ -174,11 +190,17 @@ impl CodexCredentialQuotaService {
|
||||
if accounts.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = match self.global_profile_client().await {
|
||||
Ok(client) => client,
|
||||
Err(error) => {
|
||||
// 身份配置失败尚未发出请求,也需要释放已预留的首查任务
|
||||
self.scheduling.defer_failed_initial_refreshes(
|
||||
&pending_initial,
|
||||
self.initial_sync_delays.as_ref(),
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
for account in accounts {
|
||||
let observed_at = SystemTime::now();
|
||||
match self.fetch_usage(&client, &account).await {
|
||||
@@ -410,11 +432,7 @@ impl CodexCredentialQuotaService {
|
||||
if !access_token_is_current(&account, observed_at) {
|
||||
return Err(CodexCredentialQuotaError::CredentialRefreshRequired);
|
||||
}
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self.global_profile_client().await?;
|
||||
let FetchedCodexQuota { account, value } = match self.fetch_usage(&client, &account).await {
|
||||
Ok(fetched) => fetched,
|
||||
Err(CodexQuotaFetchError::InvalidCredential) => {
|
||||
|
||||
@@ -140,17 +140,7 @@ impl CodexCredentialQuotaService {
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile);
|
||||
let client = self.global_profile_client().await?;
|
||||
|
||||
for account in accounts {
|
||||
if account.quota().is_exhausted() {
|
||||
|
||||
@@ -8,10 +8,12 @@ use crate::transport::{
|
||||
tls::{build_reqwest_client_with_custom_ca, ensure_rustls_provider},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use reqwest::{Client, StatusCode, redirect::Policy};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_OAUTH_RESPONSE_BYTES: usize = 64 * 1024;
|
||||
@@ -386,6 +388,7 @@ pub struct OpenAiTokenClient {
|
||||
client: Client,
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
/// 官方 Codex token client 无法安全构建
|
||||
@@ -408,14 +411,23 @@ impl OpenAiTokenClient {
|
||||
.timeout(TOKEN_REQUEST_TIMEOUT);
|
||||
let client =
|
||||
build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?;
|
||||
Ok(Self::new(client, self.config.clone(), self.profile.clone()))
|
||||
Ok(Self {
|
||||
client,
|
||||
..self.clone()
|
||||
})
|
||||
}
|
||||
/// 共享运行时画像;刷新时取快照,授权码交换仍使用 raw auth 请求
|
||||
pub fn new(client: Client, config: TokenClientConfig, profile: CodexWireProfileState) -> Self {
|
||||
/// 认证请求按执行时的全局配置解析身份
|
||||
pub fn new(
|
||||
client: Client,
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,7 +451,12 @@ impl OpenAiTokenClient {
|
||||
endpoint.set_path(PERSONAL_ACCESS_TOKEN_WHOAMI_PATH);
|
||||
endpoint.set_query(None);
|
||||
endpoint.set_fragment(None);
|
||||
let headers = build_codex_profile_headers(&self.profile.snapshot())
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| PersonalAccessTokenError::Unavailable)?;
|
||||
let headers = build_codex_profile_headers(&profile)
|
||||
.map_err(|_| PersonalAccessTokenError::Unavailable)?;
|
||||
let client = self
|
||||
.with_proxy(proxy)
|
||||
@@ -495,6 +512,7 @@ impl OpenAiTokenClient {
|
||||
pub fn openai_token_client(
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Result<OpenAiTokenClient, TokenClientBuildError> {
|
||||
ensure_rustls_provider();
|
||||
let builder = gateway_egress::http_client(None)
|
||||
@@ -503,7 +521,12 @@ pub fn openai_token_client(
|
||||
.connect_timeout(TOKEN_CONNECT_TIMEOUT)
|
||||
.timeout(TOKEN_REQUEST_TIMEOUT);
|
||||
let client = build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?;
|
||||
Ok(OpenAiTokenClient::new(client, config, profile))
|
||||
Ok(OpenAiTokenClient::new(
|
||||
client,
|
||||
config,
|
||||
profile,
|
||||
runtime_policy,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -591,14 +614,22 @@ impl TokenRefresher for OpenAiTokenClient {
|
||||
.await
|
||||
}
|
||||
async fn refresh(&self, refresh_token: &str) -> Result<TokenPair, RefreshFailure> {
|
||||
let headers = build_codex_profile_headers(&self.profile.snapshot()).map_err(|source| {
|
||||
RefreshFailure::Transport {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|source| RefreshFailure::RetryableTransport {
|
||||
redacted: false,
|
||||
source: Some(source),
|
||||
message: "OpenAI OAuth refresh profile is unavailable".to_owned(),
|
||||
})?;
|
||||
let headers =
|
||||
build_codex_profile_headers(&profile).map_err(|source| RefreshFailure::Transport {
|
||||
redacted: false,
|
||||
source: Some(source.into()),
|
||||
message: Some("OpenAI OAuth refresh profile is invalid".to_owned()),
|
||||
upstream: None,
|
||||
}
|
||||
})?;
|
||||
})?;
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
@@ -642,9 +673,17 @@ impl AuthorizationCodeExchanger for OpenAiTokenClient {
|
||||
&self,
|
||||
grant: AuthorizationCodeGrant,
|
||||
) -> Result<AuthorizationTokenSet, AuthorizationCodeExchangeError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| AuthorizationCodeExchangeError::Unavailable)?;
|
||||
let headers = build_codex_profile_headers(&profile)
|
||||
.map_err(|_| AuthorizationCodeExchangeError::Unavailable)?;
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
.headers(headers)
|
||||
.form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
|
||||
@@ -162,6 +162,7 @@ pub async fn initialize(
|
||||
profile.clone(),
|
||||
http.clone(),
|
||||
config.base_url().to_owned(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let selector = Arc::new(CodexCredentialSelector::new(
|
||||
provider_kind.clone(),
|
||||
@@ -197,6 +198,7 @@ pub async fn initialize(
|
||||
credential::token_client::openai_token_client(
|
||||
config.token_client_config(),
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
)
|
||||
.map_err(|_| OpenAiInitializeError::TokenClient)?,
|
||||
);
|
||||
@@ -230,6 +232,7 @@ pub async fn initialize(
|
||||
Arc::clone(&accounts),
|
||||
CodexCredentialAdmin,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
)
|
||||
.with_oauth_client_id(config.oauth_client_id()),
|
||||
);
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(super) const CLI_ORIGINATOR: &str = "codex_cli_rs";
|
||||
pub(super) const TUI_ORIGINATOR: &str = "codex-tui";
|
||||
pub(super) const EXEC_ORIGINATOR: &str = "codex_exec";
|
||||
pub(super) const TERMINAL: &str = "unknown";
|
||||
pub(super) const MACOS_CLI_TERMINAL: &str = "Apple_Terminal/488.9";
|
||||
|
||||
pub(super) struct Environment {
|
||||
pub os_type: &'static str,
|
||||
@@ -19,7 +20,7 @@ pub(super) struct Environment {
|
||||
|
||||
pub(super) const MACOS_ENVIRONMENT: Environment = Environment {
|
||||
os_type: "Mac OS",
|
||||
os_version: "15.7.1",
|
||||
os_version: "27.2.1",
|
||||
arch: "arm64",
|
||||
};
|
||||
pub(super) const LINUX_ENVIRONMENT: Environment = Environment {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(super) const USER_AGENT_PRODUCTS: [&str; 4] =
|
||||
["Codex Desktop", "codex-tui", "codex_exec", "codex_cli_rs"];
|
||||
|
||||
impl CodexWireProfileState {
|
||||
/// 后台模型操作没有 Client Key,按当前全局选择冻结整套身份
|
||||
/// 账号后台操作没有 Client Key,按当前全局选择冻结整套身份
|
||||
pub(crate) async fn resolve_global_request_profile(
|
||||
&self,
|
||||
policy: &dyn ProviderRuntimePolicyPort,
|
||||
|
||||
@@ -362,6 +362,10 @@ impl CodexWireProfileState {
|
||||
let configuration = ClientProfileSelection {
|
||||
client,
|
||||
platform,
|
||||
cli_entry: (client == ClientKind::Cli && platform == ClientPlatform::Macos)
|
||||
.then_some(CliEntry::Tui),
|
||||
terminal: (client == ClientKind::Cli && platform == ClientPlatform::Macos)
|
||||
.then(|| baseline::MACOS_CLI_TERMINAL.to_owned()),
|
||||
..ClientProfileSelection::default()
|
||||
};
|
||||
let available = configuration.resolve(self).is_ok();
|
||||
|
||||
@@ -105,6 +105,10 @@ impl CodexWireProfile {
|
||||
/// 复合 User-Agent 是两个独立 surface
|
||||
#[must_use]
|
||||
pub fn desktop_user_agent(&self) -> String {
|
||||
// 非 Desktop 预设及完整自定义 UA 没有独立桌面格式,保持所选身份
|
||||
if self.client_kind != ClientKind::Desktop || self.exact_user_agent.is_some() {
|
||||
return self.user_agent();
|
||||
}
|
||||
format!(
|
||||
"{}/{} ({}; {})",
|
||||
self.originator, self.desktop_version, self.os_type, self.arch
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn build_codex_model_headers(
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// Core 默认客户端身份,用于模型接口及 OAuth refresh;raw token exchange 不使用
|
||||
/// 客户端身份头供模型接口和服务端认证请求共用,不携带账号凭据
|
||||
pub fn build_codex_profile_headers(profile: &CodexWireProfile) -> CodexClientResult<HeaderMap> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
|
||||
@@ -16,10 +16,12 @@ pub(super) struct CompiledStep {
|
||||
|
||||
impl CompiledStep {
|
||||
pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> {
|
||||
if rule.action == PrivacyAction::AnonymizeWorkspace
|
||||
&& (rule.scope != PrivacyScope::TurnMetadata
|
||||
|| rule.selector != "$.workspaces"
|
||||
|| rule.pattern.is_some())
|
||||
if matches!(
|
||||
rule.action,
|
||||
PrivacyAction::AnonymizeProject | PrivacyAction::AnonymizeWorkspace
|
||||
) && (rule.scope != PrivacyScope::TurnMetadata
|
||||
|| rule.selector != "$.workspaces"
|
||||
|| rule.pattern.is_some())
|
||||
{
|
||||
return Err("工作区匿名化仅支持 turn_metadata 的 $.workspaces,且不使用匹配表达式");
|
||||
}
|
||||
@@ -99,6 +101,9 @@ impl CompiledStep {
|
||||
) -> Result<bool, &'static str> {
|
||||
budget.step()?;
|
||||
match self.rule.action {
|
||||
PrivacyAction::AnonymizeProject => {
|
||||
*count += super::workspace::anonymize_project(value, budget)?;
|
||||
}
|
||||
PrivacyAction::AnonymizeWorkspace => {
|
||||
*count += super::workspace::anonymize(value, budget)?;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,42 @@ pub(super) fn account_session_scope(session: &str, account: &ProviderAccount) ->
|
||||
}
|
||||
|
||||
pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<usize, &'static str> {
|
||||
let count = anonymize_project(value, budget)?;
|
||||
let workspaces = value.as_object_mut().ok_or("工作区映射必须是对象")?;
|
||||
let mut renamed = Map::new();
|
||||
// 保留已保存组合动作的用户名替换与 Git 裁剪,独立项目动作不包含这些副作用
|
||||
for (path, mut metadata) in std::mem::take(workspaces) {
|
||||
let object = metadata.as_object_mut().ok_or("工作区信息必须是对象")?;
|
||||
object.remove("associated_remote_urls");
|
||||
object.remove("latest_git_commit_hash");
|
||||
let split = path.rfind(['/', '\\']).ok_or("工作区路径缺少工程目录")?;
|
||||
let mut alias = String::new();
|
||||
let mut username = false;
|
||||
for part in path[..=split].split_inclusive(['/', '\\']) {
|
||||
let component = part.trim_end_matches(['/', '\\']);
|
||||
if username && !component.is_empty() {
|
||||
alias.push_str("user");
|
||||
alias.push_str(&part[component.len()..]);
|
||||
username = false;
|
||||
} else {
|
||||
alias.push_str(part);
|
||||
username = component.eq_ignore_ascii_case("users")
|
||||
|| component.eq_ignore_ascii_case("home");
|
||||
}
|
||||
}
|
||||
alias.push_str(&path[split + 1..]);
|
||||
if renamed.insert(alias, metadata).is_some() {
|
||||
return Err("工作区匿名化产生重名");
|
||||
}
|
||||
}
|
||||
*workspaces = renamed;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub(super) fn anonymize_project(
|
||||
value: &mut Value,
|
||||
budget: &mut Budget<'_>,
|
||||
) -> Result<usize, &'static str> {
|
||||
let workspaces = value.as_object().ok_or("工作区映射必须是对象")?;
|
||||
if workspaces.is_empty() {
|
||||
return Ok(0);
|
||||
@@ -32,9 +68,7 @@ pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<us
|
||||
let mut renamed = Map::new();
|
||||
for (path, metadata) in workspaces {
|
||||
budget.text(path)?;
|
||||
let mut metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
|
||||
metadata.remove("associated_remote_urls");
|
||||
metadata.remove("latest_git_commit_hash");
|
||||
let metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
|
||||
let alias = alias_path(path, session)?;
|
||||
if renamed.insert(alias, Value::Object(metadata)).is_some() {
|
||||
return Err("工作区匿名化产生重名");
|
||||
@@ -63,21 +97,8 @@ fn alias_path(path: &str, session: &str) -> Result<String, &'static str> {
|
||||
hash.update(session.as_bytes());
|
||||
hash.update(path.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
// 保留客户端的分隔符和父目录层级,用户名与工程名改用化名
|
||||
let mut alias = String::new();
|
||||
let mut username = false;
|
||||
for part in path[..=split].split_inclusive(['/', '\\']) {
|
||||
let component = part.trim_end_matches(['/', '\\']);
|
||||
if username && !component.is_empty() {
|
||||
alias.push_str("user");
|
||||
alias.push_str(&part[component.len()..]);
|
||||
username = false;
|
||||
} else {
|
||||
alias.push_str(part);
|
||||
username =
|
||||
component.eq_ignore_ascii_case("users") || component.eq_ignore_ascii_case("home");
|
||||
}
|
||||
}
|
||||
// 只改工程名,父目录与用户名交给独立的字段名替换步骤
|
||||
let mut alias = path[..=split].to_owned();
|
||||
alias.push_str(&shuffled_project_name(&path[split + 1..], &digest));
|
||||
alias.push_str(&format!(
|
||||
"-{}-{}",
|
||||
|
||||
@@ -389,6 +389,7 @@ fn pat_service(server: &MockServer) -> CodexCredentialAdminService {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
runtime_policy(),
|
||||
)
|
||||
.expect("auth client");
|
||||
CodexCredentialAdminService::new(
|
||||
@@ -505,6 +506,7 @@ async fn pat_import_times_out_without_falling_back_to_document_identity() {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
runtime_policy(),
|
||||
);
|
||||
let service = CodexCredentialAdminService::new(
|
||||
Arc::new(UnusedRefresher),
|
||||
|
||||
@@ -171,6 +171,7 @@ async fn complete_with_name(
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -228,6 +229,11 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() {
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
wire_profile,
|
||||
Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
gateway_core::account::OpaqueProviderData::new(serde_json::json!({
|
||||
"client": "desktop", "platform": "macos", "versionMode": "latest", "osVersion": "27.0.1"
|
||||
}).as_object().unwrap().clone()),
|
||||
))),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -379,6 +385,54 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() {
|
||||
assert!(!parameters.contains_key("nonce"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authorization_uses_global_cli_metadata_and_rejects_invalid_configuration() {
|
||||
let document = |value: serde_json::Value| {
|
||||
gateway_core::account::OpaqueProviderData::new(value.as_object().unwrap().clone())
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
document(
|
||||
serde_json::json!({"client":"cli","platform":"macos","versionMode":"fixed","codexVersion":"0.170.0"}),
|
||||
),
|
||||
)));
|
||||
let service = CodexOAuthAdminService::new(
|
||||
Arc::new(PendingStore::default()),
|
||||
Arc::new(Exchanger {
|
||||
id_token: "unused".into(),
|
||||
}),
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
mutation: mutation(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let outer = Url::parse(&started.authorization_url).unwrap();
|
||||
let inner = outer
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == "authorize_url")
|
||||
.unwrap()
|
||||
.1
|
||||
.into_owned();
|
||||
let inner = Url::parse(&inner).unwrap();
|
||||
let parameters: std::collections::BTreeMap<_, _> = inner.query_pairs().into_owned().collect();
|
||||
assert_eq!(parameters["originator"], "codex_cli_rs");
|
||||
assert!(!parameters.contains_key("codex_app_version"));
|
||||
*policy.0.lock().unwrap() = document(serde_json::json!({"client":"unsupported"}));
|
||||
assert!(matches!(
|
||||
service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
mutation: mutation()
|
||||
})
|
||||
.await,
|
||||
Err(CodexOAuthAdminError::Profile(_))
|
||||
));
|
||||
}
|
||||
|
||||
fn profile() -> CodexWireProfileState {
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default())
|
||||
}
|
||||
@@ -395,6 +449,7 @@ async fn separate_new_authorizations_use_distinct_surface_stable_ids() {
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -452,6 +507,7 @@ async fn repeated_reauthorization_preserves_surface_id_with_a_cleared_name() {
|
||||
store.clone(),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -510,6 +566,7 @@ async fn reauthorization_binds_the_selected_slot_to_the_new_oauth_account() {
|
||||
store,
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
|
||||
@@ -13,6 +13,60 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
use crate::support::{MemoryAccountStore, profile, secret};
|
||||
|
||||
#[tokio::test]
|
||||
async fn profile_subscription_and_avatar_follow_global_identity_changes() {
|
||||
let server = MockServer::start().await;
|
||||
let (store, _) = service("acct_global_profile", &server).await;
|
||||
let account = store.account("acct_global_profile").unwrap();
|
||||
for (endpoint, body) in [
|
||||
(
|
||||
"/api/codex/profiles/me",
|
||||
json!({"profile":{"profile_picture_url":"https://chatgpt.com/backend-api/estuary/public_content/enc/avatar-token="},"stats":{}}),
|
||||
),
|
||||
("/backend-api/subscriptions", json!({"will_renew":true})),
|
||||
] {
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
Mock::given(path("/estuary/public_content/enc/avatar-token="))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw("<svg/>", "image/svg+xml"))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new(
|
||||
Default::default(),
|
||||
)),
|
||||
));
|
||||
let service = CodexCredentialProfileService::new(
|
||||
store.repository(),
|
||||
wire_profile(),
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
server.uri(),
|
||||
policy.clone(),
|
||||
);
|
||||
for os in ["27.0.1", "27.0.2"] {
|
||||
let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test");
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(
|
||||
json!({"mode":"custom","userAgent":ua})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
service.profile_statistics(account.id()).await.unwrap();
|
||||
service.subscription(account.id()).await.unwrap();
|
||||
let mut avatar = service.profile_avatar(account.id()).await.unwrap();
|
||||
while avatar.body.try_next().await.unwrap().is_some() {}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 3);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(request.headers["user-agent"], ua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_profile() -> CodexWireProfileState {
|
||||
CodexWireProfileState::new(CodexWireProfile {
|
||||
client_kind: provider_openai::profile::selection::ClientKind::Desktop,
|
||||
@@ -58,6 +112,7 @@ async fn service(
|
||||
.build()
|
||||
.expect("client"),
|
||||
server.uri(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
(store, service)
|
||||
}
|
||||
|
||||
@@ -33,6 +33,74 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
use crate::support::{MemoryAccountStore, profile, secret};
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_background_operations_use_current_global_identity_and_recover_from_invalid_profile()
|
||||
{
|
||||
use gateway_core::account::OpaqueProviderData;
|
||||
let server = MockServer::start().await;
|
||||
for (endpoint, body) in [
|
||||
(
|
||||
"/api/codex/usage",
|
||||
json!({"rate_limit":{"allowed":true,"primary_window":{"used_percent":10}}}),
|
||||
),
|
||||
(
|
||||
"/api/codex/rate-limit-reset-credits",
|
||||
json!({"available_count":0,"credits":[]}),
|
||||
),
|
||||
(
|
||||
"/api/codex/rate-limit-reset-credits/consume",
|
||||
json!({"code":"reset","credit":{"id":"test-credit","reset_type":"codex_rate_limits"}}),
|
||||
),
|
||||
] {
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_global_identity").await;
|
||||
let account = store.account("acct_global_identity").unwrap();
|
||||
let document =
|
||||
|value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone());
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(document(json!({"mode":"custom","userAgent":"invalid"}))),
|
||||
));
|
||||
let service = CodexCredentialQuotaService::new(
|
||||
store.repository(),
|
||||
wire_profile(),
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
server.uri(),
|
||||
Arc::new(crate::support::MemoryCooldownPort::new()),
|
||||
policy.clone(),
|
||||
)
|
||||
.with_initial_sync_delays(Arc::new(|| Duration::ZERO));
|
||||
assert!(matches!(
|
||||
service.synchronize().await,
|
||||
Err(CodexCredentialQuotaError::Profile(_))
|
||||
));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
for os in ["27.0.1", "27.0.2"] {
|
||||
let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test");
|
||||
*policy.0.lock().unwrap() = document(json!({"mode":"custom","userAgent":ua}));
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
if os == "27.0.1" {
|
||||
assert_eq!(service.synchronize().await.unwrap().updated, 1);
|
||||
} else {
|
||||
service.refresh_account(account.id()).await.unwrap();
|
||||
}
|
||||
service.list_reset_credits(account.id()).await.unwrap();
|
||||
service
|
||||
.consume_reset_credit(account.id(), Some("test-credit"), uuid::Uuid::new_v4())
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 3);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(request.headers["user-agent"], ua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_profile() -> CodexWireProfileState {
|
||||
CodexWireProfileState::new(CodexWireProfile {
|
||||
client_kind: provider_openai::profile::selection::ClientKind::Desktop,
|
||||
|
||||
@@ -614,6 +614,7 @@ async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
)),
|
||||
Arc::new(RefreshLeases),
|
||||
Arc::new(RefreshCredentialState),
|
||||
|
||||
@@ -49,7 +49,7 @@ async fn refresh_and_code_exchange_use_the_selected_account_proxy() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() {
|
||||
async fn authentication_requests_track_global_identity_and_releases() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
@@ -60,18 +60,33 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
.mount(&server)
|
||||
.await;
|
||||
let profile = provider_openai::profile::CodexWireProfileState::new(Default::default());
|
||||
let policy = std::sync::Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new(
|
||||
Default::default(),
|
||||
)),
|
||||
));
|
||||
let client = provider_openai::credential::token_client::openai_token_client(
|
||||
TokenClientConfig {
|
||||
client_id: "audit-client".to_owned(),
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
profile.clone(),
|
||||
policy.clone(),
|
||||
)
|
||||
.expect("production auth transport");
|
||||
for (core, desktop, build) in [
|
||||
("1.2.3", "26.800.10000", "8000"),
|
||||
("1.2.4", "26.901.10000", "8109"),
|
||||
for (core, desktop, build, os_version) in [
|
||||
("1.2.3", "26.800.10000", "8000", "27.0.1"),
|
||||
("1.2.4", "26.901.10000", "8109", "27.0.2"),
|
||||
] {
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(
|
||||
serde_json::json!({
|
||||
"client": "desktop", "platform": "macos", "versionMode": "latest",
|
||||
"osVersion": os_version
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
profile.update_bundled_release(&provider_openai::profile::CodexBundledReleaseProfile {
|
||||
codex_version: core.to_owned(),
|
||||
desktop_version: desktop.to_owned(),
|
||||
@@ -91,7 +106,9 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
let exchange = &requests[requests.len() - 1];
|
||||
assert_eq!(
|
||||
refresh.headers["user-agent"],
|
||||
profile.snapshot().user_agent()
|
||||
format!(
|
||||
"Codex Desktop/{core} (Mac OS {os_version}; arm64) unknown (Codex Desktop; {desktop})"
|
||||
)
|
||||
);
|
||||
assert_eq!(refresh.headers["originator"], "Codex Desktop");
|
||||
assert_eq!(refresh.headers["content-type"], "application/json");
|
||||
@@ -99,18 +116,32 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
exchange.headers["content-type"],
|
||||
"application/x-www-form-urlencoded"
|
||||
);
|
||||
for name in [
|
||||
"originator",
|
||||
"user-agent",
|
||||
"version",
|
||||
"x-openai-internal-codex-residency",
|
||||
] {
|
||||
assert!(!exchange.headers.contains_key(name), "raw exchange: {name}");
|
||||
}
|
||||
for name in ["authorization", "chatgpt-account-id", "version"] {
|
||||
assert!(!refresh.headers.contains_key(name), "refresh: {name}");
|
||||
assert_eq!(
|
||||
exchange.headers["user-agent"],
|
||||
refresh.headers["user-agent"]
|
||||
);
|
||||
assert_eq!(exchange.headers["originator"], "Codex Desktop");
|
||||
for request in [refresh, exchange] {
|
||||
for name in ["authorization", "chatgpt-account-id", "version"] {
|
||||
assert!(!request.headers.contains_key(name), "auth request: {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default());
|
||||
assert!(matches!(
|
||||
client.refresh("audit-refresh").await,
|
||||
Err(RefreshFailure::RetryableTransport { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
client
|
||||
.exchange_authorization_code(AuthorizationCodeGrant {
|
||||
code: SecretString::from("audit-code"),
|
||||
code_verifier: SecretString::from("audit-verifier")
|
||||
})
|
||||
.await,
|
||||
Err(AuthorizationCodeExchangeError::Unavailable)
|
||||
));
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 4);
|
||||
}
|
||||
|
||||
fn client(server: &MockServer) -> OpenAiTokenClient {
|
||||
@@ -124,6 +155,7 @@ fn client(server: &MockServer) -> OpenAiTokenClient {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -392,6 +424,7 @@ async fn authorization_code_response_timeouts_remain_ambiguous_without_exposing_
|
||||
token_endpoint: format!("http://{address}/oauth/token?PRIVATE_URL_MARKER"),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let error = client
|
||||
.exchange_authorization_code(AuthorizationCodeGrant {
|
||||
|
||||
@@ -247,7 +247,7 @@ async fn restored_cache_release_should_stay_in_version_lag_history() {
|
||||
assert_eq!(lagged.desktop_version, "26.810.41047");
|
||||
assert_eq!(
|
||||
lagged.user_agent(),
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 27.2.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
);
|
||||
// 滞后两档落到启动种子,恢复观察与启动种子共同构成启动历史。
|
||||
assert_eq!(
|
||||
|
||||
@@ -10,7 +10,7 @@ use provider_openai::profile::{
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn six_presets_have_explicit_availability_and_cli_has_no_desktop_suffix() {
|
||||
fn six_presets_resolve_available_client_identities() {
|
||||
let state = CodexWireProfileState::new(CodexWireProfile::default());
|
||||
assert_eq!(
|
||||
ClientProfileSelection::default().resolve(&state).unwrap(),
|
||||
@@ -25,22 +25,29 @@ fn six_presets_have_explicit_availability_and_cli_has_no_desktop_suffix() {
|
||||
.iter()
|
||||
.all(|preset| preset["automaticAvailable"] == true)
|
||||
);
|
||||
for platform in [
|
||||
ClientPlatform::Macos,
|
||||
ClientPlatform::Linux,
|
||||
ClientPlatform::Windows,
|
||||
] {
|
||||
let selection = ClientProfileSelection {
|
||||
client: ClientKind::Cli,
|
||||
platform,
|
||||
..Default::default()
|
||||
};
|
||||
for preset in presets
|
||||
.iter()
|
||||
.filter(|preset| preset["configuration"]["client"] == "cli")
|
||||
{
|
||||
let selection: ClientProfileSelection =
|
||||
serde_json::from_value(preset["configuration"].clone()).unwrap();
|
||||
let profile = selection.resolve(&state).unwrap();
|
||||
assert_eq!(profile.originator, "codex_cli_rs");
|
||||
assert_eq!(profile.os_type, platform.os_type());
|
||||
if selection.platform == ClientPlatform::Macos {
|
||||
let version = &profile.codex_version;
|
||||
assert_eq!(
|
||||
profile.user_agent(),
|
||||
format!(
|
||||
"codex-tui/{version} (Mac OS 27.2.1; arm64) Apple_Terminal/488.9 (codex-tui; {version})"
|
||||
)
|
||||
);
|
||||
assert_eq!(profile.originator, "codex-tui");
|
||||
} else {
|
||||
assert_eq!(profile.originator, "codex_cli_rs");
|
||||
assert!(profile.user_agent().ends_with("unknown"));
|
||||
}
|
||||
assert_eq!(profile.os_type, selection.platform.os_type());
|
||||
assert!(profile.desktop_version.is_empty());
|
||||
assert!(!profile.user_agent().contains("Desktop"));
|
||||
assert!(profile.user_agent().ends_with("unknown"));
|
||||
assert!(profile.verified_at > chrono::DateTime::UNIX_EPOCH);
|
||||
}
|
||||
for platform in [ClientPlatform::Linux, ClientPlatform::Windows] {
|
||||
|
||||
@@ -73,7 +73,7 @@ async fn lagged_profiles_track_observed_release_history() {
|
||||
assert_eq!(lagged.desktop_version, "26.810.41047");
|
||||
assert_eq!(
|
||||
lagged.user_agent(),
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 27.2.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
);
|
||||
assert_eq!(
|
||||
selection(Some(2)).resolve(&state).unwrap().codex_version,
|
||||
|
||||
@@ -10,6 +10,119 @@ fn anonymous_rule() -> PrivacyRule {
|
||||
)
|
||||
}
|
||||
|
||||
fn composed_rule(username: &str) -> PrivacyRule {
|
||||
let mut configured = rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeProject,
|
||||
);
|
||||
let mut rename = step(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::RenameKey,
|
||||
);
|
||||
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
|
||||
rename.replacement = format!("${{1}}{username}${{2}}");
|
||||
configured.steps.push(rename);
|
||||
for selector in [
|
||||
"$.workspaces.*.associated_remote_urls",
|
||||
"$.workspaces.*.latest_git_commit_hash",
|
||||
] {
|
||||
configured.steps.push(step(
|
||||
PrivacyScope::TurnMetadata,
|
||||
selector,
|
||||
PrivacyAction::RemoveField,
|
||||
));
|
||||
}
|
||||
configured
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_anonymization_preserves_usernames_and_git_information() {
|
||||
for path in [
|
||||
"/home/alex/projects/private",
|
||||
"/Users/alex/private",
|
||||
r"C:\Users\alex\private",
|
||||
] {
|
||||
let metadata = json!({"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true});
|
||||
let mut request = sample(
|
||||
vec![rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeProject,
|
||||
)],
|
||||
json!({"turn_metadata":{"workspaces":{path:metadata}}}),
|
||||
);
|
||||
request
|
||||
.headers
|
||||
.insert("session-id".into(), vec!["sample-session".into()]);
|
||||
let output = preview(request).unwrap();
|
||||
let (alias, value) = output.body["turn_metadata"]["workspaces"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(alias.starts_with(path.rsplit_once(['/', '\\']).unwrap().0));
|
||||
assert_ne!(alias, path);
|
||||
assert_eq!(value, &metadata);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_steps_preserve_combined_behavior_and_allow_customization() {
|
||||
for path in [
|
||||
"/home/alex/projects/private",
|
||||
"/Users/alex/private",
|
||||
r"C:\Users\alex\private",
|
||||
] {
|
||||
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}}});
|
||||
let mut request = sample(
|
||||
vec![anonymous_rule()],
|
||||
json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}),
|
||||
);
|
||||
request.turn_metadata = Some(metadata.to_string());
|
||||
request
|
||||
.headers
|
||||
.insert("session-id".into(), vec!["sample-session".into()]);
|
||||
request
|
||||
.headers
|
||||
.insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]);
|
||||
let combined = preview(request.clone()).unwrap();
|
||||
request.policy.rules = vec![composed_rule("user")];
|
||||
let composed = preview(request.clone()).unwrap();
|
||||
assert_eq!(composed.body, combined.body);
|
||||
assert_eq!(composed.headers, combined.headers);
|
||||
assert_eq!(composed.turn_metadata, combined.turn_metadata);
|
||||
|
||||
let mut customized = composed_rule("blg");
|
||||
customized.steps.remove(2);
|
||||
request.policy.rules = vec![customized];
|
||||
let output = preview(request).unwrap();
|
||||
let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap();
|
||||
let (alias, workspace) = value["workspaces"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
alias.starts_with(
|
||||
&path
|
||||
.rsplit_once(['/', '\\'])
|
||||
.unwrap()
|
||||
.0
|
||||
.replace("alex", "blg")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
workspace["associated_remote_urls"],
|
||||
metadata["workspaces"][path]["associated_remote_urls"]
|
||||
);
|
||||
assert!(workspace.get("latest_git_commit_hash").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
|
||||
for path in [
|
||||
@@ -209,7 +322,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
|
||||
compile(&policy(vec![rule(
|
||||
scope,
|
||||
selector,
|
||||
PrivacyAction::AnonymizeWorkspace
|
||||
PrivacyAction::AnonymizeProject
|
||||
)]))
|
||||
.is_err()
|
||||
);
|
||||
|
||||
@@ -94,6 +94,11 @@ pub(super) fn map_quota_error(error: GrokQuotaError) -> ProviderAdminError {
|
||||
Error::InvalidData => (Kind::Invalid, "凭据或额度数据无效"),
|
||||
Error::Upstream => (Kind::Unavailable, "额度查询失败"),
|
||||
Error::Store => (Kind::Unavailable, "额度查询暂不可用"),
|
||||
Error::Profile(source) => {
|
||||
return provider_error(Kind::Unavailable)
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
};
|
||||
provider_error(kind).with_public_message(message)
|
||||
}
|
||||
@@ -108,6 +113,11 @@ pub(super) fn map_catalog_error(error: GrokCredentialCatalogError) -> ProviderAd
|
||||
Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"),
|
||||
Error::Upstream => (Kind::Unavailable, "模型查询失败"),
|
||||
Error::Cache | Error::Store => (Kind::Unavailable, "模型查询暂不可用"),
|
||||
Error::Profile(source) => {
|
||||
return provider_error(Kind::Unavailable)
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
};
|
||||
provider_error(kind).with_public_message(message)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use gateway_core::account::{
|
||||
};
|
||||
use gateway_core::provider_ports::{
|
||||
ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope,
|
||||
ProviderRuntimePolicyPort,
|
||||
};
|
||||
use gateway_core::routing::{ProviderCatalogGeneration, ProviderKind};
|
||||
|
||||
@@ -348,6 +349,8 @@ pub enum GrokCredentialCatalogError {
|
||||
ConflictingModelFacts,
|
||||
#[error("Grok model catalog cache update failed")]
|
||||
Cache,
|
||||
#[error("Grok client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Grok provider account store is unavailable")]
|
||||
Store,
|
||||
}
|
||||
@@ -359,6 +362,7 @@ pub struct GrokCredentialCatalogService {
|
||||
cache: Arc<dyn GrokCredentialCatalogCache>,
|
||||
published: Arc<RwLock<PublishedCatalogState>>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
/// 同一目录模型可由多个套餐的成员账号发现
|
||||
@@ -377,6 +381,7 @@ impl GrokCredentialCatalogService {
|
||||
transport: Arc<dyn GrokModelCatalogTransport>,
|
||||
cache: Arc<dyn GrokCredentialCatalogCache>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
@@ -384,6 +389,7 @@ impl GrokCredentialCatalogService {
|
||||
cache,
|
||||
published: Arc::new(RwLock::new(PublishedCatalogState::default())),
|
||||
wire_profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,12 +584,18 @@ impl GrokCredentialCatalogService {
|
||||
candidates: Vec<LoadedGrokCredential>,
|
||||
) -> Result<FetchedCredentialCatalog, GrokCredentialCatalogError> {
|
||||
let mut last_error = None;
|
||||
let profile = XaiWireProfileState::new(
|
||||
self.wire_profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(GrokCredentialCatalogError::Profile)?,
|
||||
);
|
||||
for candidate in candidates.into_iter().take(MAX_CATALOG_FETCH_ATTEMPTS) {
|
||||
match fetch_candidate_catalog(
|
||||
Arc::clone(&self.client),
|
||||
scope.clone(),
|
||||
candidate,
|
||||
self.wire_profile.clone(),
|
||||
profile.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
|
||||
use crate::credential::token::{parse_oauth_error, parse_refresh_success, parse_token_success};
|
||||
use crate::{
|
||||
AllowedRedirectUri, AuthorizationCodeGrant, DiscoveryDocument, FormField, GrokOAuthConfig,
|
||||
HttpHeader, OAuthError, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport,
|
||||
OAuthOperation, OAuthPrincipal, PendingAuthorization, RefreshTokenGrant, RefreshedTokenSet,
|
||||
TokenCandidate, TokenVerificationContext, TokenVerifier, VerificationFailure, VerificationFlow,
|
||||
OAuthError, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport, OAuthOperation,
|
||||
OAuthPrincipal, PendingAuthorization, RefreshTokenGrant, RefreshedTokenSet, TokenCandidate,
|
||||
TokenVerificationContext, TokenVerifier, VerificationFailure, VerificationFlow,
|
||||
VerificationMethod, VerifiedTokenSet,
|
||||
};
|
||||
|
||||
@@ -16,6 +18,7 @@ use crate::{
|
||||
pub struct GrokOAuthClient {
|
||||
config: GrokOAuthConfig,
|
||||
wire_profile: crate::XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
transport: Arc<dyn OAuthHttpTransport>,
|
||||
verifier: Arc<dyn TokenVerifier>,
|
||||
outbound_proxy: Option<gateway_core::account::OutboundProxy>,
|
||||
@@ -29,12 +32,14 @@ impl GrokOAuthClient {
|
||||
wire_profile: crate::XaiWireProfileState,
|
||||
transport: Arc<dyn OAuthHttpTransport>,
|
||||
verifier: Arc<dyn TokenVerifier>,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
wire_profile,
|
||||
transport,
|
||||
verifier,
|
||||
runtime_policy,
|
||||
outbound_proxy: None,
|
||||
}
|
||||
}
|
||||
@@ -59,10 +64,11 @@ impl GrokOAuthClient {
|
||||
/// transport 失败、非成功状态、JSON 非法、issuer 不匹配、端点跨 origin、
|
||||
/// 缺少 JWKS 或算法不安全时返回错误
|
||||
pub async fn discover(&self) -> Result<DiscoveryDocument, OAuthError> {
|
||||
let profile = self.request_profile(OAuthOperation::Discovery).await?;
|
||||
let response = self
|
||||
.execute(
|
||||
OAuthOperation::Discovery,
|
||||
OAuthHttpRequest::get(self.config.discovery_url()),
|
||||
OAuthHttpRequest::get(self.config.discovery_url()).with_profile(&profile),
|
||||
)
|
||||
.await?;
|
||||
if !is_success(&response) {
|
||||
@@ -101,10 +107,13 @@ impl GrokOAuthClient {
|
||||
discovery: &DiscoveryDocument,
|
||||
grant: AuthorizationCodeGrant,
|
||||
) -> Result<VerifiedTokenSet, OAuthError> {
|
||||
let profile = self
|
||||
.request_profile(OAuthOperation::AuthorizationCodeToken)
|
||||
.await?;
|
||||
let (code, redirect_uri, code_verifier, nonce) = grant.into_parts();
|
||||
let request = OAuthHttpRequest::post(
|
||||
discovery.token_endpoint().clone(),
|
||||
vec![self.version_header()],
|
||||
vec![],
|
||||
vec![
|
||||
FormField::public("grant_type", "authorization_code"),
|
||||
FormField::secret("code", code),
|
||||
@@ -114,7 +123,10 @@ impl GrokOAuthClient {
|
||||
],
|
||||
);
|
||||
let response = self
|
||||
.execute(OAuthOperation::AuthorizationCodeToken, request)
|
||||
.execute(
|
||||
OAuthOperation::AuthorizationCodeToken,
|
||||
request.with_profile(&profile),
|
||||
)
|
||||
.await?;
|
||||
if !is_success(&response) {
|
||||
return Err(parse_oauth_error(
|
||||
@@ -144,7 +156,9 @@ impl GrokOAuthClient {
|
||||
let evidence = self
|
||||
.verifier
|
||||
.verify(
|
||||
context.with_outbound_proxy(self.outbound_proxy.as_ref()),
|
||||
context
|
||||
.with_outbound_proxy(self.outbound_proxy.as_ref())
|
||||
.with_wire_profile(&profile),
|
||||
candidate,
|
||||
)
|
||||
.await?;
|
||||
@@ -172,6 +186,9 @@ impl GrokOAuthClient {
|
||||
candidate: crate::GrokOAuthImportCandidate,
|
||||
) -> Result<VerifiedTokenSet, crate::GrokOAuthImportError> {
|
||||
let validated = candidate.validate(&self.config, chrono::Utc::now())?;
|
||||
let profile = self
|
||||
.request_profile(OAuthOperation::CredentialImport)
|
||||
.await?;
|
||||
let scope = validated.scope;
|
||||
let mut tokens = validated.tokens;
|
||||
let flow = if validated.requires_refresh {
|
||||
@@ -180,7 +197,11 @@ impl GrokOAuthClient {
|
||||
.take()
|
||||
.ok_or(crate::GrokOAuthImportError::InvalidField("refresh_token"))?;
|
||||
let refreshed = self
|
||||
.refresh(discovery, &RefreshTokenGrant::new(refresh_token.clone()))
|
||||
.refresh_with_profile(
|
||||
discovery,
|
||||
&RefreshTokenGrant::new(refresh_token.clone()),
|
||||
&profile,
|
||||
)
|
||||
.await?;
|
||||
tokens = crate::credential::token::UnverifiedTokenSet {
|
||||
access_token: refreshed.access_token().clone(),
|
||||
@@ -214,7 +235,9 @@ impl GrokOAuthClient {
|
||||
let evidence = self
|
||||
.verifier
|
||||
.verify(
|
||||
context.with_outbound_proxy(self.outbound_proxy.as_ref()),
|
||||
context
|
||||
.with_outbound_proxy(self.outbound_proxy.as_ref())
|
||||
.with_wire_profile(&profile),
|
||||
verification_candidate,
|
||||
)
|
||||
.await
|
||||
@@ -250,6 +273,16 @@ impl GrokOAuthClient {
|
||||
&self,
|
||||
discovery: &DiscoveryDocument,
|
||||
grant: &RefreshTokenGrant,
|
||||
) -> Result<RefreshedTokenSet, OAuthError> {
|
||||
let profile = self.request_profile(OAuthOperation::RefreshToken).await?;
|
||||
self.refresh_with_profile(discovery, grant, &profile).await
|
||||
}
|
||||
|
||||
async fn refresh_with_profile(
|
||||
&self,
|
||||
discovery: &DiscoveryDocument,
|
||||
grant: &RefreshTokenGrant,
|
||||
profile: &crate::XaiWireProfile,
|
||||
) -> Result<RefreshedTokenSet, OAuthError> {
|
||||
let form = vec![
|
||||
FormField::public("grant_type", "refresh_token"),
|
||||
@@ -259,11 +292,8 @@ impl GrokOAuthClient {
|
||||
let response = self
|
||||
.execute(
|
||||
OAuthOperation::RefreshToken,
|
||||
OAuthHttpRequest::post(
|
||||
discovery.token_endpoint().clone(),
|
||||
vec![self.version_header()],
|
||||
form,
|
||||
),
|
||||
OAuthHttpRequest::post(discovery.token_endpoint().clone(), vec![], form)
|
||||
.with_profile(profile),
|
||||
)
|
||||
.await?;
|
||||
if !is_success(&response) {
|
||||
@@ -284,8 +314,19 @@ impl GrokOAuthClient {
|
||||
.map_err(|failure| OAuthError::transport(operation, failure))
|
||||
}
|
||||
|
||||
fn version_header(&self) -> HttpHeader {
|
||||
HttpHeader::new("x-grok-client-version", self.wire_profile.client_version())
|
||||
async fn request_profile(
|
||||
&self,
|
||||
operation: OAuthOperation,
|
||||
) -> Result<crate::XaiWireProfile, OAuthError> {
|
||||
self.wire_profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
OAuthError::transport(
|
||||
operation,
|
||||
crate::TransportFailure::new(crate::TransportFailureKind::NotSent),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -161,7 +161,9 @@ impl ReqwestOidcTokenVerifier {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
}
|
||||
let kid = header.kid.as_deref().ok_or(VerificationFailure::Rejected)?;
|
||||
let key = self.decoding_key(context.jwks_uri(), kid, egress).await?;
|
||||
let key = self
|
||||
.decoding_key(context.jwks_uri(), kid, egress, context.wire_profile())
|
||||
.await?;
|
||||
|
||||
let mut validation = Validation::new(Algorithm::ES256);
|
||||
validation.leeway = 0;
|
||||
@@ -221,11 +223,12 @@ impl ReqwestOidcTokenVerifier {
|
||||
if !valid_bearer_token(access_token) {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
}
|
||||
let response = egress
|
||||
let request = egress
|
||||
.client
|
||||
.get(context.userinfo_endpoint().clone())
|
||||
.header(ACCEPT, "application/json")
|
||||
.bearer_auth(access_token)
|
||||
.bearer_auth(access_token);
|
||||
let response = with_profile(request, context.wire_profile())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| VerificationFailure::Unavailable)?;
|
||||
@@ -253,6 +256,7 @@ impl ReqwestOidcTokenVerifier {
|
||||
jwks_uri: &Url,
|
||||
kid: &str,
|
||||
egress: &OidcEgress,
|
||||
profile: Option<&crate::XaiWireProfile>,
|
||||
) -> Result<DecodingKey, VerificationFailure> {
|
||||
if !valid_key_id(kid) {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
@@ -270,7 +274,7 @@ impl ReqwestOidcTokenVerifier {
|
||||
}
|
||||
|
||||
// fresh cache 未命中 kid 时只强制刷新一次,以支持官方密钥轮换
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client).await?;
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client, profile).await?;
|
||||
cache.replace(jwks_uri.clone(), keys);
|
||||
return cache
|
||||
.keys
|
||||
@@ -280,7 +284,7 @@ impl ReqwestOidcTokenVerifier {
|
||||
}
|
||||
|
||||
// 过期缓存不会在网络或协议失败时作为 stale fallback 使用
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client).await?;
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client, profile).await?;
|
||||
cache.replace(jwks_uri.clone(), keys);
|
||||
cache
|
||||
.keys
|
||||
@@ -293,13 +297,15 @@ impl ReqwestOidcTokenVerifier {
|
||||
&self,
|
||||
jwks_uri: &Url,
|
||||
client: &Client,
|
||||
profile: Option<&crate::XaiWireProfile>,
|
||||
) -> Result<HashMap<String, CachedJwk>, VerificationFailure> {
|
||||
if !self.endpoint_policy.validate_jwks(jwks_uri) {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
}
|
||||
let response = client
|
||||
let request = client
|
||||
.get(jwks_uri.clone())
|
||||
.header(ACCEPT, "application/json")
|
||||
.header(ACCEPT, "application/json");
|
||||
let response = with_profile(request, profile)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| VerificationFailure::Unavailable)?;
|
||||
@@ -318,6 +324,18 @@ impl ReqwestOidcTokenVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
fn with_profile(
|
||||
request: reqwest::RequestBuilder,
|
||||
profile: Option<&crate::XaiWireProfile>,
|
||||
) -> reqwest::RequestBuilder {
|
||||
match profile {
|
||||
Some(profile) => request
|
||||
.header("user-agent", profile.user_agent())
|
||||
.header("x-grok-client-version", &profile.client_version),
|
||||
None => request,
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenVerifier for ReqwestOidcTokenVerifier {
|
||||
fn verify<'a>(
|
||||
&'a self,
|
||||
|
||||
@@ -10,6 +10,7 @@ use gateway_core::account::{
|
||||
AccountQuotaResetWindow, AccountQuotaSignals, CredentialRevision, ProviderAccount,
|
||||
ProviderAccountId, QuotaObservation, QuotaResetPeriod, QuotaState,
|
||||
};
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use super::repository::{GrokCredentialRepository, LoadedGrokCredential};
|
||||
@@ -145,7 +146,7 @@ impl GrokQuotaSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[derive(Debug, Clone, thiserror::Error)]
|
||||
pub enum GrokQuotaError {
|
||||
#[error("xAI quota account is unavailable")]
|
||||
AccountUnavailable,
|
||||
@@ -155,6 +156,8 @@ pub enum GrokQuotaError {
|
||||
InvalidData,
|
||||
#[error("xAI quota upstream request failed")]
|
||||
Upstream,
|
||||
#[error("xAI quota client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("xAI quota store is unavailable")]
|
||||
Store,
|
||||
}
|
||||
@@ -166,6 +169,7 @@ pub struct GrokCredentialQuotaService {
|
||||
client: Arc<GrokBillingClient>,
|
||||
scheduling: GrokQuotaSchedulingProjection,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
@@ -346,12 +350,14 @@ impl GrokCredentialQuotaService {
|
||||
repository: GrokCredentialRepository,
|
||||
transport: Arc<dyn GrokBillingTransport>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
client: Arc::new(GrokBillingClient::new(transport)),
|
||||
scheduling: GrokQuotaSchedulingProjection::default(),
|
||||
wire_profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,7 +426,13 @@ impl GrokCredentialQuotaService {
|
||||
{
|
||||
return Err(GrokQuotaError::AccountUnavailable);
|
||||
}
|
||||
let session = billing_session(&loaded, &self.wire_profile)?;
|
||||
let profile = XaiWireProfileState::new(
|
||||
self.wire_profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(GrokQuotaError::Profile)?,
|
||||
);
|
||||
let session = billing_session(&loaded, &profile)?;
|
||||
let billing = self
|
||||
.client
|
||||
.fetch(&session)
|
||||
|
||||
@@ -91,6 +91,7 @@ pub struct TokenVerificationContext<'a> {
|
||||
signing_algorithms: &'a [String],
|
||||
expected_nonce: Option<&'a SecretValue>,
|
||||
outbound_proxy: Option<&'a gateway_core::account::OutboundProxy>,
|
||||
wire_profile: Option<&'a crate::XaiWireProfile>,
|
||||
}
|
||||
|
||||
impl<'a> TokenVerificationContext<'a> {
|
||||
@@ -112,9 +113,22 @@ impl<'a> TokenVerificationContext<'a> {
|
||||
signing_algorithms,
|
||||
expected_nonce,
|
||||
outbound_proxy: None,
|
||||
wire_profile: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 认证验证沿用当前 OAuth 操作已冻结的全局客户端身份
|
||||
#[must_use]
|
||||
pub fn with_wire_profile(mut self, profile: &'a crate::XaiWireProfile) -> Self {
|
||||
self.wire_profile = Some(profile);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn wire_profile(&self) -> Option<&crate::XaiWireProfile> {
|
||||
self.wire_profile
|
||||
}
|
||||
|
||||
/// 绑定 OAuth owner 选择的账号出口,供公开的 [`TokenVerifier`] 实现遵守同一代理合同
|
||||
/// 出口只决定路由,不改变 issuer、JWKS、签名和 nonce 的信任校验
|
||||
#[must_use]
|
||||
|
||||
@@ -129,11 +129,13 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, Xai
|
||||
catalog_transport,
|
||||
catalog_cache_port,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let quota = Arc::new(GrokCredentialQuotaService::new(
|
||||
repository.clone(),
|
||||
billing_transport,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let selector: Arc<dyn GrokSessionSelector> = Arc::new(GrokAccountSessionSelector::new(
|
||||
provider_kind.clone(),
|
||||
@@ -162,6 +164,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, Xai
|
||||
profile.clone(),
|
||||
oauth_transport,
|
||||
token_verifier,
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let refresher: Arc<dyn GrokCredentialRefresher> =
|
||||
Arc::new(GrokOAuthRefreshClient::new(Arc::clone(&oauth)));
|
||||
|
||||
@@ -129,6 +129,14 @@ pub struct OAuthHttpRequest {
|
||||
}
|
||||
|
||||
impl OAuthHttpRequest {
|
||||
pub(crate) fn with_profile(mut self, profile: &crate::XaiWireProfile) -> Self {
|
||||
self.headers.extend([
|
||||
HttpHeader::new("x-grok-client-version", &profile.client_version),
|
||||
HttpHeader::new("user-agent", profile.user_agent()),
|
||||
]);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get(url: Url) -> Self {
|
||||
Self {
|
||||
method: HttpMethod::Get,
|
||||
|
||||
@@ -47,6 +47,20 @@ impl XaiWireProfile {
|
||||
pub struct XaiWireProfileState(Arc<RwLock<XaiWireProfile>>);
|
||||
|
||||
impl XaiWireProfileState {
|
||||
/// 账号后台操作按当前全局配置冻结身份,不读取 Client Key 覆盖
|
||||
pub(crate) async fn resolve_global_request_profile(
|
||||
&self,
|
||||
policy: &dyn gateway_core::provider_ports::ProviderRuntimePolicyPort,
|
||||
) -> Result<XaiWireProfile, gateway_core::error::ErrorSource> {
|
||||
let kind = gateway_core::routing::ProviderKind::new("xai")?;
|
||||
let Some(configuration) = policy.load_request_profile(&kind).await? else {
|
||||
return Ok(self.snapshot());
|
||||
};
|
||||
super::selection::GrokClientProfileSelection::parse(&configuration)
|
||||
.and_then(|selection| selection.resolve(self))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new(profile: XaiWireProfile) -> Self {
|
||||
Self(Arc::new(RwLock::new(profile)))
|
||||
|
||||
@@ -126,6 +126,7 @@ impl GrokModelCatalogRequest {
|
||||
session.wire_profile.client_version(),
|
||||
),
|
||||
GrokHeader::public("x-grok-client-mode", session.wire_profile.client_mode()),
|
||||
GrokHeader::public("user-agent", session.wire_profile.user_agent()),
|
||||
GrokHeader::public("accept", "application/json"),
|
||||
];
|
||||
if let Some(email) = &session.email {
|
||||
@@ -289,6 +290,7 @@ impl GrokBillingRequest {
|
||||
session.wire_profile.client_version(),
|
||||
),
|
||||
GrokHeader::public("x-grok-client-mode", session.wire_profile.client_mode()),
|
||||
GrokHeader::public("user-agent", session.wire_profile.user_agent()),
|
||||
GrokHeader::public("accept", "application/json"),
|
||||
];
|
||||
if let Some(email) = &session.email {
|
||||
|
||||
@@ -27,6 +27,103 @@ use crate::support::{
|
||||
const CLI_PROXY_FIXTURE: &[u8] =
|
||||
include_bytes!("../transport/catalog/fixtures/cli_proxy_models.json");
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_billing_and_subscription_use_current_global_identity() {
|
||||
use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode};
|
||||
use provider_xai::{
|
||||
GrokBillingRequest, GrokBillingTransport, GrokBillingTransportFuture,
|
||||
GrokBillingTransportResponse, GrokCredentialCatalogService, GrokCredentialQuotaService,
|
||||
};
|
||||
#[derive(Default)]
|
||||
struct RecordingTransport(Mutex<Vec<Vec<(String, String)>>>);
|
||||
impl RecordingTransport {
|
||||
fn record(&self, headers: &[provider_xai::GrokHeader]) {
|
||||
self.0.lock().unwrap().push(
|
||||
headers
|
||||
.iter()
|
||||
.filter(|h| matches!(h.name(), "user-agent" | "x-grok-client-version"))
|
||||
.map(|h| (h.name().to_owned(), h.value().expose().to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
impl GrokModelCatalogTransport for RecordingTransport {
|
||||
fn execute(&self, request: GrokModelCatalogRequest) -> GrokModelCatalogTransportFuture<'_> {
|
||||
self.record(request.headers());
|
||||
Box::pin(async {
|
||||
Ok(GrokModelCatalogTransportResponse::new(
|
||||
CLI_PROXY_FIXTURE,
|
||||
None,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
impl GrokBillingTransport for RecordingTransport {
|
||||
fn execute(&self, request: GrokBillingRequest) -> GrokBillingTransportFuture<'_> {
|
||||
self.record(request.headers());
|
||||
Box::pin(async {
|
||||
Ok(GrokBillingTransportResponse::new(
|
||||
br#"{"config":{"creditUsagePercent":25},"subscriptionTier":"SuperGrokPro"}"#,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
let store = MemoryProviderAccountStore::shared();
|
||||
seed_input(&store, &create_input("global_profile", "global-subject"))
|
||||
.await
|
||||
.unwrap();
|
||||
let repository = GrokCredentialRepository::new(store);
|
||||
let selected = |version: &str| {
|
||||
GrokClientProfileSelection {
|
||||
version_mode: VersionMode::Fixed,
|
||||
client_version: Some(version.into()),
|
||||
target_os: "windows".into(),
|
||||
target_arch: "arm64".into(),
|
||||
..Default::default()
|
||||
}
|
||||
.document()
|
||||
.unwrap()
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
selected("9.8.7"),
|
||||
)));
|
||||
let transport = Arc::new(RecordingTransport::default());
|
||||
let catalog = GrokCredentialCatalogService::new(
|
||||
repository.clone(),
|
||||
transport.clone(),
|
||||
Arc::new(MemoryGrokCatalogCache::default()),
|
||||
crate::support::xai_wire_profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
let quota = GrokCredentialQuotaService::new(
|
||||
repository,
|
||||
transport.clone(),
|
||||
crate::support::xai_wire_profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
for version in ["9.8.7", "9.8.8"] {
|
||||
*policy.0.lock().unwrap() = selected(version);
|
||||
catalog
|
||||
.refresh_account_catalog(&account_id("global_profile"))
|
||||
.await
|
||||
.unwrap();
|
||||
quota
|
||||
.refresh_account(&account_id("global_profile"))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut requests = transport.0.lock().unwrap();
|
||||
assert_eq!(requests.len(), 3);
|
||||
for headers in requests.drain(..) {
|
||||
let header = |name| headers.iter().find(|h| h.0 == name).unwrap().1.as_str();
|
||||
assert_eq!(
|
||||
header("user-agent"),
|
||||
format!("grok-shell/{version} (windows; aarch64)")
|
||||
);
|
||||
assert_eq!(header("x-grok-client-version"), version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueueCatalogTransport {
|
||||
calls: AtomicUsize,
|
||||
responses:
|
||||
|
||||
@@ -21,6 +21,80 @@ const DISCOVERY: &[u8] = include_bytes!("fixtures/discovery.json");
|
||||
const TOKEN_SUCCESS: &[u8] = include_bytes!("fixtures/token_success.json");
|
||||
const REFRESH_SUCCESS: &[u8] = include_bytes!("fixtures/refresh_success.json");
|
||||
|
||||
#[tokio::test]
|
||||
async fn oauth_discovery_exchange_and_refresh_use_current_global_identity() {
|
||||
use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode};
|
||||
let selected = |version: &str| {
|
||||
GrokClientProfileSelection {
|
||||
version_mode: VersionMode::Fixed,
|
||||
client_version: Some(version.to_owned()),
|
||||
target_os: "windows".into(),
|
||||
target_arch: "arm64".into(),
|
||||
..Default::default()
|
||||
}
|
||||
.document()
|
||||
.unwrap()
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
selected("9.8.7"),
|
||||
)));
|
||||
let transport = Arc::new(FixtureTransport::new(vec![
|
||||
response(200, DISCOVERY),
|
||||
response(200, TOKEN_SUCCESS),
|
||||
response(200, REFRESH_SUCCESS),
|
||||
]));
|
||||
let client = GrokOAuthClient::new(
|
||||
config(),
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FixtureVerifier),
|
||||
policy.clone(),
|
||||
);
|
||||
let discovery = client.discover().await.unwrap();
|
||||
let allowlist =
|
||||
RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"]).unwrap();
|
||||
let pending = client
|
||||
.start_authorization_code(
|
||||
&discovery,
|
||||
allowlist
|
||||
.authorize("https://gateway.example/oauth/grok/callback")
|
||||
.unwrap(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let state = state_from_authorization_url(&pending);
|
||||
let grant = pending
|
||||
.accept_callback(
|
||||
AuthorizationCallback::parse(&format!("code=fixture-code&state={state}")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
client
|
||||
.exchange_authorization_code(&discovery, grant)
|
||||
.await
|
||||
.unwrap();
|
||||
*policy.0.lock().unwrap() = selected("9.8.8");
|
||||
let grant = RefreshTokenGrant::new(SecretValue::new("refresh-test"));
|
||||
client.refresh(&discovery, &grant).await.unwrap();
|
||||
for (request, version) in transport.requests().iter().zip(["9.8.7", "9.8.7", "9.8.8"]) {
|
||||
let header = |name| {
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.name() == name)
|
||||
.unwrap()
|
||||
.value()
|
||||
};
|
||||
assert_eq!(
|
||||
header("user-agent"),
|
||||
format!("grok-shell/{version} (windows; aarch64)")
|
||||
);
|
||||
assert_eq!(header("x-grok-client-version"), version);
|
||||
}
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default());
|
||||
assert!(client.refresh(&discovery, &grant).await.is_err());
|
||||
assert_eq!(transport.requests().len(), 3);
|
||||
}
|
||||
|
||||
struct FixtureTransport {
|
||||
responses: Mutex<VecDeque<Result<OAuthHttpResponse, TransportFailure>>>,
|
||||
requests: Mutex<Vec<OAuthHttpRequest>>,
|
||||
@@ -92,6 +166,7 @@ async fn credential_import_should_require_exact_metadata_and_official_userinfo()
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let now = chrono::Utc::now();
|
||||
@@ -157,6 +232,7 @@ async fn expired_import_should_refresh_then_require_authoritative_userinfo() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let now = chrono::Utc::now();
|
||||
@@ -203,6 +279,7 @@ async fn credential_import_should_reject_non_official_client_before_verification
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let now = chrono::Utc::now();
|
||||
@@ -260,6 +337,7 @@ async fn authorization_code_flow_should_verify_before_returning_tokens() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let allowlist = RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"])
|
||||
@@ -305,6 +383,7 @@ async fn authorization_code_flow_should_fail_closed_without_verifier() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let allowlist = RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"])
|
||||
@@ -344,6 +423,7 @@ async fn refresh_should_preserve_ambiguous_send_classification() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let grant = RefreshTokenGrant::new(SecretValue::new(
|
||||
@@ -369,6 +449,7 @@ async fn refresh_should_return_rotated_token_without_id_token() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let grant = RefreshTokenGrant::new(SecretValue::new(
|
||||
|
||||
@@ -66,6 +66,7 @@ async fn expired_access_token_requires_official_refresh_before_identity_verifica
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("official discovery fixture");
|
||||
let error = client
|
||||
@@ -125,6 +126,7 @@ async fn verified_import_inside_refresh_margin_should_not_persist_a_refresh_sche
|
||||
crate::support::xai_wire_profile(),
|
||||
Arc::new(DiscoveryTransport),
|
||||
Arc::new(AcceptingUserInfoVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("official discovery fixture");
|
||||
let tokens = client
|
||||
@@ -351,6 +353,7 @@ async fn verify(candidate: GrokOAuthImportCandidate) -> GrokOAuthImportError {
|
||||
crate::support::xai_wire_profile(),
|
||||
Arc::new(DiscoveryTransport),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("official discovery fixture");
|
||||
client
|
||||
|
||||
@@ -23,6 +23,53 @@ use crate::support::loopback_endpoint_policy;
|
||||
|
||||
const CACHE_TTL: Duration = Duration::from_secs(60 * 60);
|
||||
|
||||
#[tokio::test]
|
||||
async fn jwks_and_userinfo_use_the_frozen_oauth_identity() {
|
||||
let server = MockServer::start().await;
|
||||
let endpoint = endpoints(&server);
|
||||
let key = TestKey::new(37, "global-profile-key");
|
||||
mount_jwks(&server, key.jwks(), 1).await;
|
||||
Mock::given(path("/oauth2/userinfo"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"sub":"test-user"})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let verifier = verifier(&endpoint.origin, CACHE_TTL);
|
||||
let nonce = SecretValue::new("global-profile-nonce");
|
||||
let algorithms = vec!["ES256".into()];
|
||||
let access = SecretValue::new("test-access");
|
||||
let token = SecretValue::new(key.sign(&valid_claims(&nonce), Algorithm::ES256));
|
||||
let profile = provider_xai::XaiWireProfile {
|
||||
client_version: "9.8.7".into(),
|
||||
target_os: "windows".into(),
|
||||
target_arch: "arm64".into(),
|
||||
..Default::default()
|
||||
};
|
||||
verifier
|
||||
.verify(
|
||||
auth_context(&endpoint, &algorithms, &nonce).with_wire_profile(&profile),
|
||||
TokenCandidate::new(&access, Some(&token), None),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
verifier
|
||||
.verify(
|
||||
import_context(&endpoint, &algorithms).with_wire_profile(&profile),
|
||||
TokenCandidate::new(&access, None, Some(Duration::from_secs(60))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for request in requests {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
"grok-shell/9.8.7 (windows; aarch64)"
|
||||
);
|
||||
assert_eq!(request.headers["x-grok-client-version"], "9.8.7");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_jwks_cache_evicts_idle_exits_at_the_fixed_bound() {
|
||||
let origin = MockServer::start().await;
|
||||
|
||||
@@ -55,14 +55,25 @@ pub fn grok_catalog_service(
|
||||
transport: Arc<dyn GrokModelCatalogTransport>,
|
||||
cache: Arc<dyn GrokCredentialCatalogCache>,
|
||||
) -> GrokCredentialCatalogService {
|
||||
GrokCredentialCatalogService::new(repository, transport, cache, xai_wire_profile())
|
||||
GrokCredentialCatalogService::new(
|
||||
repository,
|
||||
transport,
|
||||
cache,
|
||||
xai_wire_profile(),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn grok_quota_service(
|
||||
repository: GrokCredentialRepository,
|
||||
transport: Arc<dyn GrokBillingTransport>,
|
||||
) -> GrokCredentialQuotaService {
|
||||
GrokCredentialQuotaService::new(repository, transport, xai_wire_profile())
|
||||
GrokCredentialQuotaService::new(
|
||||
repository,
|
||||
transport,
|
||||
xai_wire_profile(),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -807,6 +818,28 @@ pub fn create_input(suffix: &str, subject: &str) -> CreateGrokCredential {
|
||||
|
||||
pub struct StaticRuntimePolicy;
|
||||
|
||||
pub struct RequestProfileRuntimePolicy(pub Mutex<gateway_core::account::OpaqueProviderData>);
|
||||
|
||||
impl ProviderRuntimePolicyPort for RequestProfileRuntimePolicy {
|
||||
fn load_request_profile<'a>(
|
||||
&'a self,
|
||||
provider: &'a ProviderKind,
|
||||
) -> futures::future::BoxFuture<
|
||||
'a,
|
||||
Result<Option<gateway_core::account::OpaqueProviderData>, ProviderStoreError>,
|
||||
> {
|
||||
assert_eq!(provider.as_str(), "xai");
|
||||
let profile = self.0.lock().unwrap().clone();
|
||||
Box::pin(async move { Ok(Some(profile)) })
|
||||
}
|
||||
|
||||
fn load_refresh_policy(
|
||||
&self,
|
||||
) -> futures::future::BoxFuture<'_, Result<ProviderRefreshPolicy, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(refresh_policy()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TestSessionAffinity {
|
||||
pub bindings: Mutex<
|
||||
|
||||
@@ -208,6 +208,7 @@ async fn inference_and_oauth_connect_through_each_accounts_authenticated_proxy()
|
||||
crate::support::xai_wire_profile(),
|
||||
Arc::new(ReqwestOAuthTransport::new(Arc::new(OfficialGrokEndpointPolicy)).unwrap()),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
.with_outbound_proxy(Some(proxy));
|
||||
assert!(
|
||||
@@ -1277,6 +1278,7 @@ async fn official_oauth_transport_should_resolve_through_the_production_policy_w
|
||||
.expect("production OAuth transport"),
|
||||
),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
|
||||
let discovery = client
|
||||
|
||||
+22
-6
@@ -2424,7 +2424,7 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
JSON 路径支持 `$`、`.成员`、`["带特殊字符的键"]`、`[索引]`、`.*` 和 `[*]`,不支持递归和过滤表达式。
|
||||
缺少字段视为未命中;类型不符属于执行失败。`regex_replace` 替换字符串,`set_value` 保持原字段类型设置 JSON 值,
|
||||
`rename_key` 替换所选对象的直接键名,重名时失败;`remove_field` 删除所选字段或数组项,不能删除作用范围根节点。
|
||||
`anonymize_workspace` 仅用于 `turn_metadata` 的 `$.workspaces`,`pattern` 必须为 `null`,按逻辑会话改写工程路径并删除 Git 远端与提交 metadata
|
||||
`anonymize_project` 仅用于 `turn_metadata` 的 `$.workspaces`,`pattern` 必须为 `null`,按账号与逻辑会话改写项目名,保留父目录、用户名及映射内的 metadata
|
||||
删除动作的 `pattern: null` 表示无条件删除,字符串模式表示只删除字符串值匹配的字段或数组项。
|
||||
请求头规则生成的值必须是 ASCII 文本,以保持 HTTP 与 WebSocket opening 的一致性;metadata 范围会自动转义 Unicode
|
||||
|
||||
@@ -2446,11 +2446,20 @@ WebSocket 请求头在握手时发送。隐私规则改变握手头时,普通
|
||||
UA、平台参数及自动 Git 上下文版本由 [OpenAI 上游客户端身份](#openai-上游客户端身份)管理。
|
||||
保存后的规则按其 `steps` 执行,不随预设定义变化
|
||||
|
||||
「按账号与会话匿名化工作区」预设使用 `anonymize_workspace`,保留路径分隔符与父目录层级,将用户目录中的用户名改为 `user`。
|
||||
「按账号与会话匿名化工作区」预设按顺序生成四个可编辑步骤:
|
||||
|
||||
1. `anonymize_project` 根据原始路径生成项目化名,保留分隔符与父目录
|
||||
2. `rename_key` 将 Linux、macOS 和 Windows 用户目录中的用户名改为 `user`,替换内容可自定义
|
||||
3. `remove_field` 删除 `$.workspaces.*.associated_remote_urls`
|
||||
4. `remove_field` 删除 `$.workspaces.*.latest_git_commit_hash`
|
||||
|
||||
各步骤可以修改、删除或调整顺序;用户名替换与 Git 信息处理不由项目匿名化动作隐式执行。
|
||||
工程名取原名的前 48 个字母或数字打乱顺序,再加两组 1~1000 的数字和短后缀;没有字母或数字时使用 `project`。
|
||||
例如 `codex-proxy-rs` 可变为 `xrpceodxroys-427-83-a1b2c3d4`。同一 Client Key、账号、逻辑会话和工作区的化名在重试与重启后保持一致;
|
||||
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
|
||||
映射内的 `associated_remote_urls`、`latest_git_commit_hash` 被移除,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
|
||||
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
|
||||
|
||||
已保存的 `anonymize_workspace` 组合动作继续替换用户名、生成项目化名并删除 Git 信息。管理端编辑时将其展开为四个独立步骤,应用草稿并保存后生效;展开后的步骤仍计入总上限
|
||||
|
||||
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
|
||||
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
|
||||
@@ -2669,6 +2678,10 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI
|
||||
更新时省略某项保留原值,对象替换该项,`null` 删除显式选择并使用 Provider 默认值;不清除其他 Provider 的配置。
|
||||
配置内容由对应 Provider 校验,不包含账号凭据。Key 可通过 `providerRequestProfileOverrides` 整体覆盖所属 Provider 的选择
|
||||
|
||||
OpenAI、xAI、Antigravity 的模型请求均按 Key 覆盖优先、其次全局的顺序选择身份。
|
||||
OAuth、令牌续期、额度刷新、订阅和模型目录查询等账号后台操作使用所属平台的全局身份,
|
||||
不读取单个 Key 的覆盖;修改全局配置后,下次执行采用新选择
|
||||
|
||||
各 Provider 的选项响应均包含 `globalConfiguration`。OpenAI 返回六个 `presets`、`maxVersionLag` 和
|
||||
`recognizedUserAgentPrefixes`。匹配前缀时,OpenAI 从 UA 派生 originator 与 Core 版本,其他自定义 UA 需要提供这两个字段。
|
||||
xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets`
|
||||
@@ -2676,9 +2689,9 @@ xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets`
|
||||
### OpenAI 上游客户端身份
|
||||
|
||||
OpenAI 通用身份默认使用 `MacOS · Desktop · 自动最新`。
|
||||
该配置作用于 Client Key 的 OpenAI 模型请求,适用于 HTTP/SSE、WebSocket、Images 和 Search,
|
||||
也用于账号模型目录的后台发现、手动刷新、导出及定时预热;下次执行时采用当前全局选择,不使用单个 Key 的覆盖。
|
||||
不改变 xAI、入站客户端版本门禁、账号认证或后台 Desktop 专属操作
|
||||
模型请求覆盖 HTTP/SSE、WebSocket、Images 和 Search。后台全局身份还作用于授权链接的客户端参数、
|
||||
PAT 验证、额度重置卡、资料、头像和定时预热;各端点保留各自的请求头格式。
|
||||
该配置不覆盖浏览器授权页的 UA,不保证上游登录通知中的设备标签与之相同,也不改变入站客户端版本门禁
|
||||
|
||||
自定义配置使用 `{ "mode": "custom", "userAgent": "完整 UA" }`。
|
||||
已识别的 `Codex Desktop`、`codex-tui`、`codex_exec`、`codex_cli_rs` 前缀由后端解析 `originator` 和 Core `version`,
|
||||
@@ -2707,6 +2720,9 @@ TUI 默认标识为 `codex-tui`,Exec 为 `codex_exec`,入口后缀使用同
|
||||
`originator` 覆盖只更改产品名前缀和配套头,后缀仍表示所选入口。省略 `osType` 使用平台名称;
|
||||
自定义运行环境在自动更新时保持不变。未指定 `cliEntry` 时使用 `codex_cli_rs` 默认值且不添加入口后缀
|
||||
|
||||
macOS 的默认系统版本为 `27.2.1`。选择 macOS CLI 预设时,配置包含 `cliEntry: "tui"` 和
|
||||
`terminal: "Apple_Terminal/488.9"`;已保存的入口和终端配置不随预设变化而改写
|
||||
|
||||
`terminal` 填写官方客户端的真实终端标记,如 `iTerm.app/3.5.0`、`vscode/1.99.0`、`Apple_Terminal`、
|
||||
`Ghostty`、`WindowsTerminal`、`tmux-256color`、`xterm-256color`。省略时使用 `unknown`:
|
||||
官方 Desktop 由 GUI 启动、无终端环境变量,其 UA 中的终端标记本就是 `unknown`,
|
||||
|
||||
@@ -1069,6 +1069,9 @@ OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再
|
||||
credential 与 quota 是两组独立事实:credential refresh 不等于 quota refresh,额度接口的 401/403
|
||||
也不能单独证明 refresh token 永久失效
|
||||
|
||||
OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过自身 profile 解析器读取当前全局身份,
|
||||
冻结到对应上游请求,不读取 Key 覆盖;模型请求由请求上下文按 Key 覆盖优先、其次全局解析身份
|
||||
|
||||
- OpenAI 支持 OAuth、AT/RT、PAT 和上游 API Key。OAuth 身份来自官方 JWT claims,PAT 经官方身份接口验证,
|
||||
不信任导入文档顶层身份字段。RT-only 导入先换取 AT;AT-only、PAT 与 API Key 不参加 OAuth 自动续期。
|
||||
输入形态和适用操作见 [账号能力与导入](api.md#账号能力导入与-oauth)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@boxicons/vue": "1.0.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lucide/vue": "^1.77.0",
|
||||
|
||||
Generated
+6
-6
@@ -195,8 +195,8 @@ importers:
|
||||
specifier: 1.0.1
|
||||
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
||||
'@codex-proxy/ui':
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.1
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.2
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
@@ -456,9 +456,9 @@ packages:
|
||||
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
||||
engines: {node: '>= 20.12.0'}
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee':
|
||||
resolution: {gitHosted: true, integrity: sha512-pPner6XWo+saTWErInK+LLSUxbSmTtd274hrWorFnOfLqDNN2cTwl1UwDsPvaRShl7jy4dVxPC5vDWAgszwdZQ==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee}
|
||||
version: 0.13.1
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450':
|
||||
resolution: {gitHosted: true, integrity: sha512-/lXIKZtNWb+WYmu6ImkuCpqwba7denlWbmGY5kjIrT/CpH00LOn438uIfI9Ow21FBTbt3yZrYqOBcrbQK2lXzA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450}
|
||||
version: 0.13.2
|
||||
engines: {node: '>=24'}
|
||||
peerDependencies:
|
||||
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
@@ -3590,7 +3590,7 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
dependencies:
|
||||
'@ant-design/colors': 8.0.1
|
||||
'@ant-design/fast-color': 3.0.1
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { RequestOptions } from '../../request'
|
||||
import request from '../../request'
|
||||
|
||||
export type PrivacyScope = 'turn_metadata' | 'desktop_git_context' | 'environment_text' | 'request_body' | 'request_header'
|
||||
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_workspace'
|
||||
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project' | 'anonymize_workspace'
|
||||
export type JsonValue = unknown
|
||||
|
||||
export interface PrivacyRule {
|
||||
|
||||
@@ -1,40 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
|
||||
import { LayoutGrid } from '@lucide/vue'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
|
||||
defineProps<{ disabled?: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const provider = defineModel<string>({ required: true })
|
||||
const options = computed(() => ([
|
||||
{
|
||||
label: t('common.providers.all'),
|
||||
value: '',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
...PROVIDER_IDS.map(value => ({
|
||||
label: formatProviderLabel(value),
|
||||
value,
|
||||
icon: providerIcon(value),
|
||||
})),
|
||||
]))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-w-0 max-w-full items-center gap-1">
|
||||
<div class="min-w-0 overflow-x-auto">
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-model="provider"
|
||||
:aria-label="t('common.providers.filter')"
|
||||
display="icon"
|
||||
:style="{ width: `${options.length * 40 + 4}px` }"
|
||||
:options="options"
|
||||
:leading-option="{ label: t('common.providers.all'), value: '', icon: LayoutGrid }"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<script setup lang="ts" generic="Value extends string">
|
||||
import type { SegmentedOption } from '@codex-proxy/ui'
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
providers?: readonly Value[]
|
||||
leadingOption?: SegmentedOption
|
||||
display?: 'icon' | 'label'
|
||||
size?: 'small' | 'default' | 'large'
|
||||
disabled?: boolean
|
||||
ariaLabel?: string
|
||||
}>(), {
|
||||
display: 'icon',
|
||||
disabled: false,
|
||||
})
|
||||
const provider = defineModel<Value>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const options = computed(() => [
|
||||
...(props.leadingOption
|
||||
? [props.leadingOption]
|
||||
: []),
|
||||
...(props.providers ?? PROVIDER_IDS).map(value => ({
|
||||
value,
|
||||
label: formatProviderLabel(value),
|
||||
icon: providerIcon(value),
|
||||
})),
|
||||
])
|
||||
const style = computed(() => props.display === 'icon'
|
||||
? { width: `${options.value.length * 40 + 4}px` }
|
||||
: undefined)
|
||||
|
||||
function selectProvider(value: string) {
|
||||
if (options.value.some(option => option.value === value))
|
||||
provider.value = value as Value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZSegmented
|
||||
:model-value="provider"
|
||||
:options="options"
|
||||
:display="display"
|
||||
:size="size"
|
||||
:disabled="disabled"
|
||||
:aria-label="ariaLabel ?? t('common.providers.select')"
|
||||
:style="style"
|
||||
@update:model-value="selectProvider"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
|
||||
defineProps<{ disabled?: boolean }>()
|
||||
const provider = defineModel<BuiltinProvider>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="grid min-w-0 gap-4" :aria-label="t('common.providers.settings')">
|
||||
<div class="flex justify-end">
|
||||
<ProviderSelect
|
||||
v-model="provider"
|
||||
:disabled="disabled"
|
||||
class="shrink-0"
|
||||
/>
|
||||
</div>
|
||||
<slot />
|
||||
</section>
|
||||
</template>
|
||||
@@ -2,12 +2,12 @@
|
||||
import type { Component } from 'vue'
|
||||
import type { ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates } from '@/api'
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { isEqual } from 'es-toolkit'
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import AntigravityRequestProfileEditor from '@/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import { PROVIDER_IDS } from '@/providers/catalog'
|
||||
import OpenAiRequestProfileEditor from '@/providers/openai/request-profile/OpenAiRequestProfileEditor.vue'
|
||||
import XaiRequestProfileEditor from '@/providers/xai/request-profile/XaiRequestProfileEditor.vue'
|
||||
|
||||
@@ -37,12 +37,6 @@ const model = defineModel<ProviderRequestProfiles>({
|
||||
const updates = defineModel<ProviderRequestProfileUpdates>('updates')
|
||||
const selectedProvider = shallowRef<BuiltinProvider>(PROVIDER_IDS[0]!)
|
||||
const provider = computed(() => props.provider ?? selectedProvider.value)
|
||||
const providerOptions = PROVIDER_IDS.map(value => ({
|
||||
value,
|
||||
label: formatProviderLabel(value),
|
||||
icon: providerIcon(value),
|
||||
}))
|
||||
const providerSelectorStyle = { width: `${providerOptions.length * 40}px` }
|
||||
const drafts = shallowRef<ProviderRequestProfiles>({})
|
||||
const profile = computed<ProviderRequestProfile | null | undefined>({
|
||||
get: () => {
|
||||
@@ -84,15 +78,12 @@ watch(() => props.active, (active) => {
|
||||
|
||||
<template>
|
||||
<div class="grid min-w-0 gap-4">
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-if="!allowInherit && !props.provider"
|
||||
v-model="selectedProvider"
|
||||
class="max-w-full justify-self-end"
|
||||
:aria-label="t('settings.clientProfile.clientIdentityProvider')"
|
||||
:options="providerOptions"
|
||||
:disabled="disabled"
|
||||
:style="providerSelectorStyle"
|
||||
display="icon"
|
||||
/>
|
||||
<component
|
||||
:is="editors[provider]"
|
||||
@@ -104,15 +95,12 @@ watch(() => props.active, (active) => {
|
||||
:disabled="disabled"
|
||||
>
|
||||
<template #source-extra>
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-if="!props.provider"
|
||||
v-model="selectedProvider"
|
||||
class="max-w-full shrink-0"
|
||||
:aria-label="t('settings.clientProfile.upstreamIdentityPlatform')"
|
||||
:options="providerOptions"
|
||||
:disabled="disabled"
|
||||
:style="providerSelectorStyle"
|
||||
display="icon"
|
||||
/>
|
||||
</template>
|
||||
</component>
|
||||
|
||||
@@ -70,7 +70,9 @@
|
||||
"filter": "Filter by platform",
|
||||
"unknown": "Unknown platform",
|
||||
"customAuth": "Custom authentication · {normalized}",
|
||||
"unknownAuth": "Unknown authentication type"
|
||||
"unknownAuth": "Unknown authentication type",
|
||||
"settings": "Platform settings",
|
||||
"select": "Select platform"
|
||||
},
|
||||
"location": {
|
||||
"resolving": "Resolving exit location",
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"subagents": "Collaborative subagents",
|
||||
"memberModels": "Member account models",
|
||||
"fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.",
|
||||
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent."
|
||||
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent.",
|
||||
"noProviderSettings": "No group-specific settings for this platform"
|
||||
},
|
||||
"metrics": {
|
||||
"restricted": "Restricted",
|
||||
|
||||
@@ -592,8 +592,7 @@
|
||||
"fieldPath": "Field path",
|
||||
"fieldPathSyntax": "Field path syntax",
|
||||
"jsonPathHelp": "Supports object members, quoted keys, array indexes, and * wildcards, for example $[\"workspaces\"][\"/home/alex/demo\"]",
|
||||
"sessionAliasEffect": "Stable per account and session; Git metadata removed",
|
||||
"anonymizeWorkspaceHelp": "Shuffle the project name and add numbers; rotate aliases for new accounts or sessions, remove Git metadata, and preserve execution paths",
|
||||
"sessionAliasEffect": "Stable project alias per account and session",
|
||||
"targetHelp": "Use $ for environment text and a header name for request headers",
|
||||
"commonFields": "Common fields",
|
||||
"deleteMatchHelp": "Remove only fields or array items whose values match the regular expression",
|
||||
@@ -647,6 +646,7 @@
|
||||
"gitCommitId": "Git commit ID",
|
||||
"gitRemoteCollection": "Git remote collection",
|
||||
"workspaceFingerprint": "Workspace fingerprint",
|
||||
"anonymizeProject": "Anonymize project name by account and session",
|
||||
"anonymizeWorkspace": "Anonymize workspace by account and session",
|
||||
"unifyWorkspaceInformation": "Unify workspace information"
|
||||
},
|
||||
|
||||
@@ -70,7 +70,9 @@
|
||||
"filter": "按平台筛选",
|
||||
"unknown": "未知平台",
|
||||
"customAuth": "自定义认证 · {normalized}",
|
||||
"unknownAuth": "未知认证类型"
|
||||
"unknownAuth": "未知认证类型",
|
||||
"settings": "平台设置",
|
||||
"select": "选择平台"
|
||||
},
|
||||
"location": {
|
||||
"resolving": "正在解析出口位置",
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"subagents": "协作子代理",
|
||||
"memberModels": "成员账号模型",
|
||||
"fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择",
|
||||
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求"
|
||||
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求",
|
||||
"noProviderSettings": "该平台暂无分组专属设置"
|
||||
},
|
||||
"metrics": {
|
||||
"restricted": "受限",
|
||||
|
||||
@@ -592,8 +592,7 @@
|
||||
"fieldPath": "字段路径",
|
||||
"fieldPathSyntax": "字段路径语法",
|
||||
"jsonPathHelp": "支持对象成员、双引号键名、数组索引和 * 通配,例如 $[\"workspaces\"][\"/home/alex/demo\"]",
|
||||
"sessionAliasEffect": "同账号同会话化名固定,移除 Git 信息",
|
||||
"anonymizeWorkspaceHelp": "打乱工程名并加数字,换账号或新会话时更换化名;移除 Git 信息,保留真实执行路径",
|
||||
"sessionAliasEffect": "同账号同会话项目化名固定",
|
||||
"targetHelp": "环境文本使用 $,请求头直接填写名称",
|
||||
"commonFields": "常用字段",
|
||||
"deleteMatchHelp": "仅删除值匹配正则的字段或数组项",
|
||||
@@ -647,6 +646,7 @@
|
||||
"gitCommitId": "Git 提交 ID",
|
||||
"gitRemoteCollection": "Git 远端集合",
|
||||
"workspaceFingerprint": "工作区指纹",
|
||||
"anonymizeProject": "按账号与会话匿名化项目名",
|
||||
"anonymizeWorkspace": "按账号与会话匿名化工作区",
|
||||
"unifyWorkspaceInformation": "统一工作区信息"
|
||||
},
|
||||
|
||||
@@ -70,7 +70,9 @@
|
||||
"filter": "按平臺篩選",
|
||||
"unknown": "未知平臺",
|
||||
"customAuth": "自定義認證 · {normalized}",
|
||||
"unknownAuth": "未知認證類型"
|
||||
"unknownAuth": "未知認證類型",
|
||||
"settings": "平台設定",
|
||||
"select": "選擇平台"
|
||||
},
|
||||
"location": {
|
||||
"resolving": "正在解析出口位置",
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"subagents": "協作子代理",
|
||||
"memberModels": "成員帳號模型",
|
||||
"fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇",
|
||||
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求"
|
||||
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求",
|
||||
"noProviderSettings": "此平台暫無分組專屬設定"
|
||||
},
|
||||
"metrics": {
|
||||
"restricted": "受限",
|
||||
|
||||
@@ -592,8 +592,7 @@
|
||||
"fieldPath": "字段路徑",
|
||||
"fieldPathSyntax": "字段路徑語法",
|
||||
"jsonPathHelp": "支持對象成員、雙引號鍵名、數組索引和 * 通配,例如 $[\"workspaces\"][\"/home/alex/demo\"]",
|
||||
"sessionAliasEffect": "同賬號同會話化名固定,移除 Git 資訊",
|
||||
"anonymizeWorkspaceHelp": "打亂工程名並加數字,換賬號或新會話時更換化名;移除 Git 資訊,保留真實執行路徑",
|
||||
"sessionAliasEffect": "同賬號同會話專案化名固定",
|
||||
"targetHelp": "環境文本使用 $,請求頭直接填寫名稱",
|
||||
"commonFields": "常用字段",
|
||||
"deleteMatchHelp": "僅刪除值匹配正則的字段或數組項",
|
||||
@@ -647,6 +646,7 @@
|
||||
"gitCommitId": "Git 提交 ID",
|
||||
"gitRemoteCollection": "Git 遠端集合",
|
||||
"workspaceFingerprint": "工作區指紋",
|
||||
"anonymizeProject": "按賬號與會話匿名化專案名稱",
|
||||
"anonymizeWorkspace": "按賬號與會話匿名化工作區",
|
||||
"unifyWorkspaceInformation": "統一工作區信息"
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Fingerprint, Plug } from '@lucide/vue'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
const providers = {
|
||||
openai: { label: 'Codex', icon: Openai },
|
||||
openai: { label: 'OpenAI', icon: Openai },
|
||||
xai: { label: 'xAI', icon: Xai },
|
||||
antigravity: { label: 'Antigravity', icon: GoogleAntigravity },
|
||||
} as const
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ZFormItem, ZIconButton, ZInput } from '@codex-proxy/ui'
|
||||
import { Dices } from '@lucide/vue'
|
||||
import { useTemplateRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
import { generateRequestId as generateUuid } from '@/utils/operation'
|
||||
@@ -8,6 +9,10 @@ import { generateRequestId as generateUuid } from '@/utils/operation'
|
||||
defineProps<{ disabled: boolean, placeholder: string, error: string }>()
|
||||
const seed = defineModel<string>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const input = useTemplateRef<InstanceType<typeof ZInput>>('input')
|
||||
defineExpose({
|
||||
focus: () => input.value?.focus(),
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -26,6 +31,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
</ZIconButton>
|
||||
</template>
|
||||
<ZInput
|
||||
ref="input"
|
||||
v-model="seed"
|
||||
:aria-label="t('settings.clientProfile.installationSeed')"
|
||||
:aria-invalid="!!error"
|
||||
|
||||
+8
-19
@@ -1,52 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountCreateSource } from '../../utils/accountCreate'
|
||||
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { LayoutGrid } from '@lucide/vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import { isBuiltinProvider } from '@/providers/catalog'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const source = defineModel<AccountCreateSource | null>({ required: true })
|
||||
const options = computed(() => ([
|
||||
{
|
||||
value: 'bundle',
|
||||
label: t('accounts.onboarding.batchImport'),
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
...PROVIDER_IDS.map(provider => ({
|
||||
value: `provider:${provider}`,
|
||||
label: formatProviderLabel(provider),
|
||||
icon: providerIcon(provider),
|
||||
})),
|
||||
]))
|
||||
const selected = computed({
|
||||
get: () => source.value?.kind === 'provider'
|
||||
? `provider:${source.value.id}`
|
||||
? source.value.id
|
||||
: source.value?.kind ?? '',
|
||||
set: (value: string) => {
|
||||
if (!options.value.some(option => option.value === value))
|
||||
if (value !== 'bundle' && !isBuiltinProvider(value))
|
||||
return
|
||||
source.value = value === 'bundle'
|
||||
? { kind: 'bundle' }
|
||||
: {
|
||||
kind: 'provider',
|
||||
id: value.slice('provider:'.length),
|
||||
id: value,
|
||||
}
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-model="selected"
|
||||
class="w-full"
|
||||
:aria-label="t('accounts.onboarding.selectAccountPlatform')"
|
||||
:options="options"
|
||||
:leading-option="{ value: 'bundle', label: t('accounts.onboarding.batchImport'), icon: LayoutGrid }"
|
||||
display="label"
|
||||
:disabled="disabled"
|
||||
size="large"
|
||||
/>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import type { DashboardWireProfile } from '@/api'
|
||||
import { ZCard, ZEmpty, ZSegmented } from '@codex-proxy/ui'
|
||||
import { ZCard, ZEmpty } from '@codex-proxy/ui'
|
||||
|
||||
import { Box, CheckCircle2, Monitor, RefreshCw, ShieldCheck, Terminal, TriangleAlert } from '@lucide/vue'
|
||||
|
||||
import { computed, shallowRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import { PROVIDER_IDS } from '@/providers/catalog'
|
||||
import { describeWireProfile } from './identity'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -17,22 +18,17 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const selectedProvider = shallowRef('')
|
||||
|
||||
const providerOptions = computed(() => {
|
||||
const providers = new Set([
|
||||
const providers = computed(() => [
|
||||
...new Set([
|
||||
...PROVIDER_IDS,
|
||||
...props.profiles.map(profile => profile.provider),
|
||||
])
|
||||
return Array.from(providers, value => ({
|
||||
label: formatProviderLabel(value),
|
||||
value,
|
||||
icon: providerIcon(value),
|
||||
}))
|
||||
})
|
||||
]),
|
||||
])
|
||||
|
||||
const activeProvider = computed({
|
||||
get: () => providerOptions.value.some(option => option.value === selectedProvider.value)
|
||||
get: () => providers.value.includes(selectedProvider.value)
|
||||
? selectedProvider.value
|
||||
: providerOptions.value[0]?.value ?? '',
|
||||
: providers.value[0] ?? '',
|
||||
set: (value: string) => { selectedProvider.value = value },
|
||||
})
|
||||
|
||||
@@ -148,13 +144,11 @@ const runtimeEnvironment = computed(() => {
|
||||
<h2 class="m-0 pt-0.5 text-xl leading-[1.15] font-heavy text-z-text text-balance">
|
||||
{{ t('dashboard.clientIdentity.title') }}
|
||||
</h2>
|
||||
<div v-if="providerOptions.length > 1" class="min-w-0 max-w-full overflow-x-auto">
|
||||
<ZSegmented
|
||||
<div v-if="providers.length > 1" class="min-w-0 max-w-full overflow-x-auto">
|
||||
<ProviderSelect
|
||||
v-model="activeProvider"
|
||||
:aria-label="t('dashboard.clientIdentity.provider')"
|
||||
:options="providerOptions"
|
||||
:style="{ width: `${providerOptions.length * 40 + 4}px` }"
|
||||
display="icon"
|
||||
:providers="providers"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,13 +3,15 @@ import type { FormRules } from '@codex-proxy/ui'
|
||||
import type { AccountGroupFormValue } from '../composables/useAccountGroups'
|
||||
|
||||
import type { AccountGroup } from '@/api'
|
||||
import { normalizeRgbaHexColor, ZButton, ZColorPicker, ZDialog, ZForm, ZFormItem, ZInput, ZSegmented, ZTextarea } from '@codex-proxy/ui'
|
||||
import { computed, useTemplateRef, watch } from 'vue'
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { normalizeRgbaHexColor, ZButton, ZColorPicker, ZDialog, ZEmpty, ZForm, ZFormItem, ZInput, ZSegmented, ZTextarea } from '@codex-proxy/ui'
|
||||
import { computed, shallowRef, useTemplateRef, watch } from 'vue'
|
||||
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountModelAccessField from '@/components/account-model-access-field/index.vue'
|
||||
import { accountModelAccessError } from '@/components/account-model-access-field/validation'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
import ProviderSettingsSection from '@/components/ProviderSettingsSection.vue'
|
||||
import { ACCOUNT_GROUP_COLOR_PRESETS } from '../constants'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -25,6 +27,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const open = defineModel<boolean>({ required: true })
|
||||
const form = defineModel<AccountGroupFormValue>('form', { required: true })
|
||||
const provider = shallowRef<BuiltinProvider>('openai')
|
||||
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
|
||||
const rules = computed<FormRules<AccountGroupFormValue>>(() => ({
|
||||
name: {
|
||||
@@ -48,7 +51,11 @@ const rules = computed<FormRules<AccountGroupFormValue>>(() => ({
|
||||
message: t('groups.actions.selectValidGroupingColor'),
|
||||
},
|
||||
}))
|
||||
watch(open, () => formRef.value?.clearValidate())
|
||||
watch(open, (visible) => {
|
||||
formRef.value?.clearValidate()
|
||||
if (visible)
|
||||
provider.value = 'openai'
|
||||
})
|
||||
|
||||
async function requestSave() {
|
||||
if (props.saving || !await formRef.value?.validate().catch(() => false))
|
||||
@@ -99,9 +106,31 @@ const description = computed(() => props.group
|
||||
:disabled="saving"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<div class="col-span-full grid grid-cols-2 items-start gap-x-6 gap-y-4.5 sm:grid-cols-subgrid **:[[role=radio]]:px-3.5 md:**:[[role=radio]]:px-4.5">
|
||||
<div class="contents sm:flex sm:min-w-0 sm:flex-wrap sm:items-start sm:gap-x-6 sm:gap-y-4.5">
|
||||
<ZFormItem :label="t('groups.editor.fastMode')" class="col-span-full sm:flex-auto">
|
||||
<ZFormItem :label="t('groups.editor.imageGeneration')" class="col-span-full">
|
||||
<ZSegmented
|
||||
:model-value="form.allowImageGeneration ? 'enabled' : 'disabled'"
|
||||
:aria-label="t('groups.editor.imageGeneration')"
|
||||
:options="toggleOptions"
|
||||
:disabled="saving"
|
||||
@update:model-value="form.allowImageGeneration = $event === 'enabled'"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<AccountModelAccessField
|
||||
class="col-span-full" :group-id="group?.id ?? null" :model-value="form.modelAccess" form-prop="modelAccess" :disabled="saving"
|
||||
@update:model-value="value => { if (value) form.modelAccess = value }"
|
||||
/>
|
||||
<ZFormItem :label="t('groups.editor.description')" class="col-span-full">
|
||||
<ZTextarea
|
||||
v-model="form.description"
|
||||
:aria-label="t('groups.editor.groupDescription')"
|
||||
:rows="2"
|
||||
:placeholder="t('groups.editor.describePurposeOfThisGroup')"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<ProviderSettingsSection v-model="provider" class="col-span-full" :disabled="saving">
|
||||
<div v-if="provider === 'openai'" class="flex flex-wrap items-start gap-x-6 gap-y-4.5">
|
||||
<ZFormItem :label="t('groups.editor.fastMode')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('groups.editor.fastMode')" :content="t('groups.editor.fastModeHelp')" />
|
||||
</template>
|
||||
@@ -117,42 +146,21 @@ const description = computed(() => props.group
|
||||
:disabled="saving"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<ZFormItem :label="t('groups.editor.imageGeneration')" class="sm:flex-auto">
|
||||
<ZFormItem :label="t('groups.editor.subagents')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('groups.editor.subagents')" :content="t('groups.editor.subagentsHelp')" />
|
||||
</template>
|
||||
<ZSegmented
|
||||
:model-value="form.allowImageGeneration ? 'enabled' : 'disabled'"
|
||||
:aria-label="t('groups.editor.imageGeneration')"
|
||||
:model-value="form.allowSubagents ? 'enabled' : 'disabled'"
|
||||
:aria-label="t('groups.editor.subagents')"
|
||||
:options="toggleOptions"
|
||||
:disabled="saving"
|
||||
@update:model-value="form.allowImageGeneration = $event === 'enabled'"
|
||||
@update:model-value="form.allowSubagents = $event === 'enabled'"
|
||||
/>
|
||||
</ZFormItem>
|
||||
</div>
|
||||
<ZFormItem :label="t('groups.editor.subagents')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('groups.editor.subagents')" :content="t('groups.editor.subagentsHelp')" />
|
||||
</template>
|
||||
<ZSegmented
|
||||
:model-value="form.allowSubagents ? 'enabled' : 'disabled'"
|
||||
:aria-label="t('groups.editor.subagents')"
|
||||
:options="toggleOptions"
|
||||
:disabled="saving"
|
||||
@update:model-value="form.allowSubagents = $event === 'enabled'"
|
||||
/>
|
||||
</ZFormItem>
|
||||
</div>
|
||||
<AccountModelAccessField
|
||||
class="col-span-full" :group-id="group?.id ?? null" :model-value="form.modelAccess" form-prop="modelAccess" :disabled="saving"
|
||||
@update:model-value="value => { if (value) form.modelAccess = value }"
|
||||
/>
|
||||
<ZFormItem :label="t('groups.editor.description')" class="col-span-full">
|
||||
<ZTextarea
|
||||
v-model="form.description"
|
||||
:aria-label="t('groups.editor.groupDescription')"
|
||||
:rows="2"
|
||||
:placeholder="t('groups.editor.describePurposeOfThisGroup')"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<ZEmpty v-else :title="t('groups.editor.noProviderSettings')" size="small" surface="none" />
|
||||
</ProviderSettingsSection>
|
||||
</ZForm>
|
||||
|
||||
<template #footer>
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import type { ApiKeyLimitField } from '../composables/useApiKeyFormRules'
|
||||
import type { AccountGroupRef, ApiKey, ApiKeyBatchChanges, ApiKeyPeerSharing, ProviderRequestProfileUpdates } from '@/api'
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { ZButton, ZConfirmDialog, ZDialog, ZForm, ZFormItem } from '@codex-proxy/ui'
|
||||
import { KeyRound } from '@lucide/vue'
|
||||
import { isEqual } from 'es-toolkit'
|
||||
import { computed, ref, useTemplateRef, watch } from 'vue'
|
||||
import { computed, nextTick, ref, shallowRef, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { batchUpdateApiKeys } from '@/api'
|
||||
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
|
||||
import ProviderSettingsSection from '@/components/ProviderSettingsSection.vue'
|
||||
import ProviderRequestProfilesEditor from '@/components/request-profile/index.vue'
|
||||
import { useAsyncAction } from '@/composables/useAsyncAction'
|
||||
import { notification as ZNotification } from '@/plugins/notification'
|
||||
@@ -29,6 +31,8 @@ const open = defineModel<boolean>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const { loading, run } = useAsyncAction()
|
||||
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
|
||||
const seedField = useTemplateRef<InstanceType<typeof InstallationSeedField>>('seedField')
|
||||
const provider = shallowRef<BuiltinProvider>('openai')
|
||||
const rules = useApiKeyLimitRules()
|
||||
const confirmAll = ref(false)
|
||||
function emptyForm() {
|
||||
@@ -146,10 +150,11 @@ const changes = computed<ApiKeyBatchChanges>(() => {
|
||||
}
|
||||
return patch
|
||||
})
|
||||
const canSave = computed(() => props.keys.length > 0 && Object.keys(changes.value).length > 0 && !invalidScope.value && !seedError.value)
|
||||
const canSave = computed(() => props.keys.length > 0 && Object.keys(changes.value).length > 0 && !invalidScope.value)
|
||||
|
||||
watch(open, (visible) => {
|
||||
if (visible) {
|
||||
provider.value = 'openai'
|
||||
form.value = emptyForm()
|
||||
touchedLimits.value.clear()
|
||||
for (const field of apiKeyLimitFields)
|
||||
@@ -158,7 +163,15 @@ watch(open, (visible) => {
|
||||
})
|
||||
|
||||
async function save() {
|
||||
if (!canSave.value || loading.value || !await formRef.value?.validate().catch(() => false))
|
||||
if (!canSave.value || loading.value)
|
||||
return
|
||||
if (seedError.value) {
|
||||
provider.value = 'openai'
|
||||
await nextTick()
|
||||
seedField.value?.focus()
|
||||
return
|
||||
}
|
||||
if (!await formRef.value?.validate().catch(() => false))
|
||||
return
|
||||
if (form.value.groupIds?.length === 0) {
|
||||
confirmAll.value = true
|
||||
@@ -201,17 +214,17 @@ async function applyChanges() {
|
||||
|
||||
<ApiKeyPeerSharingField :sharing="sharing" :disabled="loading" @change="updateSharing" />
|
||||
|
||||
<div class="grid gap-4">
|
||||
<ZFormItem :label="t('keys.editor.upstreamIdentity')">
|
||||
<ProviderRequestProfilesEditor v-model:updates="form.profiles" :initial-profiles="initialProfiles" allow-inherit :active="open" :disabled="loading" />
|
||||
</ZFormItem>
|
||||
<InstallationSeedField v-model="form.installationSeed" :disabled="loading" :error="seedError" :placeholder="hasExistingSeed ? t('accounts.modelAccess.reserve') : t('settings.clientProfile.installationSeedPlaceholder')" />
|
||||
</div>
|
||||
<ApiKeyLimitFields
|
||||
v-model:daily-limit-usd="form.dailyLimitUsd" v-model:weekly-limit-usd="form.weeklyLimitUsd"
|
||||
v-model:max-concurrency="form.maxConcurrency" v-model:requests-per-minute="form.requestsPerMinute"
|
||||
:mixed="mixedLimits" :disabled="loading" @edit="touchedLimits.add($event)"
|
||||
/>
|
||||
<ProviderSettingsSection v-model="provider" :disabled="loading">
|
||||
<ZFormItem :label="t('keys.editor.upstreamIdentity')">
|
||||
<ProviderRequestProfilesEditor v-model:updates="form.profiles" :initial-profiles="initialProfiles" allow-inherit :active="open" :provider="provider" :disabled="loading" />
|
||||
</ZFormItem>
|
||||
<InstallationSeedField v-if="provider === 'openai'" ref="seedField" v-model="form.installationSeed" :disabled="loading" :error="seedError" :placeholder="hasExistingSeed ? t('accounts.modelAccess.reserve') : t('settings.clientProfile.installationSeedPlaceholder')" />
|
||||
</ProviderSettingsSection>
|
||||
</ZForm>
|
||||
|
||||
<template #footer>
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
import type { ApiKeyFormValue } from '../composables/useApiKeyEditor'
|
||||
|
||||
import type { AccountGroupRef, ApiKeyPeerSharing } from '@/api'
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { ZButton, ZDialog, ZForm, ZFormItem, ZInput } from '@codex-proxy/ui'
|
||||
import { KeyRound } from '@lucide/vue'
|
||||
|
||||
import { computed, useTemplateRef, watch } from 'vue'
|
||||
import { computed, nextTick, shallowRef, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
|
||||
import ProviderSettingsSection from '@/components/ProviderSettingsSection.vue'
|
||||
import ProviderRequestProfilesEditor from '@/components/request-profile/index.vue'
|
||||
import { isValidInstallationSeed } from '@/providers/openai/request-profile/installationSeed'
|
||||
import InstallationSeedField from '@/providers/openai/request-profile/InstallationSeedField.vue'
|
||||
@@ -32,6 +34,8 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const open = defineModel<boolean>({ default: false })
|
||||
const form = defineModel<ApiKeyFormValue>('form', { required: true })
|
||||
const provider = shallowRef<BuiltinProvider>('openai')
|
||||
const seedField = useTemplateRef<InstanceType<typeof InstallationSeedField>>('seedField')
|
||||
const title = computed(() => props.editing
|
||||
? t('keys.actions.editKey')
|
||||
: t('keys.filters.createApiKey'))
|
||||
@@ -42,10 +46,22 @@ const installationSeedError = computed(() => isValidInstallationSeed(form.value.
|
||||
? ''
|
||||
: t('settings.clientProfile.invalidInstallationSeed'))
|
||||
|
||||
watch(open, () => formRef.value?.clearValidate())
|
||||
watch(open, (visible) => {
|
||||
formRef.value?.clearValidate()
|
||||
if (visible)
|
||||
provider.value = 'openai'
|
||||
})
|
||||
|
||||
async function requestSave() {
|
||||
if (props.saving || installationSeedError.value || !await formRef.value?.validate().catch(() => false))
|
||||
if (props.saving)
|
||||
return
|
||||
if (installationSeedError.value) {
|
||||
provider.value = 'openai'
|
||||
await nextTick()
|
||||
seedField.value?.focus()
|
||||
return
|
||||
}
|
||||
if (!await formRef.value?.validate().catch(() => false))
|
||||
return
|
||||
emit('save')
|
||||
}
|
||||
@@ -123,27 +139,30 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) {
|
||||
|
||||
<ApiKeyPeerSharingField :sharing="form.peerSharing" :disabled="saving" @change="updatePeerSharing" />
|
||||
|
||||
<div class="grid gap-4">
|
||||
<ApiKeyLimitFields
|
||||
v-model:daily-limit-usd="form.dailyLimitUsd" v-model:weekly-limit-usd="form.weeklyLimitUsd"
|
||||
v-model:max-concurrency="form.maxConcurrency" v-model:requests-per-minute="form.requestsPerMinute"
|
||||
:disabled="saving"
|
||||
/>
|
||||
|
||||
<ProviderSettingsSection v-model="provider" :disabled="saving">
|
||||
<ZFormItem :label="t('keys.editor.upstreamIdentity')">
|
||||
<ProviderRequestProfilesEditor
|
||||
:model-value="form.providerRequestProfileOverrides" allow-inherit
|
||||
:active="open"
|
||||
:provider="provider"
|
||||
:disabled="saving"
|
||||
@update:model-value="updateForm('providerRequestProfileOverrides', $event)"
|
||||
/>
|
||||
</ZFormItem>
|
||||
|
||||
<InstallationSeedField
|
||||
v-if="provider === 'openai'"
|
||||
ref="seedField"
|
||||
v-model="form.installationSeed" :error="installationSeedError" :disabled="saving"
|
||||
:placeholder="t('settings.clientProfile.installationSeedPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ApiKeyLimitFields
|
||||
v-model:daily-limit-usd="form.dailyLimitUsd" v-model:weekly-limit-usd="form.weeklyLimitUsd"
|
||||
v-model:max-concurrency="form.maxConcurrency" v-model:requests-per-minute="form.requestsPerMinute"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</ProviderSettingsSection>
|
||||
</ZForm>
|
||||
|
||||
<template #footer>
|
||||
@@ -153,7 +172,6 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) {
|
||||
<ZButton
|
||||
type="primary"
|
||||
:loading="saving"
|
||||
:disabled="!!installationSeedError"
|
||||
@click="requestSave"
|
||||
>
|
||||
{{ editing ? t('common.actions.save') : t('common.actions.create') }}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, isBuiltinProvider, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const provider = defineModel<BuiltinProvider>({ required: true })
|
||||
const options = PROVIDER_IDS.map(value => ({
|
||||
value,
|
||||
label: value === 'openai'
|
||||
? 'OpenAI'
|
||||
: formatProviderLabel(value),
|
||||
icon: providerIcon(value),
|
||||
}))
|
||||
|
||||
function selectProvider(value: string) {
|
||||
if (isBuiltinProvider(value))
|
||||
provider.value = value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZSegmented
|
||||
:model-value="provider"
|
||||
:options="options"
|
||||
:aria-label="t('settings.page.providerLabel')"
|
||||
class="w-full @sm/settings:w-auto @max-sm/settings:[&>button]:px-2"
|
||||
@update:model-value="selectProvider"
|
||||
/>
|
||||
</template>
|
||||
@@ -1,10 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { ZButton, ZIconButton, ZInput, ZPopover, ZSegmented, ZSelect } from '@codex-proxy/ui'
|
||||
import { ZButton, ZIconButton, ZInput, ZPopover, ZSelect } from '@codex-proxy/ui'
|
||||
|
||||
import { CircleAlert, Download, Percent, Plus, RotateCcw, Search, X } from '@lucide/vue'
|
||||
import { computed, shallowRef, useId } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, providerIcon } from '@/providers/catalog'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import { sourceLabels } from './model'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -26,11 +26,6 @@ const source = defineModel<string>('source', { required: true })
|
||||
const syncInfoOpen = shallowRef(false)
|
||||
const syncInfoId = useId()
|
||||
const syncTime = computed(() => props.syncedAtDisplay ?? t('settings.pricing.notSyncedYet'))
|
||||
const providerOptions = computed(() => props.providers.map(value => ({
|
||||
label: formatProviderLabel(value),
|
||||
value,
|
||||
icon: providerIcon(value),
|
||||
})))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -41,13 +36,11 @@ const providerOptions = computed(() => props.providers.map(value => ({
|
||||
<Search class="size-4" />
|
||||
</template>
|
||||
</ZInput>
|
||||
<div v-if="providerOptions.length" class="min-w-0 max-w-full overflow-x-auto">
|
||||
<ZSegmented
|
||||
<div v-if="providers.length" class="min-w-0 max-w-full overflow-x-auto">
|
||||
<ProviderSelect
|
||||
v-model="provider"
|
||||
:aria-label="t('settings.pricing.modelProvider')"
|
||||
display="icon"
|
||||
:style="{ width: `${providerOptions.length * 40 + 4}px` }"
|
||||
:options="providerOptions"
|
||||
:providers="providers"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Play } from '@lucide/vue'
|
||||
import { cloneDeep } from 'es-toolkit'
|
||||
import { computed, ref, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { exampleRequest, newRule, newStep } from './presets'
|
||||
import { exampleRequest, expandWorkspaceSteps, newRule, newStep } from './presets'
|
||||
import StepFields from './StepFields.vue'
|
||||
import StepList from './StepList.vue'
|
||||
import { usePrivacyPreview } from './usePrivacyPreview'
|
||||
@@ -46,6 +46,7 @@ watch(open, (value) => {
|
||||
if (value) {
|
||||
selectedIndex.value = 0
|
||||
draft.value = cloneDeep(props.rule ?? newRule())
|
||||
draft.value.steps = expandWorkspaceSteps(draft.value.steps)
|
||||
fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value))
|
||||
sample.value = JSON.stringify(exampleRequest(), null, 2)
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ const columns = computed(() => (defineTableColumns<PrivacyRule>([
|
||||
{{ [...new Set(row.steps.map(step => scopes.find(item => item.value === step.scope)?.label))].join('、') }}
|
||||
</template>
|
||||
<template #action="{ row }">
|
||||
{{ [...new Set(row.steps.map(step => actions.find(item => item.value === step.action)?.label))].join('、') }}
|
||||
{{ [...new Set(row.steps.map(step => step.action === 'anonymize_workspace' ? t('settings.privacy.presets.anonymizeWorkspace') : actions.find(item => item.value === step.action)?.label))].join('、') }}
|
||||
</template>
|
||||
<template #actions="{ row }">
|
||||
<div class="flex items-center justify-end gap-1">
|
||||
|
||||
@@ -12,7 +12,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
const step = defineModel<PrivacyStep>({ required: true })
|
||||
const fixedValue = defineModel<string>('fixedValue', { required: true })
|
||||
const fieldPresetId = useId()
|
||||
const anonymizesWorkspace = computed(() => step.value.action === 'anonymize_workspace')
|
||||
const anonymizesProject = computed(() => step.value.action === 'anonymize_project')
|
||||
const usesPattern = computed(() => ['regex_replace', 'rename_key'].includes(step.value.action) || (step.value.action === 'remove_field' && step.value.pattern !== null))
|
||||
const pattern = computed({
|
||||
get: () => step.value.pattern ?? '',
|
||||
@@ -44,7 +44,7 @@ const selectorPlaceholder = computed(() => ({
|
||||
})[step.value.scope])
|
||||
|
||||
watch(() => step.value.action, (action) => {
|
||||
if (action === 'anonymize_workspace') {
|
||||
if (action === 'anonymize_project') {
|
||||
step.value.scope = 'turn_metadata'
|
||||
step.value.selector = '$.workspaces'
|
||||
step.value.pattern = null
|
||||
@@ -61,7 +61,7 @@ watch(() => step.value.action, (action) => {
|
||||
<template>
|
||||
<ZForm class="sm:grid-cols-2">
|
||||
<ZFormItem class="md:[&>div:first-child]:min-h-8" :label="t('settings.privacy.rules.scope')">
|
||||
<ZSelect v-model="step.scope" class="w-full" :options="scopes" :disabled="anonymizesWorkspace" :aria-label="t('settings.privacy.rules.scope')" />
|
||||
<ZSelect v-model="step.scope" class="w-full" :options="scopes" :disabled="anonymizesProject" :aria-label="t('settings.privacy.rules.scope')" />
|
||||
</ZFormItem>
|
||||
<ZFormItem class="md:[&>div:first-child]:min-h-8" :label="t('settings.privacy.rules.processingMethod')">
|
||||
<ZSelect v-model="step.action" class="w-full" :options="actions" :aria-label="t('settings.privacy.rules.processingMethod')" />
|
||||
@@ -80,13 +80,10 @@ watch(() => step.value.action, (action) => {
|
||||
</ZPopover>
|
||||
</template>
|
||||
<div class="flex flex-wrap items-center gap-2 sm:flex-nowrap">
|
||||
<ZInput v-model="step.selector" :disabled="anonymizesWorkspace" :placeholder="selectorPlaceholder" :aria-label="t('settings.privacy.steps.fieldPath')" maxlength="1024" class="min-w-0 flex-1 font-mono" :class="fields.length ? 'basis-full sm:basis-auto' : undefined" spellcheck="false" />
|
||||
<ZSelect v-if="fields.length" :id="fieldPresetId" v-model="fieldChoice" :disabled="anonymizesWorkspace" class="min-w-0 flex-1 sm:w-40 sm:flex-none" :options="fields" :aria-label="t('settings.privacy.steps.commonFields')" />
|
||||
<ZInput v-model="step.selector" :disabled="anonymizesProject" :placeholder="selectorPlaceholder" :aria-label="t('settings.privacy.steps.fieldPath')" maxlength="1024" class="min-w-0 flex-1 font-mono" :class="fields.length ? 'basis-full sm:basis-auto' : undefined" spellcheck="false" />
|
||||
<ZSelect v-if="fields.length" :id="fieldPresetId" v-model="fieldChoice" :disabled="anonymizesProject" class="min-w-0 flex-1 sm:w-40 sm:flex-none" :options="fields" :aria-label="t('settings.privacy.steps.commonFields')" />
|
||||
</div>
|
||||
</ZFormItem>
|
||||
<p v-if="anonymizesWorkspace" class="m-0 text-z-sm text-z-text-secondary sm:col-span-2">
|
||||
{{ t('settings.privacy.steps.anonymizeWorkspaceHelp') }}
|
||||
</p>
|
||||
<ZCheckbox v-if="step.action === 'remove_field'" v-model="conditional" class="sm:col-span-2" :label="t('settings.privacy.steps.deleteMatchHelp')" />
|
||||
<ZFormItem v-if="usesPattern" :class="step.action === 'remove_field' ? 'sm:col-span-2' : undefined" :label="t('settings.privacy.steps.matchExpression')">
|
||||
<ZInput v-model="pattern" :placeholder="step.action === 'rename_key' ? t('settings.privacy.steps.forExampleHome') : t('settings.privacy.steps.forExamplePrivateOrg')" :aria-label="t('settings.privacy.steps.matchExpression')" maxlength="4096" spellcheck="false" class="font-mono" />
|
||||
|
||||
@@ -27,7 +27,7 @@ const items = computed(() => props.steps.map((step, index) => {
|
||||
: step.selector.trim() || t('settings.privacy.steps.noFieldsSelected'))
|
||||
const scope = scopes.value.find(scope => scope.value === step.scope)?.label
|
||||
const action = actions.value.find(action => action.value === step.action)?.label
|
||||
const effect = step.action === 'anonymize_workspace'
|
||||
const effect = step.action === 'anonymize_project'
|
||||
? t('settings.privacy.steps.sessionAliasEffect')
|
||||
: step.action === 'set_value'
|
||||
? `→ ${props.fixedValues[index] ?? '""'}`
|
||||
|
||||
@@ -27,8 +27,8 @@ export const scopes = computed<{ value: PrivacyScope, label: string }[]>(() => (
|
||||
]))
|
||||
export const actions = computed<{ value: PrivacyAction, label: string }[]>(() => ([
|
||||
{
|
||||
value: 'anonymize_workspace',
|
||||
label: t('settings.privacy.presets.anonymizeWorkspace'),
|
||||
value: 'anonymize_project',
|
||||
label: t('settings.privacy.presets.anonymizeProject'),
|
||||
},
|
||||
{
|
||||
value: 'regex_replace',
|
||||
@@ -53,6 +53,10 @@ export const fieldsByScope = computed<Partial<Record<PrivacyScope, { value: stri
|
||||
value: '',
|
||||
label: t('settings.privacy.presets.customFieldPath'),
|
||||
},
|
||||
{
|
||||
value: '$.workspaces.*.associated_remote_urls',
|
||||
label: t('settings.privacy.presets.gitRemoteCollection'),
|
||||
},
|
||||
{
|
||||
value: '$.workspaces.*.associated_remote_urls.*',
|
||||
label: t('settings.privacy.presets.gitRemoteAddress'),
|
||||
@@ -115,18 +119,40 @@ export function newRule(): PrivacyRule {
|
||||
}
|
||||
}
|
||||
|
||||
// 化名从原始路径派生,用户名替换不能改变其身份输入
|
||||
const workspaceSteps: Partial<PrivacyStep>[] = [
|
||||
{
|
||||
scope: 'turn_metadata',
|
||||
selector: '$.workspaces',
|
||||
action: 'anonymize_project',
|
||||
pattern: null,
|
||||
},
|
||||
{
|
||||
scope: 'turn_metadata',
|
||||
selector: '$.workspaces',
|
||||
action: 'rename_key',
|
||||
pattern: String.raw`(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])`,
|
||||
replacement: `\${1}user\${2}`,
|
||||
},
|
||||
{
|
||||
scope: 'turn_metadata',
|
||||
selector: '$.workspaces.*.associated_remote_urls',
|
||||
action: 'remove_field',
|
||||
pattern: null,
|
||||
},
|
||||
{
|
||||
scope: 'turn_metadata',
|
||||
selector: '$.workspaces.*.latest_git_commit_hash',
|
||||
action: 'remove_field',
|
||||
pattern: null,
|
||||
},
|
||||
]
|
||||
|
||||
export const presets = computed<{ key: string, name: string, steps: Partial<PrivacyStep>[] }[]>(() => ([
|
||||
{
|
||||
key: 'session-workspace',
|
||||
name: t('settings.privacy.presets.anonymizeWorkspace'),
|
||||
steps: [
|
||||
{
|
||||
scope: 'turn_metadata',
|
||||
selector: '$.workspaces',
|
||||
action: 'anonymize_workspace',
|
||||
pattern: null,
|
||||
},
|
||||
],
|
||||
steps: workspaceSteps,
|
||||
},
|
||||
{
|
||||
key: 'workspace',
|
||||
@@ -156,13 +182,24 @@ export function createPreset(key: string): PrivacyRule {
|
||||
return {
|
||||
...newRule(),
|
||||
name: preset.name,
|
||||
steps: preset.steps.map(step => ({
|
||||
...newStep(),
|
||||
...cloneDeep(step),
|
||||
})),
|
||||
steps: createSteps(preset.steps),
|
||||
}
|
||||
}
|
||||
|
||||
function createSteps(steps: Partial<PrivacyStep>[]): PrivacyStep[] {
|
||||
return steps.map(step => ({
|
||||
...newStep(),
|
||||
...cloneDeep(step),
|
||||
}))
|
||||
}
|
||||
|
||||
export function expandWorkspaceSteps(steps: PrivacyStep[]): PrivacyStep[] {
|
||||
// 只展开编辑草稿,已保存的组合动作由后端保持原行为
|
||||
return steps.flatMap(step => step.action === 'anonymize_workspace'
|
||||
? createSteps(workspaceSteps)
|
||||
: [step])
|
||||
}
|
||||
|
||||
// 样本使用虚构仓库、路径与标识,字段形状对应官方 Core 和 Desktop Git 上下文
|
||||
const metadata = {
|
||||
workspaces: {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Save, Undo2 } from '@lucide/vue'
|
||||
import { computed, nextTick, reactive, shallowRef, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
|
||||
import { isBuiltinProvider, PROVIDER_IDS } from '@/providers/catalog'
|
||||
|
||||
@@ -19,7 +20,6 @@ import GuardianReviewCard from './components/GuardianReviewCard.vue'
|
||||
import ModelAliasesCard from './components/ModelAliasesCard.vue'
|
||||
import PricingSection from './components/pricing/index.vue'
|
||||
import PrivacyPolicyCard from './components/privacy/index.vue'
|
||||
import ProviderSettingsNav from './components/ProviderSettingsNav.vue'
|
||||
import RequestCountryCard from './components/RequestCountryCard.vue'
|
||||
import RequestHistoryCard from './components/RequestHistoryCard.vue'
|
||||
import RequestLocationCard from './components/RequestLocationCard.vue'
|
||||
@@ -195,7 +195,7 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
:options="sectionOptions"
|
||||
@update:model-value="switchSection"
|
||||
/>
|
||||
<ProviderSettingsNav v-if="section === 'upstream'" :model-value="provider" :disabled="disabled" @update:model-value="switchProvider" />
|
||||
<ProviderSelect v-if="section === 'upstream'" :model-value="provider" display="label" class="w-full @sm/settings:w-auto @max-sm/settings:[&>button]:px-2" :aria-label="t('settings.page.providerLabel')" :disabled="disabled" @update:model-value="switchProvider" />
|
||||
<div v-if="isBasicSection || hasChanges" class="ml-auto flex items-center justify-end gap-2">
|
||||
<span v-if="hasChanges" class="mr-1 size-1.5 shrink-0 rounded-full bg-z-warning" aria-hidden="true" />
|
||||
<ZIconButton v-if="hasChanges" :aria-label="t('settings.page.undoAllBasicSettingsChanges')" variant="solid" :disabled="saving || loading || detectingLocation" @click="resetForm">
|
||||
|
||||
+1
-1
Submodule modules/ui updated: 023337b917...305d01af72
+6
-21
@@ -1,27 +1,12 @@
|
||||
# v3.55.0
|
||||
|
||||
## 新增功能
|
||||
|
||||
- 接入 Antigravity OAuth 账号,支持授权、导入导出、模型目录、额度查询与本地费用估算
|
||||
- 支持 Antigravity 原生 GenAI 生成、流式输出和 Token 计数,并可通过 Responses、Chat Completions 与 Messages 调用
|
||||
- 新增「按账号与会话匿名化工作区」隐私预设,打乱工程名并附加数字,换账号或会话时派生新化名,同时移除 Git 远端与提交 metadata
|
||||
# v3.55.1
|
||||
|
||||
## 优化改进
|
||||
|
||||
- 账号亲和设置统一应用于 OpenAI、xAI 和 Antigravity,支持宽松、优先与严格模式
|
||||
- 备份设置不再回传已保存的密钥,保存与连接测试按配置版本校验
|
||||
- 请求列表缺少上游耗时时,显示带 `≈` 的本地平均输出速率
|
||||
- 统一各页面的平台选择器,分组和密钥按平台展示专属配置,通用项保持独立
|
||||
- 工作区匿名化拆分为项目名、用户名、Git 远端及提交信息四个可编辑步骤,已有组合规则继续生效
|
||||
- 更新 macOS 客户端身份预设,CLI 预设默认使用 TUI 入口和 Apple Terminal,保留已保存的入口与终端配置
|
||||
|
||||
## 问题修复
|
||||
|
||||
- 修复 OpenAI 耗尽窗口丢失、重置时间无法对应或持续后移时的额度恢复判断
|
||||
- 修复上游 WebSocket 控制连接过期后,客户端未收到重连提示的问题
|
||||
- 修复调整模型价格或轮换管理密钥后,运行设置草稿被误判为冲突的问题
|
||||
|
||||
## 升级须知
|
||||
|
||||
- 已有亲和设置自动迁移,Admin API 字段 `openaiAccountAffinity`、`openaiSessionAffinityTtlHours` 改为 `accountAffinity`、`sessionAffinityTtlHours`
|
||||
- 备份管理接口写入时须携带 `storageRevision`,读取密钥配置状态使用 `secretConfigured`,保存时省略 `secretAccessKey` 保留原值
|
||||
- 账号导出统一使用 `label`、`createdAt`、`updatedAt`、`accessTokenExpiresAt` 和 `scopes` 字段,xAI 凭据位于 `credentials` 对象,直接解析导出文件的工具需同步适配
|
||||
- Antigravity 所有生成入口使用服务端 AGY 系统提示词配置替换客户端系统指令,转换入口不支持 `previous_response_id` 续接
|
||||
- 未发布的迁移 `0046~0048` 合并为 `0046`,已执行这些迁移的源码部署实例需先核对迁移历史,正式版升级不受影响
|
||||
- 修复 OpenAI、xAI 和 Antigravity 的账号后台操作未使用全局上游身份的问题,覆盖 OAuth、令牌续期、额度刷新及目录查询等场景
|
||||
- 修复插件 SDK 未同步项目匿名化动作的问题,使其与宿主隐私配置合同保持一致
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.55.0
|
||||
version: 3.55.1
|
||||
published:
|
||||
'3':
|
||||
stable: 3.54.5
|
||||
rc: 3.54.5
|
||||
beta: 3.54.5
|
||||
alpha: 3.54.5
|
||||
stable: 3.55.0
|
||||
rc: 3.55.0
|
||||
beta: 3.55.0
|
||||
alpha: 3.55.0
|
||||
|
||||
Reference in New Issue
Block a user