Reanchor auth spine in Codex login
This commit is contained in:
parent
e44d4f96e6
commit
1a9678bb01
8 changed files with 5920 additions and 1673 deletions
5199
epiphany-openai-auth-spine/Cargo.lock
generated
5199
epiphany-openai-auth-spine/Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -8,14 +8,12 @@ name = "epiphany_openai_auth_spine"
|
|||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
codex-client = { path = "../vendor/codex/codex-rs/codex-client" }
|
||||
keyring = "3.6.3"
|
||||
reqwest = { version = "0.12", features = ["blocking", "json"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
codex-login = { path = "../vendor/codex/codex-rs/login" }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
tracing = "0.1"
|
||||
|
||||
[patch.crates-io]
|
||||
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "132f5b39c862e3a970f731d709608b3e6276d5f6" }
|
||||
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }
|
||||
|
||||
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
|
||||
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }
|
||||
|
|
|
|||
|
|
@ -1,871 +1,55 @@
|
|||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use base64::Engine;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_client::build_reqwest_client_with_custom_ca;
|
||||
use codex_client::with_chatgpt_cloudflare_cookie_store;
|
||||
use keyring::Entry;
|
||||
use reqwest::StatusCode;
|
||||
use reqwest::header::HeaderMap;
|
||||
use reqwest::header::HeaderValue;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use thiserror::Error;
|
||||
use tracing::warn;
|
||||
|
||||
pub const OPENAI_API_KEY_ENV_VAR: &str = "OPENAI_API_KEY";
|
||||
pub const CODEX_API_KEY_ENV_VAR: &str = "CODEX_API_KEY";
|
||||
pub const REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR: &str = "CODEX_REFRESH_TOKEN_URL_OVERRIDE";
|
||||
const REFRESH_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
|
||||
const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
|
||||
const TOKEN_REFRESH_INTERVAL_MINUTES: i64 = 8;
|
||||
const KEYRING_SERVICE: &str = "Codex Auth";
|
||||
|
||||
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AuthCredentialsStoreMode {
|
||||
#[default]
|
||||
File,
|
||||
Keyring,
|
||||
Auto,
|
||||
Ephemeral,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AuthMode {
|
||||
ApiKey,
|
||||
Chatgpt,
|
||||
#[serde(rename = "chatgptAuthTokens")]
|
||||
ChatgptAuthTokens,
|
||||
#[serde(rename = "agentIdentity")]
|
||||
AgentIdentity,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AccountPlanType {
|
||||
#[default]
|
||||
Free,
|
||||
Go,
|
||||
Plus,
|
||||
Pro,
|
||||
ProLite,
|
||||
Team,
|
||||
#[serde(rename = "self_serve_business_usage_based")]
|
||||
SelfServeBusinessUsageBased,
|
||||
Business,
|
||||
#[serde(rename = "enterprise_cbp_usage_based")]
|
||||
EnterpriseCbpUsageBased,
|
||||
Enterprise,
|
||||
Edu,
|
||||
#[serde(other)]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum ChatGptPlanType {
|
||||
Known(KnownChatGptPlan),
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum KnownChatGptPlan {
|
||||
Free,
|
||||
Go,
|
||||
Plus,
|
||||
Pro,
|
||||
ProLite,
|
||||
Team,
|
||||
#[serde(rename = "self_serve_business_usage_based")]
|
||||
SelfServeBusinessUsageBased,
|
||||
Business,
|
||||
#[serde(rename = "enterprise_cbp_usage_based")]
|
||||
EnterpriseCbpUsageBased,
|
||||
#[serde(alias = "hc")]
|
||||
Enterprise,
|
||||
Edu,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Default)]
|
||||
pub struct TokenData {
|
||||
#[serde(
|
||||
deserialize_with = "deserialize_id_token",
|
||||
serialize_with = "serialize_id_token"
|
||||
)]
|
||||
pub id_token: IdTokenInfo,
|
||||
pub access_token: String,
|
||||
pub refresh_token: String,
|
||||
pub account_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct IdTokenInfo {
|
||||
pub email: Option<String>,
|
||||
pub chatgpt_plan_type: Option<ChatGptPlanType>,
|
||||
pub chatgpt_user_id: Option<String>,
|
||||
pub chatgpt_account_id: Option<String>,
|
||||
pub chatgpt_account_is_fedramp: bool,
|
||||
pub raw_jwt: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
|
||||
pub struct AuthDotJson {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auth_mode: Option<AuthMode>,
|
||||
#[serde(rename = "OPENAI_API_KEY")]
|
||||
pub openai_api_key: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tokens: Option<TokenData>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_refresh: Option<DateTime<Utc>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub agent_identity: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum CodexAuth {
|
||||
ApiKey(ApiKeyAuth),
|
||||
Chatgpt(ChatgptAuth),
|
||||
ChatgptAuthTokens(ChatgptAuthTokens),
|
||||
AgentIdentity(AgentIdentityAuth),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApiKeyAuth {
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChatgptAuth {
|
||||
auth: AuthDotJson,
|
||||
codex_home: PathBuf,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChatgptAuthTokens {
|
||||
auth: AuthDotJson,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AgentIdentityAuth {
|
||||
account_id: Option<String>,
|
||||
plan_type: Option<AccountPlanType>,
|
||||
chatgpt_account_is_fedramp: bool,
|
||||
}
|
||||
|
||||
impl CodexAuth {
|
||||
pub fn from_api_key(api_key: impl Into<String>) -> Self {
|
||||
Self::ApiKey(ApiKeyAuth {
|
||||
api_key: api_key.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_api_key_auth(&self) -> bool {
|
||||
matches!(self, Self::ApiKey(_))
|
||||
}
|
||||
|
||||
pub fn is_chatgpt_auth(&self) -> bool {
|
||||
matches!(self, Self::Chatgpt(_) | Self::ChatgptAuthTokens(_))
|
||||
}
|
||||
|
||||
pub fn auth_mode(&self) -> AuthMode {
|
||||
match self {
|
||||
Self::ApiKey(_) => AuthMode::ApiKey,
|
||||
Self::Chatgpt(_) => AuthMode::Chatgpt,
|
||||
Self::ChatgptAuthTokens(_) => AuthMode::ChatgptAuthTokens,
|
||||
Self::AgentIdentity(_) => AuthMode::AgentIdentity,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uses_codex_backend(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Chatgpt(_) | Self::ChatgptAuthTokens(_) | Self::AgentIdentity(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_token(&self) -> std::io::Result<String> {
|
||||
match self {
|
||||
Self::ApiKey(auth) => Ok(auth.api_key.clone()),
|
||||
Self::Chatgpt(auth) => auth.access_token(),
|
||||
Self::ChatgptAuthTokens(auth) => auth.access_token(),
|
||||
Self::AgentIdentity(_) => Err(std::io::Error::other(
|
||||
"agent identity auth is not implemented in Epiphany auth spine",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_account_id(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::ApiKey(_) => None,
|
||||
Self::Chatgpt(auth) => auth.account_id(),
|
||||
Self::ChatgptAuthTokens(auth) => auth.account_id(),
|
||||
Self::AgentIdentity(auth) => auth.account_id.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn account_plan_type(&self) -> Option<AccountPlanType> {
|
||||
match self {
|
||||
Self::ApiKey(_) => None,
|
||||
Self::Chatgpt(auth) => auth.account_plan_type(),
|
||||
Self::ChatgptAuthTokens(auth) => auth.account_plan_type(),
|
||||
Self::AgentIdentity(auth) => auth.plan_type,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_fedramp_account(&self) -> bool {
|
||||
match self {
|
||||
Self::ApiKey(_) => false,
|
||||
Self::Chatgpt(auth) => auth.is_fedramp_account(),
|
||||
Self::ChatgptAuthTokens(auth) => auth.is_fedramp_account(),
|
||||
Self::AgentIdentity(auth) => auth.chatgpt_account_is_fedramp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatgptAuth {
|
||||
fn access_token(&self) -> std::io::Result<String> {
|
||||
let tokens = self.tokens()?;
|
||||
let should_refresh = match self.auth.last_refresh {
|
||||
Some(last_refresh) => {
|
||||
Utc::now().signed_duration_since(last_refresh).num_minutes()
|
||||
>= TOKEN_REFRESH_INTERVAL_MINUTES
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if should_refresh && !tokens.refresh_token.is_empty() {
|
||||
let previous_access_token = tokens.access_token.clone();
|
||||
return refresh_and_persist_tokens(
|
||||
self.codex_home.clone(),
|
||||
self.store_mode,
|
||||
tokens.refresh_token.clone(),
|
||||
)
|
||||
.map(|auth| {
|
||||
auth.tokens
|
||||
.map(|tokens| tokens.access_token)
|
||||
.unwrap_or(previous_access_token)
|
||||
});
|
||||
}
|
||||
Ok(tokens.access_token.clone())
|
||||
}
|
||||
|
||||
fn tokens(&self) -> std::io::Result<&TokenData> {
|
||||
self.auth
|
||||
.tokens
|
||||
.as_ref()
|
||||
.ok_or_else(|| std::io::Error::other("ChatGPT token data is not available"))
|
||||
}
|
||||
|
||||
fn account_id(&self) -> Option<String> {
|
||||
token_account_id(self.auth.tokens.as_ref())
|
||||
}
|
||||
|
||||
fn account_plan_type(&self) -> Option<AccountPlanType> {
|
||||
token_account_plan_type(self.auth.tokens.as_ref())
|
||||
}
|
||||
|
||||
fn is_fedramp_account(&self) -> bool {
|
||||
token_is_fedramp(self.auth.tokens.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatgptAuthTokens {
|
||||
fn access_token(&self) -> std::io::Result<String> {
|
||||
self.auth
|
||||
.tokens
|
||||
.as_ref()
|
||||
.map(|tokens| tokens.access_token.clone())
|
||||
.ok_or_else(|| std::io::Error::other("ChatGPT token data is not available"))
|
||||
}
|
||||
|
||||
fn account_id(&self) -> Option<String> {
|
||||
token_account_id(self.auth.tokens.as_ref())
|
||||
}
|
||||
|
||||
fn account_plan_type(&self) -> Option<AccountPlanType> {
|
||||
token_account_plan_type(self.auth.tokens.as_ref())
|
||||
}
|
||||
|
||||
fn is_fedramp_account(&self) -> bool {
|
||||
token_is_fedramp(self.auth.tokens.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthManager {
|
||||
codex_home: PathBuf,
|
||||
enable_codex_api_key_env: bool,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
cached_auth: RwLock<Option<CodexAuth>>,
|
||||
}
|
||||
|
||||
impl AuthManager {
|
||||
pub fn shared(
|
||||
codex_home: PathBuf,
|
||||
enable_codex_api_key_env: bool,
|
||||
auth_credentials_store_mode: AuthCredentialsStoreMode,
|
||||
_chatgpt_base_url: Option<String>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self::new(
|
||||
codex_home,
|
||||
enable_codex_api_key_env,
|
||||
auth_credentials_store_mode,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
codex_home: PathBuf,
|
||||
enable_codex_api_key_env: bool,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
) -> Self {
|
||||
let cached_auth = load_auth(&codex_home, enable_codex_api_key_env, store_mode)
|
||||
.ok()
|
||||
.flatten();
|
||||
Self {
|
||||
codex_home,
|
||||
enable_codex_api_key_env,
|
||||
store_mode,
|
||||
cached_auth: RwLock::new(cached_auth),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn auth(&self) -> Option<CodexAuth> {
|
||||
if self.enable_codex_api_key_env
|
||||
&& let Some(api_key) = read_codex_api_key_from_env()
|
||||
{
|
||||
return Some(CodexAuth::from_api_key(api_key));
|
||||
}
|
||||
if let Ok(guard) = self.cached_auth.read()
|
||||
&& let Some(auth) = guard.clone()
|
||||
{
|
||||
return Some(auth);
|
||||
}
|
||||
let auth = load_auth(
|
||||
&self.codex_home,
|
||||
self.enable_codex_api_key_env,
|
||||
self.store_mode,
|
||||
)
|
||||
.ok()
|
||||
.flatten();
|
||||
if let Ok(mut guard) = self.cached_auth.write() {
|
||||
*guard = auth.clone();
|
||||
}
|
||||
auth
|
||||
}
|
||||
|
||||
pub fn auth_mode(&self) -> Option<AuthMode> {
|
||||
if self.enable_codex_api_key_env && read_codex_api_key_from_env().is_some() {
|
||||
return Some(AuthMode::ApiKey);
|
||||
}
|
||||
self.cached_auth
|
||||
.read()
|
||||
.ok()
|
||||
.and_then(|guard| guard.as_ref().map(CodexAuth::auth_mode))
|
||||
}
|
||||
|
||||
pub fn codex_api_key_env_enabled(&self) -> bool {
|
||||
self.enable_codex_api_key_env
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_openai_api_key_from_env() -> Option<String> {
|
||||
read_trimmed_env(OPENAI_API_KEY_ENV_VAR)
|
||||
}
|
||||
|
||||
pub fn read_codex_api_key_from_env() -> Option<String> {
|
||||
read_trimmed_env(CODEX_API_KEY_ENV_VAR)
|
||||
}
|
||||
|
||||
fn read_trimmed_env(key: &str) -> Option<String> {
|
||||
std::env::var(key)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn load_auth(
|
||||
codex_home: &PathBuf,
|
||||
enable_codex_api_key_env: bool,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
) -> std::io::Result<Option<CodexAuth>> {
|
||||
if enable_codex_api_key_env && let Some(api_key) = read_codex_api_key_from_env() {
|
||||
return Ok(Some(CodexAuth::from_api_key(api_key)));
|
||||
}
|
||||
if let Some(api_key) = read_openai_api_key_from_env() {
|
||||
return Ok(Some(CodexAuth::from_api_key(api_key)));
|
||||
}
|
||||
let Some(auth_dot_json) = load_auth_dot_json(codex_home, store_mode)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
build_auth(codex_home.clone(), store_mode, auth_dot_json).map(Some)
|
||||
}
|
||||
|
||||
fn build_auth(
|
||||
codex_home: PathBuf,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
auth_dot_json: AuthDotJson,
|
||||
) -> std::io::Result<CodexAuth> {
|
||||
if let Some(api_key) = auth_dot_json.openai_api_key.as_ref() {
|
||||
return Ok(CodexAuth::from_api_key(api_key.clone()));
|
||||
}
|
||||
match auth_dot_json.auth_mode.unwrap_or(AuthMode::Chatgpt) {
|
||||
AuthMode::ApiKey => auth_dot_json
|
||||
.openai_api_key
|
||||
.map(CodexAuth::from_api_key)
|
||||
.ok_or_else(|| std::io::Error::other("OpenAI API key is not available")),
|
||||
AuthMode::Chatgpt => Ok(CodexAuth::Chatgpt(ChatgptAuth {
|
||||
auth: auth_dot_json,
|
||||
codex_home,
|
||||
store_mode,
|
||||
})),
|
||||
AuthMode::ChatgptAuthTokens => Ok(CodexAuth::ChatgptAuthTokens(ChatgptAuthTokens {
|
||||
auth: auth_dot_json,
|
||||
})),
|
||||
AuthMode::AgentIdentity => Ok(CodexAuth::AgentIdentity(AgentIdentityAuth {
|
||||
account_id: None,
|
||||
plan_type: None,
|
||||
chatgpt_account_is_fedramp: false,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_file(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join("auth.json")
|
||||
}
|
||||
|
||||
fn load_file_auth_dot_json(codex_home: &Path) -> std::io::Result<Option<AuthDotJson>> {
|
||||
let auth_path = auth_file(codex_home);
|
||||
let contents = match std::fs::read_to_string(&auth_path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
serde_json::from_str(&contents)
|
||||
.map(Some)
|
||||
.map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
fn save_file_auth_dot_json(codex_home: &Path, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let auth_path = auth_file(codex_home);
|
||||
if let Some(parent) = auth_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let json_data = serde_json::to_string_pretty(auth).map_err(std::io::Error::other)?;
|
||||
let mut options = OpenOptions::new();
|
||||
options.truncate(true).write(true).create(true);
|
||||
let mut file = options.open(auth_path)?;
|
||||
file.write_all(json_data.as_bytes())?;
|
||||
file.flush()
|
||||
}
|
||||
|
||||
fn delete_file_if_exists(codex_home: &Path) -> std::io::Result<bool> {
|
||||
match std::fs::remove_file(auth_file(codex_home)) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn compute_store_key(codex_home: &Path) -> String {
|
||||
let canonical = codex_home
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| codex_home.to_path_buf());
|
||||
let path_str = canonical.to_string_lossy();
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(path_str.as_bytes());
|
||||
let digest = hasher.finalize();
|
||||
let hex = format!("{digest:x}");
|
||||
let truncated = hex.get(..16).unwrap_or(&hex);
|
||||
format!("cli|{truncated}")
|
||||
}
|
||||
|
||||
fn load_keyring_auth_dot_json(codex_home: &Path) -> std::io::Result<Option<AuthDotJson>> {
|
||||
let key = compute_store_key(codex_home);
|
||||
let entry = Entry::new(KEYRING_SERVICE, &key).map_err(|error| {
|
||||
std::io::Error::other(format!("failed to open CLI auth keyring entry: {error}"))
|
||||
})?;
|
||||
match entry.get_password() {
|
||||
Ok(serialized) => serde_json::from_str(&serialized).map(Some).map_err(|err| {
|
||||
std::io::Error::other(format!(
|
||||
"failed to deserialize CLI auth from keyring: {err}"
|
||||
))
|
||||
}),
|
||||
Err(keyring::Error::NoEntry) => Ok(None),
|
||||
Err(error) => Err(std::io::Error::other(format!(
|
||||
"failed to load CLI auth from keyring: {error}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_keyring_auth_dot_json(codex_home: &Path, auth: &AuthDotJson) -> std::io::Result<()> {
|
||||
let key = compute_store_key(codex_home);
|
||||
let serialized = serde_json::to_string(auth).map_err(std::io::Error::other)?;
|
||||
let entry = Entry::new(KEYRING_SERVICE, &key).map_err(|error| {
|
||||
std::io::Error::other(format!("failed to open CLI auth keyring entry: {error}"))
|
||||
})?;
|
||||
entry.set_password(&serialized).map_err(|error| {
|
||||
std::io::Error::other(format!("failed to write OAuth tokens to keyring: {error}"))
|
||||
})?;
|
||||
if let Err(err) = delete_file_if_exists(codex_home) {
|
||||
warn!("failed to remove CLI auth fallback file: {err}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_auth_dot_json(
|
||||
codex_home: &Path,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
) -> std::io::Result<Option<AuthDotJson>> {
|
||||
match store_mode {
|
||||
AuthCredentialsStoreMode::File => load_file_auth_dot_json(codex_home),
|
||||
AuthCredentialsStoreMode::Keyring => load_keyring_auth_dot_json(codex_home),
|
||||
AuthCredentialsStoreMode::Auto => match load_keyring_auth_dot_json(codex_home) {
|
||||
Ok(Some(auth)) => Ok(Some(auth)),
|
||||
Ok(None) => load_file_auth_dot_json(codex_home),
|
||||
Err(err) => {
|
||||
warn!("failed to load CLI auth from keyring, falling back to file storage: {err}");
|
||||
load_file_auth_dot_json(codex_home)
|
||||
}
|
||||
},
|
||||
AuthCredentialsStoreMode::Ephemeral => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_auth_dot_json(
|
||||
codex_home: &Path,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
auth: &AuthDotJson,
|
||||
) -> std::io::Result<()> {
|
||||
match store_mode {
|
||||
AuthCredentialsStoreMode::File => save_file_auth_dot_json(codex_home, auth),
|
||||
AuthCredentialsStoreMode::Keyring => save_keyring_auth_dot_json(codex_home, auth),
|
||||
AuthCredentialsStoreMode::Auto => match save_keyring_auth_dot_json(codex_home, auth) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
warn!("failed to save auth to keyring, falling back to file storage: {err}");
|
||||
save_file_auth_dot_json(codex_home, auth)
|
||||
}
|
||||
},
|
||||
AuthCredentialsStoreMode::Ephemeral => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn token_account_id(tokens: Option<&TokenData>) -> Option<String> {
|
||||
tokens.and_then(|tokens| {
|
||||
tokens
|
||||
.account_id
|
||||
.clone()
|
||||
.or_else(|| tokens.id_token.chatgpt_account_id.clone())
|
||||
})
|
||||
}
|
||||
|
||||
fn token_account_plan_type(tokens: Option<&TokenData>) -> Option<AccountPlanType> {
|
||||
let plan = tokens.and_then(|tokens| tokens.id_token.chatgpt_plan_type.as_ref())?;
|
||||
match plan {
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Free) => Some(AccountPlanType::Free),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Go) => Some(AccountPlanType::Go),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Plus) => Some(AccountPlanType::Plus),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Pro) => Some(AccountPlanType::Pro),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::ProLite) => Some(AccountPlanType::ProLite),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Team) => Some(AccountPlanType::Team),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::SelfServeBusinessUsageBased) => {
|
||||
Some(AccountPlanType::SelfServeBusinessUsageBased)
|
||||
}
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Business) => Some(AccountPlanType::Business),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::EnterpriseCbpUsageBased) => {
|
||||
Some(AccountPlanType::EnterpriseCbpUsageBased)
|
||||
}
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Enterprise) => Some(AccountPlanType::Enterprise),
|
||||
ChatGptPlanType::Known(KnownChatGptPlan::Edu) => Some(AccountPlanType::Edu),
|
||||
ChatGptPlanType::Unknown(_) => Some(AccountPlanType::Unknown),
|
||||
}
|
||||
}
|
||||
|
||||
fn token_is_fedramp(tokens: Option<&TokenData>) -> bool {
|
||||
tokens
|
||||
.map(|tokens| tokens.id_token.chatgpt_account_is_fedramp)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn refresh_and_persist_tokens(
|
||||
codex_home: PathBuf,
|
||||
store_mode: AuthCredentialsStoreMode,
|
||||
refresh_token: String,
|
||||
) -> std::io::Result<AuthDotJson> {
|
||||
let response = request_chatgpt_token_refresh_blocking(refresh_token)?;
|
||||
let mut auth_dot_json = load_auth_dot_json(&codex_home, store_mode)?
|
||||
.ok_or_else(|| std::io::Error::other("ChatGPT auth record is not available"))?;
|
||||
let tokens = auth_dot_json.tokens.get_or_insert_with(TokenData::default);
|
||||
if let Some(id_token) = response.id_token {
|
||||
tokens.id_token = parse_chatgpt_jwt_claims(&id_token).map_err(std::io::Error::other)?;
|
||||
}
|
||||
if let Some(access_token) = response.access_token {
|
||||
tokens.access_token = access_token;
|
||||
}
|
||||
if let Some(refresh_token) = response.refresh_token {
|
||||
tokens.refresh_token = refresh_token;
|
||||
}
|
||||
auth_dot_json.last_refresh = Some(Utc::now());
|
||||
save_auth_dot_json(&codex_home, store_mode, &auth_dot_json)?;
|
||||
Ok(auth_dot_json)
|
||||
}
|
||||
|
||||
fn request_chatgpt_token_refresh_blocking(
|
||||
refresh_token: String,
|
||||
) -> std::io::Result<RefreshResponse> {
|
||||
let refresh_request = RefreshRequest {
|
||||
client_id: CLIENT_ID,
|
||||
grant_type: "refresh_token",
|
||||
refresh_token,
|
||||
};
|
||||
let endpoint = std::env::var(REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR)
|
||||
.unwrap_or_else(|_| REFRESH_TOKEN_URL.to_string());
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.user_agent(format!(
|
||||
"epiphany-openai-auth-spine/{}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
))
|
||||
.build()
|
||||
.map_err(std::io::Error::other)?;
|
||||
let response = client
|
||||
.post(endpoint)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&refresh_request)
|
||||
.send()
|
||||
.map_err(std::io::Error::other)?;
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
return response
|
||||
.json::<RefreshResponse>()
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
let body = response.text().unwrap_or_default();
|
||||
if status == StatusCode::UNAUTHORIZED {
|
||||
return Err(std::io::Error::other(classify_refresh_token_failure(&body)));
|
||||
}
|
||||
Err(std::io::Error::other(format!(
|
||||
"failed to refresh ChatGPT token: {status}: {}",
|
||||
try_parse_error_message(&body)
|
||||
)))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct RefreshRequest {
|
||||
client_id: &'static str,
|
||||
grant_type: &'static str,
|
||||
refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
struct RefreshResponse {
|
||||
id_token: Option<String>,
|
||||
access_token: Option<String>,
|
||||
refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
#[error("{message}")]
|
||||
pub struct RefreshTokenFailedError {
|
||||
pub reason: RefreshTokenFailedReason,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl RefreshTokenFailedError {
|
||||
pub fn new(reason: RefreshTokenFailedReason, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
reason,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RefreshTokenFailedReason {
|
||||
Expired,
|
||||
Exhausted,
|
||||
Revoked,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn classify_refresh_token_failure(body: &str) -> RefreshTokenFailedError {
|
||||
let code = extract_refresh_token_error_code(body);
|
||||
let reason = match code.as_deref().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("refresh_token_expired") => RefreshTokenFailedReason::Expired,
|
||||
Some("refresh_token_reused") => RefreshTokenFailedReason::Exhausted,
|
||||
Some("refresh_token_invalidated") => RefreshTokenFailedReason::Revoked,
|
||||
_ => RefreshTokenFailedReason::Other,
|
||||
};
|
||||
RefreshTokenFailedError::new(reason, "ChatGPT refresh token could not be refreshed")
|
||||
}
|
||||
|
||||
fn extract_refresh_token_error_code(body: &str) -> Option<String> {
|
||||
let Value::Object(map) = serde_json::from_str::<Value>(body).ok()? else {
|
||||
return None;
|
||||
};
|
||||
if let Some(error_value) = map.get("error") {
|
||||
match error_value {
|
||||
Value::Object(obj) => {
|
||||
if let Some(code) = obj.get("code").and_then(Value::as_str) {
|
||||
return Some(code.to_string());
|
||||
}
|
||||
}
|
||||
Value::String(code) => return Some(code.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
map.get("code").and_then(Value::as_str).map(str::to_string)
|
||||
}
|
||||
|
||||
fn try_parse_error_message(body: &str) -> String {
|
||||
serde_json::from_str::<Value>(body)
|
||||
.ok()
|
||||
.and_then(|value| value.get("error").cloned())
|
||||
.and_then(|error| match error {
|
||||
Value::String(message) => Some(message),
|
||||
Value::Object(mut map) => map
|
||||
.remove("message")
|
||||
.and_then(|message| message.as_str().map(ToString::to_string)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| body.to_string())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct IdClaims {
|
||||
#[serde(default)]
|
||||
email: Option<String>,
|
||||
#[serde(rename = "https://api.openai.com/profile", default)]
|
||||
profile: Option<ProfileClaims>,
|
||||
#[serde(rename = "https://api.openai.com/auth", default)]
|
||||
auth: Option<AuthClaims>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ProfileClaims {
|
||||
#[serde(default)]
|
||||
email: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AuthClaims {
|
||||
#[serde(default)]
|
||||
chatgpt_plan_type: Option<ChatGptPlanType>,
|
||||
#[serde(default)]
|
||||
chatgpt_user_id: Option<String>,
|
||||
#[serde(default)]
|
||||
user_id: Option<String>,
|
||||
#[serde(default)]
|
||||
chatgpt_account_id: Option<String>,
|
||||
#[serde(default)]
|
||||
chatgpt_account_is_fedramp: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum IdTokenInfoError {
|
||||
#[error("invalid ID token format")]
|
||||
InvalidFormat,
|
||||
#[error(transparent)]
|
||||
Base64(#[from] base64::DecodeError),
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
fn decode_jwt_payload<T: DeserializeOwned>(jwt: &str) -> Result<T, IdTokenInfoError> {
|
||||
let mut parts = jwt.split('.');
|
||||
let (_header_b64, payload_b64, _sig_b64) = match (parts.next(), parts.next(), parts.next()) {
|
||||
(Some(h), Some(p), Some(s)) if !h.is_empty() && !p.is_empty() && !s.is_empty() => (h, p, s),
|
||||
_ => return Err(IdTokenInfoError::InvalidFormat),
|
||||
};
|
||||
let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload_b64)?;
|
||||
Ok(serde_json::from_slice(&payload_bytes)?)
|
||||
}
|
||||
|
||||
pub fn parse_chatgpt_jwt_claims(jwt: &str) -> Result<IdTokenInfo, IdTokenInfoError> {
|
||||
let claims: IdClaims = decode_jwt_payload(jwt)?;
|
||||
let email = claims
|
||||
.email
|
||||
.or_else(|| claims.profile.and_then(|profile| profile.email));
|
||||
match claims.auth {
|
||||
Some(auth) => Ok(IdTokenInfo {
|
||||
email,
|
||||
raw_jwt: jwt.to_string(),
|
||||
chatgpt_plan_type: auth.chatgpt_plan_type,
|
||||
chatgpt_user_id: auth.chatgpt_user_id.or(auth.user_id),
|
||||
chatgpt_account_id: auth.chatgpt_account_id,
|
||||
chatgpt_account_is_fedramp: auth.chatgpt_account_is_fedramp,
|
||||
}),
|
||||
None => Ok(IdTokenInfo {
|
||||
email,
|
||||
raw_jwt: jwt.to_string(),
|
||||
chatgpt_plan_type: None,
|
||||
chatgpt_user_id: None,
|
||||
chatgpt_account_id: None,
|
||||
chatgpt_account_is_fedramp: false,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_id_token<'de, D>(deserializer: D) -> Result<IdTokenInfo, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(deserializer)?;
|
||||
parse_chatgpt_jwt_claims(&value).map_err(serde::de::Error::custom)
|
||||
}
|
||||
|
||||
fn serialize_id_token<S>(id_token: &IdTokenInfo, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&id_token.raw_jwt)
|
||||
}
|
||||
|
||||
pub mod default_client {
|
||||
use super::*;
|
||||
|
||||
pub fn build_reqwest_client() -> reqwest::Client {
|
||||
try_build_reqwest_client().unwrap_or_else(|error| {
|
||||
tracing::warn!(error = %error, "failed to build Epiphany OpenAI auth client");
|
||||
with_chatgpt_cloudflare_cookie_store(reqwest::Client::builder())
|
||||
.build()
|
||||
.unwrap_or_else(|_| reqwest::Client::new())
|
||||
})
|
||||
}
|
||||
|
||||
fn try_build_reqwest_client()
|
||||
-> Result<reqwest::Client, codex_client::BuildCustomCaTransportError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("originator", HeaderValue::from_static("epiphany"));
|
||||
let builder = reqwest::Client::builder()
|
||||
.user_agent(format!(
|
||||
"epiphany-openai-auth-spine/{}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
))
|
||||
.default_headers(headers);
|
||||
build_reqwest_client_with_custom_ca(with_chatgpt_cloudflare_cookie_store(builder))
|
||||
}
|
||||
}
|
||||
//! Epiphany's named boundary to the retained Codex-compatible auth organ.
|
||||
//!
|
||||
//! This crate intentionally does not clone Codex login behavior. Subscription auth,
|
||||
//! token refresh, keyring/file storage, originator headers, and model-provider auth
|
||||
//! identity remain owned by vendored `codex-login` so Epiphany stays a modified
|
||||
//! Codex-derived backend instead of a clean-room impersonator.
|
||||
|
||||
pub use codex_login::AuthConfig;
|
||||
pub use codex_login::AuthCredentialsStoreMode;
|
||||
pub use codex_login::AuthDotJson;
|
||||
pub use codex_login::AuthEnvTelemetry;
|
||||
pub use codex_login::AuthManager;
|
||||
pub use codex_login::AuthManagerConfig;
|
||||
pub use codex_login::AuthMode;
|
||||
pub use codex_login::CLIENT_ID;
|
||||
pub use codex_login::CODEX_API_KEY_ENV_VAR;
|
||||
pub use codex_login::CodexAuth;
|
||||
pub use codex_login::DeviceCode;
|
||||
pub use codex_login::ExternalAuth;
|
||||
pub use codex_login::ExternalAuthChatgptMetadata;
|
||||
pub use codex_login::ExternalAuthRefreshContext;
|
||||
pub use codex_login::ExternalAuthRefreshReason;
|
||||
pub use codex_login::ExternalAuthTokens;
|
||||
pub use codex_login::LoginServer;
|
||||
pub use codex_login::OPENAI_API_KEY_ENV_VAR;
|
||||
pub use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR;
|
||||
pub use codex_login::REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR;
|
||||
pub use codex_login::RefreshTokenError;
|
||||
pub use codex_login::ServerOptions;
|
||||
pub use codex_login::ShutdownHandle;
|
||||
pub use codex_login::TokenData;
|
||||
pub use codex_login::UnauthorizedRecovery;
|
||||
pub use codex_login::collect_auth_env_telemetry;
|
||||
pub use codex_login::complete_device_code_login;
|
||||
pub use codex_login::default_client;
|
||||
pub use codex_login::enforce_login_restrictions;
|
||||
pub use codex_login::load_auth_dot_json;
|
||||
pub use codex_login::login_with_api_key;
|
||||
pub use codex_login::logout;
|
||||
pub use codex_login::logout_with_revoke;
|
||||
pub use codex_login::read_openai_api_key_from_env;
|
||||
pub use codex_login::request_device_code;
|
||||
pub use codex_login::run_device_code_login;
|
||||
pub use codex_login::run_login_server;
|
||||
pub use codex_login::save_auth;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn api_key_auth_exposes_openai_token() {
|
||||
fn api_key_auth_exposes_openai_token_through_codex_login() {
|
||||
let auth = CodexAuth::from_api_key("sk-test");
|
||||
assert!(auth.is_api_key_auth());
|
||||
assert_eq!(auth.get_token().unwrap(), "sk-test");
|
||||
|
|
@ -873,11 +57,11 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn parses_minimal_api_key_auth_json() {
|
||||
fn parses_minimal_codex_auth_json_with_vendored_shape() {
|
||||
let auth: AuthDotJson =
|
||||
serde_json::from_str(r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk-test"}"#).unwrap();
|
||||
let built = build_auth(PathBuf::from("."), AuthCredentialsStoreMode::File, auth).unwrap();
|
||||
assert_eq!(built.auth_mode(), AuthMode::ApiKey);
|
||||
assert_eq!(auth.auth_mode, Some(AuthMode::ApiKey));
|
||||
assert_eq!(auth.openai_api_key.as_deref(), Some("sk-test"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -45,12 +45,12 @@ clean-room client pretending to be Codex.
|
|||
|
||||
### Transformations
|
||||
|
||||
- `epiphany-openai-auth-spine` currently loads env, file, keyring, and
|
||||
auto-fallback Codex auth, refreshes ChatGPT access tokens, preserves account
|
||||
metadata, and exposes the auth subset needed by the Epiphany OpenAI
|
||||
transport. This is now suspect because it has copied too much auth machinery
|
||||
out of vendored Codex; the spine should become a typed wrapper over retained
|
||||
Codex-compatible auth rather than a clean-room replacement.
|
||||
- `epiphany-openai-auth-spine` is now a thin Epiphany-named boundary over
|
||||
vendored `codex-login`. It re-exports Codex auth types and default-client
|
||||
construction instead of cloning env/file/keyring/token-refresh behavior.
|
||||
Subscription credential authority remains in retained Codex-compatible
|
||||
machinery; Epiphany owns only the typed status/request/event/runtime surfaces
|
||||
around it.
|
||||
- `epiphany-openai-codex-spine` converts `CodexAuth` directly into
|
||||
authorization/account headers, chooses the ChatGPT Codex backend or OpenAI API
|
||||
base URL from auth mode, builds a local serializable Responses request body,
|
||||
|
|
@ -97,9 +97,9 @@ clean-room client pretending to be Codex.
|
|||
vendored Codex auth semantics should remain the anchor for subscription use.
|
||||
If a later model catalog is needed, it should be a typed Epiphany catalog
|
||||
document, not a revival of the old Codex provider stack.
|
||||
- Native auth does not yet preserve every Codex auth mode. External bearer
|
||||
command auth and agent identity are legacy/reference gaps unless a concrete
|
||||
user path proves they are needed.
|
||||
- External bearer command auth and agent identity remain inside the retained
|
||||
vendored Codex auth organ. Epiphany should expose them only if a concrete
|
||||
typed runtime/status need appears; do not clone them into a second authority.
|
||||
|
||||
## Extract Target
|
||||
|
||||
|
|
@ -150,9 +150,11 @@ request body, resolves credentials through `epiphany-openai-auth-spine`, chooses
|
|||
ChatGPT/OpenAI base URL from auth mode, opens an HTTP Responses SSE stream with
|
||||
`codex-client`, and converts stream deltas/completion into typed
|
||||
`EpiphanyOpenAiStreamEvent` / `EpiphanyOpenAiModelReceipt` documents. It no
|
||||
longer directly or transitively imports `codex-login`, Codex
|
||||
`ResponsesApiRequest`, `ResponsesClient`, `ResponseEvent`, provider config,
|
||||
model-provider, app-server protocol, or protocol enums.
|
||||
longer imports Codex `ResponsesApiRequest`, `ResponsesClient`,
|
||||
`ResponseEvent`, provider config, model-provider, or broad app-server
|
||||
workflow. It intentionally reaches vendored `codex-login` only through
|
||||
`epiphany-openai-auth-spine` so auth identity remains Codex-compatible without
|
||||
letting Codex own Epiphany request/state shape.
|
||||
|
||||
The CultNet paperwork is now public too. `schemas/cultnet/` contains typed
|
||||
schemas for OpenAI adapter status, model request, stream event, and terminal
|
||||
|
|
@ -200,12 +202,13 @@ application. `codex-core` re-exports the contract only as a compatibility
|
|||
alias, and `CodexThread` now calls native state-update functions around its
|
||||
remaining revision check, persistence validation, and rollout/session writeback.
|
||||
|
||||
The credential extraction currently covers Codex file/keyring/auto auth plus
|
||||
env API keys, ChatGPT token refresh, account metadata, and header material
|
||||
without importing `codex-login`. That is technically clean but architecturally
|
||||
suspect under the compliance invariant above. The next corrective cut is to
|
||||
re-anchor auth in retained vendored Codex-compatible machinery while keeping
|
||||
Epiphany's typed adapter/status/request surfaces outside the Codex host brain.
|
||||
The credential extraction overcut has been corrected. The native clone of
|
||||
Codex file/keyring/auto auth, env API key handling, ChatGPT token refresh,
|
||||
account metadata parsing, and header-client setup was deleted from
|
||||
`epiphany-openai-auth-spine`; the crate now depends on vendored `codex-login`
|
||||
and carries the Codex workspace `tokio-tungstenite` / `tungstenite` patches
|
||||
needed for standalone builds. The remaining simplification target is not auth
|
||||
purity; it is the next Epiphany-in-vendor evacuation surface.
|
||||
|
||||
The point is ownership: Epiphany calls a model adapter; it does not live inside
|
||||
the Codex host brain.
|
||||
|
|
|
|||
|
|
@ -34,11 +34,11 @@ remembers doctrine; the branch remembers the blade.
|
|||
|
||||
- Do not copy exact branch or HEAD from this note. Run `git status --short --branch` and `git log --oneline -5`.
|
||||
- The active foundation directive is now `notes/codex-starvation-and-cultnet-liberation-plan.md`. The previous Codex app-server control-plane rebuild made Epiphany less rotten inside Codex, but that is not the destination. Epiphany must become a native CultCache/CultNet runtime while remaining an honest modified Codex-derived backend for subscription auth/model use. Codex is a compatibility reliquary for OpenAI subscription auth and model transport, not the host brain and not a mask for impersonation.
|
||||
- `notes/codex-auth-spine-inventory.md` is the source-grounded keeper list for that reliquary. Corrected compliance invariant: Codex-compatible auth identity should stay anchored in vendored Codex-derived auth machinery. The current `epiphany-openai-auth-spine` native credential implementation is technically clean but now suspect; it should become a typed wrapper over retained Codex auth rather than a clean-room replacement. Codex apps, skills, marketplace, plugin UX, broad app-server workflow, and JSON-RPC sprawl remain cuttable because they are not subscription-auth legitimacy.
|
||||
- `notes/codex-auth-spine-inventory.md` is the source-grounded keeper list for that reliquary. Corrected compliance invariant: Codex-compatible auth identity stays anchored in vendored Codex-derived auth machinery. `epiphany-openai-auth-spine` is now a thin Epiphany-named boundary over `codex-login`, not a clean-room clone of credential storage or token refresh. Codex apps, skills, marketplace, plugin UX, broad app-server workflow, and JSON-RPC sprawl remain cuttable because they are not subscription-auth legitimacy.
|
||||
- Edge JSON is allowed for schema description, hostile ingress before immediate typed parsing, sealed forensic artifacts, or named quarantine experiments. When both subsystems are ours, runtime data must remain typed CultCache documents and move over CultNet typed contracts. Generic `serde_json::Value` in worker launch/result/selfPatch/runtime flow is contamination until classified and replaced.
|
||||
- `epiphany-openai-runtime` worker result ingress now parses assistant output directly into typed role/reorient ingress structs selected from the durable launch document, stores nested `statePatch` and `selfPatch` as typed MessagePack in `EpiphanyRuntimeRoleWorkerResult`, and no longer passes worker result data through generic `serde_json::Value`. JSON survives there only as the OpenAI text-output edge before typed deserialization.
|
||||
- Agent self-memory review/application now has typed `AgentSelfPatch` core APIs. JSON-value selfPatch functions are compatibility wrappers for CLI/artifact ingress; native callers should parse once at the edge and then call `review_agent_self_patch_document` / `apply_agent_self_patch_document`.
|
||||
- `epiphany-openai-codex-spine` no longer uses Codex's Responses client, model-provider layer, `codex-api`, `codex-model-provider`, `codex-model-provider-info`, `codex-protocol`, or `codex-login` for outbound model requests. That cut may have gone too far on auth. Keep the typed request/status/event surfaces, but re-anchor credential loading/refresh in retained Codex-compatible auth before further transport purges.
|
||||
- `epiphany-openai-codex-spine` no longer uses Codex's Responses client, model-provider layer, `codex-api`, `codex-model-provider`, `codex-model-provider-info`, or `codex-protocol` for outbound model requests. It reaches `codex-login` only through `epiphany-openai-auth-spine` so credential loading/refresh stays Codex-compatible while request/status/event/runtime surfaces stay typed Epiphany documents.
|
||||
- Durable Epiphany state types now live in root crate `epiphany-state-model`. `codex-protocol` re-exports them only so old rollout/API callers keep compiling; do not add new durable `Epiphany*` state structs under `vendor/codex`. `epiphany-core` imports the native model directly and no longer depends on `codex-protocol`. Pressure derives from native `EpiphanyTokenUsageSnapshot`; Codex token telemetry is mapped at the bridge. Codex rollout/event reconstruction now lives in `codex-core::epiphany_rollout`, where the Codex `RolloutItem` / `EventMsg` types belong. Exact retrieval path matching is native to `epiphany-core`, so `epiphany-core` has no direct vendored Codex crate dependency.
|
||||
- The May 2026 foundation migration in `notes/epiphany-ideal-architecture-rebuild-plan.md` is complete enough to defend. Read `notes/epiphany-architectural-teardown.md` before touching Epiphany control-plane code, but do not treat it as an open-ended excuse to keep shaving the altar. The rebuild moved scene projection, freshness derivation, pressure policy, targeted context shards, bounded graph traversal, job/progress view derivation, planning view derivation, reorientation resume/regather verdict policy, pure CRRC recommendation policy, fixed-lane coordinator decision policy, role-board projection policy, role/reorient result interpretation, role self-persistence review policy, and role/reorient acceptance bundle policy into `epiphany-core`; typed acceptance receipts replaced summary-string identity for live accept paths, runtime links are dual-written on launch, and result read-back now prefers runtime links.
|
||||
- Read `notes/epiphany-ideal-architecture-rebuild-plan.md` immediately after the teardown. It defines the smallest coherent replacement architecture: durable `EpiphanyState`, runtime-spine-owned `RuntimeState`, separate role memory/heartbeat state, `epiphany-core` as policy owner, app-server as adapter, Aquarium as reflector, typed acceptance receipts, and derived view lenses instead of a protocol verb zoo.
|
||||
|
|
@ -560,9 +560,9 @@ dependency and no generic JSON payload. A direct standalone `codex-core` path
|
|||
dependency attempt hit transitive dependency skew outside the vendored Codex
|
||||
workspace lock; do not "fix" that with random version pins. The first
|
||||
workspace-verified wrapper now exists as `epiphany-openai-codex-spine`: it
|
||||
depends on the pure typed adapter plus the Epiphany-owned auth spine and
|
||||
projects `AuthManager` / `CodexAuth` into a typed
|
||||
`EpiphanyOpenAiAdapterStatus`.
|
||||
depends on the pure typed adapter plus the Epiphany-named auth spine, which now
|
||||
re-exports retained vendored `codex-login`, and projects `AuthManager` /
|
||||
`CodexAuth` into a typed `EpiphanyOpenAiAdapterStatus`.
|
||||
`epiphany-codex-bridge` re-exports that spine so the current app-server shell
|
||||
can compile the attachment without contaminating the pure document crate. The
|
||||
same spine now owns the HTTP Responses transport wrapper without Codex's
|
||||
|
|
@ -571,22 +571,23 @@ documents map into a local serializable Responses body, auth comes from
|
|||
`epiphany-openai-auth-spine`, the stream opens through `codex-client`, and
|
||||
Responses SSE frames parse back into typed `EpiphanyOpenAiStreamEvent` and
|
||||
`EpiphanyOpenAiModelReceipt` documents. The spine no longer directly or
|
||||
transitively depends on `codex-login`, `codex-app-server-protocol`,
|
||||
`codex-protocol`, `codex-api`, `codex-model-provider`, or
|
||||
`codex-model-provider-info`. The CultNet schema
|
||||
transitively depends on Codex's Responses client, model-provider stack, or
|
||||
`codex-protocol`; it intentionally reaches `codex-login` through the retained
|
||||
auth boundary. The CultNet schema
|
||||
catalog advertises OpenAI adapter status, model request, stream event, and
|
||||
receipt document types plus the coordinator-owned model request contract. The
|
||||
remaining auth caveat is functional, not architectural: external bearer command
|
||||
auth and agent identity are not implemented natively yet.
|
||||
remaining auth caveat is exposure, not ownership: external bearer command auth
|
||||
and agent identity remain in the retained vendored auth organ until a typed
|
||||
Epiphany surface actually needs them.
|
||||
|
||||
The `epiphany-openai-spine` binary is now the first native edge for that
|
||||
wrapper. It can print typed adapter status and consume a serialized
|
||||
`EpiphanyOpenAiModelRequest` document for a model turn outside Codex
|
||||
app-server. Treat its JSON as CLI/file-edge serialization of typed documents,
|
||||
not internal data cargo. The native request path no longer pulls `codex-login`
|
||||
or `codex-api`; the next real cut is deciding whether external bearer or
|
||||
agent-identity auth deserves native implementation or remains sealed legacy
|
||||
Codex compatibility.
|
||||
not internal data cargo. The native request path no longer pulls `codex-api`;
|
||||
`codex-login` remains deliberately sealed behind `epiphany-openai-auth-spine`.
|
||||
The next real cut is another Epiphany-in-vendor evacuation surface, not a
|
||||
second attempt to clone Codex auth.
|
||||
|
||||
The native runtime no longer imports `codex-login` directly. The Codex spine now
|
||||
exports the `default_codex_home` and `auth_manager` helpers, and those helpers
|
||||
|
|
@ -611,8 +612,9 @@ Codex worker execution. `roleResult` and `reorientResult` now require those
|
|||
typed worker result documents; generic runtime job summaries are lifecycle
|
||||
receipts, not reviewable findings.
|
||||
The next cut is no longer `codex-login` weight or keyring support in this
|
||||
spine; it is either native external bearer/agent-identity auth support or the
|
||||
next Epiphany-in-vendor evacuation surface.
|
||||
spine; the auth reliquary has been re-anchored. Continue with the next
|
||||
Epiphany-in-vendor evacuation surface unless a concrete typed status/runtime
|
||||
need demands external bearer or agent-identity exposure.
|
||||
|
||||
That coordinator cut is now landed for the MVP runner. `epiphany-mvp-coordinator`
|
||||
accepts `--openai-runtime-bin`, resolves the local `epiphany-openai-runtime`
|
||||
|
|
@ -795,13 +797,11 @@ request. `epiphany_automation.rs` still gathers live host facts and executes
|
|||
the host side effects: submit `Op::Compact`, call `epiphany_launch_job`, and
|
||||
emit JSON-RPC state-update notifications.
|
||||
|
||||
The native OpenAI auth spine currently no longer depends on the vendored
|
||||
`codex-keyring-store` wrapper and uses the standard `keyring` crate directly
|
||||
while keeping Codex's `Codex Auth` service name and `cli|{sha256 path prefix}`
|
||||
store key. Treat that as an overcleaned technical state, not doctrine. The next
|
||||
auth cut should re-anchor auth in retained vendored Codex-compatible machinery
|
||||
so Epiphany remains a modified Codex backend rather than a clean-room
|
||||
impersonator.
|
||||
The native OpenAI auth spine overcut has been corrected. It no longer owns a
|
||||
clone of Codex keyring/file/env auth or ChatGPT token refresh; it re-exports
|
||||
vendored `codex-login` and carries the Codex workspace tungstenite patches
|
||||
needed for standalone builds. This is intentional impurity: a sealed
|
||||
Codex-compatible auth organ, not workflow authority.
|
||||
|
||||
The MCP config path is now product-quarantined. `Config::to_mcp_config` keeps
|
||||
user-declared MCP servers but no longer accepts a `PluginsManager`, folds
|
||||
|
|
|
|||
Binary file not shown.
File diff suppressed because one or more lines are too long
11
vendor/codex/codex-rs/Cargo.lock
generated
vendored
11
vendor/codex/codex-rs/Cargo.lock
generated
vendored
|
|
@ -5134,17 +5134,8 @@ dependencies = [
|
|||
name = "epiphany-openai-auth-spine"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"codex-client",
|
||||
"keyring",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"codex-login",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
Reference in a new issue