use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use oneharness_core::io::usage::{CLAUDE_IDENTITY_ENV, CODEX_IDENTITY_ENV};
use crate::config::{ConfigError, EnvAssignment, HarnessIdentity};
pub const HARNESS_DIRECTORY: &str = "harness";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HarnessSignIn {
identity: &'static str,
config_env: &'static str,
program: &'static str,
arguments: &'static [&'static str],
npm_program: Option<&'static str>,
}
pub const SIGN_INS: [HarnessSignIn; 2] = [
HarnessSignIn {
identity: "claude-code",
config_env: CLAUDE_IDENTITY_ENV,
program: "claude",
arguments: &["auth", "login"],
npm_program: Some("node_modules/@anthropic-ai/claude-code/bin/claude.exe"),
},
HarnessSignIn {
identity: "codex",
config_env: CODEX_IDENTITY_ENV,
program: "codex",
arguments: &["login", "--device-auth"],
npm_program: None,
},
];
impl HarnessSignIn {
#[must_use]
pub fn of(harness: &HarnessIdentity) -> Option<&'static Self> {
SIGN_INS
.iter()
.find(|entry| entry.identity == harness.as_str())
}
#[must_use]
pub fn supported() -> Vec<&'static str> {
SIGN_INS.iter().map(|entry| entry.identity).collect()
}
#[must_use]
pub const fn identity(&self) -> &'static str {
self.identity
}
#[must_use]
pub const fn config_env(&self) -> &'static str {
self.config_env
}
#[must_use]
pub const fn program(&self) -> &'static str {
self.program
}
#[must_use]
pub const fn arguments(&self) -> &'static [&'static str] {
self.arguments
}
#[must_use]
pub fn program_behind_launcher(&self, path: &OsStr) -> Option<PathBuf> {
let relative = self.npm_program?;
let native = format!("{}{}", self.program, std::env::consts::EXE_SUFFIX);
let launcher = format!("{}.cmd", self.program);
let mut behind = None;
for directory in std::env::split_paths(path) {
if directory.join(&native).is_file() {
return None;
}
if behind.is_none() && directory.join(&launcher).is_file() {
behind = Some(directory.join(relative)).filter(|program| program.is_file());
}
}
behind
}
#[must_use]
pub fn program_on(&self, path: &OsStr) -> PathBuf {
self.program_behind_launcher(path)
.unwrap_or_else(|| PathBuf::from(self.program))
}
#[must_use]
pub fn directory(&self, state_dir: &Path) -> PathBuf {
state_dir.join(HARNESS_DIRECTORY).join(self.identity)
}
pub fn prepare(&self, state_dir: &Path) -> std::io::Result<PathBuf> {
let directory = self.directory(state_dir);
for level in [state_dir.join(HARNESS_DIRECTORY), directory.clone()] {
real_directory(&level)?;
#[cfg(unix)]
std::fs::set_permissions(
&level,
std::os::unix::fs::PermissionsExt::from_mode(PRIVATE_DIRECTORY),
)?;
}
Ok(directory)
}
pub fn assignment(&self, directory: &Path) -> Result<EnvAssignment, ConfigError> {
EnvAssignment::new(&format!("{}={}", self.config_env, directory.display()))
}
}
#[cfg(unix)]
const PRIVATE_DIRECTORY: u32 = 0o700;
fn real_directory(path: &Path) -> std::io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(found) if found.is_dir() => Ok(()),
Ok(_) => Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{} is something other than a directory", path.display()),
)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => create_directory(path),
Err(error) => Err(error),
}
}
#[cfg(unix)]
fn create_directory(path: &Path) -> std::io::Result<()> {
use std::os::unix::fs::DirBuilderExt as _;
std::fs::DirBuilder::new()
.mode(PRIVATE_DIRECTORY)
.create(path)
}
#[cfg(not(unix))]
fn create_directory(path: &Path) -> std::io::Result<()> {
std::fs::create_dir(path)
}
#[cfg(test)]
mod tests {
use oneharness_core::io::usage::{CLAUDE_IDENTITY_ENV, CODEX_IDENTITY_ENV};
use super::{HARNESS_DIRECTORY, HarnessSignIn, SIGN_INS};
use crate::config::HarnessIdentity;
#[test]
fn the_table_carries_claude_code_and_codex_under_oneharnesss_own_variables() {
let found: Vec<(&str, &str)> = SIGN_INS
.iter()
.map(|entry| (entry.identity(), entry.config_env()))
.collect();
assert_eq!(
found,
vec![
("claude-code", CLAUDE_IDENTITY_ENV),
("codex", CODEX_IDENTITY_ENV)
]
);
}
#[test]
fn every_identity_is_one_oneharness_runs() {
for entry in &SIGN_INS {
let spec = oneharness_core::domain::harness::by_id(entry.identity())
.unwrap_or_else(|| panic!("OneHarness runs no `{}`", entry.identity()));
assert_eq!(entry.program(), spec.default_bin);
assert!(
!entry.arguments().is_empty(),
"`{}` declares no sign-in",
entry.identity()
);
}
}
#[test]
fn a_harness_outside_the_table_has_no_entry() {
let codex = HarnessIdentity::new("codex").expect("an identity");
let copilot = HarnessIdentity::new("copilot").expect("an identity");
assert_eq!(
HarnessSignIn::of(&codex).map(HarnessSignIn::identity),
Some("codex")
);
assert_eq!(HarnessSignIn::of(&copilot), None);
assert_eq!(HarnessSignIn::supported(), vec!["claude-code", "codex"]);
}
#[test]
fn the_directory_is_created_private_under_the_state_directory() {
let state = std::env::temp_dir().join(format!(
"printobserver-sign-in-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("the clock is past the epoch")
.as_nanos()
));
let entry = &SIGN_INS[0];
std::fs::create_dir_all(&state).expect("a state directory");
let prepared = entry.prepare(&state).expect("the directory is created");
assert_eq!(prepared, state.join(HARNESS_DIRECTORY).join("claude-code"));
assert!(prepared.is_dir(), "no directory was created");
#[cfg(unix)]
{
let mode = mode_of(&prepared);
assert_eq!(mode, 0o700, "the directory is mode {mode:o}");
}
std::fs::write(prepared.join("signed-in"), "kept").expect("the directory is writable");
#[cfg(unix)]
std::fs::set_permissions(
&prepared,
std::os::unix::fs::PermissionsExt::from_mode(0o755),
)
.expect("the directory is widened");
let again = entry.prepare(&state).expect("the directory is there");
#[cfg(unix)]
{
let narrowed = mode_of(&again);
assert_eq!(
narrowed, 0o700,
"a widened directory was left mode {narrowed:o}"
);
}
let kept = std::fs::read_to_string(again.join("signed-in"));
let assigned = entry.assignment(&again).map(|found| found.to_string());
let elsewhere = state.join("elsewhere");
std::fs::create_dir_all(&elsewhere).expect("a directory to point at");
std::fs::create_dir_all(state.join(HARNESS_DIRECTORY)).expect("the harness level");
link_directory(&elsewhere, &SIGN_INS[1].directory(&state));
let through_a_symlink = SIGN_INS[1].prepare(&state).map_err(|error| error.kind());
let linked_state = state.join("linked-state");
std::fs::create_dir_all(&linked_state).expect("a second state directory");
link_directory(&elsewhere, &linked_state.join(HARNESS_DIRECTORY));
let through_a_linked_level = entry.prepare(&linked_state).map_err(|error| error.kind());
std::fs::remove_dir_all(&state).expect("the state directory is removable");
assert_eq!(kept.expect("what it held is kept"), "kept");
assert_eq!(
through_a_symlink,
Err(std::io::ErrorKind::InvalidInput),
"a symlink in the directory's place was prepared"
);
assert_eq!(
through_a_linked_level,
Err(std::io::ErrorKind::InvalidInput),
"a symlink in the harness level's place was followed"
);
assert_eq!(
assigned.expect("an assignment"),
format!("{CLAUDE_IDENTITY_ENV}={}", again.display())
);
}
#[cfg(unix)]
fn mode_of(path: &std::path::Path) -> u32 {
use std::os::unix::fs::PermissionsExt as _;
std::fs::metadata(path)
.expect("the directory is there")
.permissions()
.mode()
& 0o777
}
fn link_directory(target: &std::path::Path, link: &std::path::Path) {
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(target, link);
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_dir(target, link);
linked.expect("a symlink where a directory belongs");
}
}