1use serde::{Deserialize, Serialize};
2use std::error::Error;
3use std::path::Path;
4
5pub struct ApiClient {
6 base_url: String,
7 api_key: Option<String>,
8 client: reqwest::Client,
9}
10
11#[derive(Serialize)]
12pub struct RegisterRepoRequest {
13 pub repo_name: String,
14 pub github_url: Option<String>,
15}
16
17#[derive(Deserialize)]
18pub struct RegisterRepoResponse {
19 pub repo_id: uuid::Uuid,
20}
21
22#[derive(Deserialize)]
23pub struct DeviceAuthResponse {
24 pub token: String,
25}
26
27#[derive(Deserialize)]
28pub struct DeviceStatusResponse {
29 pub status: String,
30 pub token: Option<String>,
31 pub email: Option<String>,
32}
33
34#[derive(Debug, Serialize)]
35pub struct CheckPoliciesRequest {
36 pub sessions: Vec<SessionCheckData>,
37}
38
39#[derive(Debug, Serialize)]
40pub struct SessionCheckData {
41 pub session_id: String,
42 pub tool_calls: Option<serde_json::Value>,
43 pub files_modified: Option<Vec<String>>,
44 pub total_tool_calls: Option<i32>,
45}
46
47#[derive(Debug, Deserialize)]
48pub struct CheckPoliciesResponse {
49 pub passed: bool,
50 pub results: Vec<CheckResultItem>,
51 pub blocked: bool,
52}
53
54#[derive(Debug, Deserialize)]
55pub struct CheckResultItem {
56 pub rule_name: String,
57 pub result: String,
58 pub action: String,
59 pub severity: String,
60 pub details: String,
61}
62
63#[derive(Debug, Deserialize)]
64pub struct RepoListItem {
65 pub id: uuid::Uuid,
66 pub name: String,
67 #[serde(default)]
68 pub github_url: Option<String>,
69 #[serde(default)]
70 pub clone_status: Option<String>,
71}
72
73#[derive(Debug, Deserialize)]
74pub struct MeResponse {
75 #[allow(dead_code)]
76 pub user_id: uuid::Uuid,
77 pub email: String,
78 pub name: Option<String>,
79}
80
81#[derive(Debug)]
82pub enum GetMeError {
83 Unauthorized,
85 Network(String),
87 Server(String),
89}
90
91impl std::fmt::Display for GetMeError {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 match self {
94 Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
95 Self::Network(m) => write!(f, "network error: {m}"),
96 Self::Server(m) => write!(f, "server error: {m}"),
97 }
98 }
99}
100
101impl std::error::Error for GetMeError {}
102
103#[derive(Debug, Serialize)]
104pub struct CiVerifyRequest {
105 pub commits: Vec<String>,
106}
107
108#[derive(Debug, Deserialize)]
109pub struct CiVerifyResponse {
110 pub status: String,
111 pub total_commits: usize,
112 pub registered_commits: usize,
113 pub sealed_commits: usize,
114 pub policy_passed_commits: usize,
115 pub results: Vec<CommitVerifyResult>,
116}
117
118#[derive(Debug, Deserialize)]
119pub struct CommitVerifyResult {
120 pub commit_sha: String,
121 pub status: String,
122 pub registered: bool,
123 pub sealed: bool,
124 pub signature_valid: bool,
125 pub chain_valid: bool,
126 pub policy_results: Vec<CiPolicyResult>,
127}
128
129#[derive(Debug, Deserialize)]
130pub struct CiPolicyResult {
131 pub rule_name: String,
132 pub result: String,
133 pub action: String,
134 pub severity: String,
135 pub details: String,
136}
137
138impl ApiClient {
139 pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
140 Self {
141 base_url: base_url.trim_end_matches('/').to_string(),
142 api_key: api_key.map(String::from),
143 client: reqwest::Client::new(),
144 }
145 }
146
147 pub async fn register_repo(
148 &self,
149 org_slug: &str,
150 req: RegisterRepoRequest,
151 ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
152 let mut builder = self
153 .client
154 .post(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
155
156 if let Some(key) = &self.api_key {
157 builder = builder.header("Authorization", format!("Bearer {key}"));
158 }
159
160 let resp = builder.json(&req).send().await?;
161
162 if !resp.status().is_success() {
163 let status = resp.status();
164 let body = resp.text().await.unwrap_or_default();
165 return Err(format!("Server returned {status}: {body}").into());
166 }
167
168 Ok(resp.json().await?)
169 }
170
171 pub async fn device_start(&self) -> Result<DeviceAuthResponse, Box<dyn Error>> {
172 let resp = self
173 .client
174 .post(format!("{}/api/v1/auth/device", self.base_url))
175 .send()
176 .await?;
177
178 if !resp.status().is_success() {
179 let status = resp.status();
180 let body = resp.text().await.unwrap_or_default();
181 return Err(format!("Server returned {status}: {body}").into());
182 }
183
184 Ok(resp.json().await?)
185 }
186
187 pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
188 let resp = self
189 .client
190 .get(format!(
191 "{}/api/v1/auth/device/{token}/status",
192 self.base_url
193 ))
194 .send()
195 .await?;
196
197 if !resp.status().is_success() {
198 let status = resp.status();
199 let body = resp.text().await.unwrap_or_default();
200 return Err(format!("Server returned {status}: {body}").into());
201 }
202
203 Ok(resp.json().await?)
204 }
205
206 pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
207 let mut builder = self
208 .client
209 .post(format!("{}/api/v1/auth/logout", self.base_url));
210 if let Some(key) = &self.api_key {
211 builder = builder.header("Authorization", format!("Bearer {key}"));
212 }
213 let resp = builder.send().await?;
214 if !resp.status().is_success() {
215 let status = resp.status();
216 let body = resp.text().await.unwrap_or_default();
217 return Err(format!("Server returned {status}: {body}").into());
218 }
219 Ok(())
220 }
221
222 pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
226 let mut builder = self.client.get(format!("{}/api/v1/auth/me", self.base_url));
227 if let Some(key) = &self.api_key {
228 builder = builder.header("Authorization", format!("Bearer {key}"));
229 }
230
231 let resp = builder
232 .send()
233 .await
234 .map_err(|e| GetMeError::Network(e.to_string()))?;
235
236 let status = resp.status();
237 if status == reqwest::StatusCode::UNAUTHORIZED {
238 return Err(GetMeError::Unauthorized);
239 }
240 if !status.is_success() {
241 let body = resp.text().await.unwrap_or_default();
242 return Err(GetMeError::Server(format!("{status}: {body}")));
243 }
244
245 resp.json::<MeResponse>()
246 .await
247 .map_err(|e| GetMeError::Server(e.to_string()))
248 }
249
250 pub async fn list_repos(&self, org_slug: &str) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
251 let mut builder = self
252 .client
253 .get(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
254 if let Some(key) = &self.api_key {
255 builder = builder.header("Authorization", format!("Bearer {key}"));
256 }
257
258 let resp = builder.send().await?;
259
260 if !resp.status().is_success() {
261 let status = resp.status();
262 let body = resp.text().await.unwrap_or_default();
263 return Err(format!("Failed to list repos ({status}): {body}").into());
264 }
265
266 let repos: Vec<RepoListItem> = resp.json().await?;
267 Ok(repos)
268 }
269
270 pub async fn verify_commits(
271 &self,
272 org_slug: &str,
273 repo_id: &uuid::Uuid,
274 req: CiVerifyRequest,
275 ) -> Result<CiVerifyResponse, Box<dyn Error>> {
276 let mut builder = self.client.post(format!(
277 "{}/api/v1/orgs/{}/repos/{}/ci/verify",
278 self.base_url, org_slug, repo_id
279 ));
280 if let Some(key) = &self.api_key {
281 builder = builder.header("Authorization", format!("Bearer {key}"));
282 }
283
284 let resp = builder.json(&req).send().await?;
285
286 if !resp.status().is_success() {
287 let status = resp.status();
288 let body = resp.text().await.unwrap_or_default();
289 return Err(format!("CI verify failed ({status}): {body}").into());
290 }
291
292 Ok(resp.json().await?)
293 }
294
295 pub async fn push_commit(
296 &self,
297 org_slug: &str,
298 repo_id: &str,
299 req: &tracevault_core::streaming::CommitPushRequest,
300 ) -> Result<tracevault_core::streaming::CommitPushResponse, Box<dyn Error>> {
301 let mut builder = self.client.post(format!(
302 "{}/api/v1/orgs/{}/repos/{}/commits",
303 self.base_url, org_slug, repo_id
304 ));
305 if let Some(key) = &self.api_key {
306 builder = builder.header("Authorization", format!("Bearer {key}"));
307 }
308 let resp = builder.json(req).send().await?;
309 if !resp.status().is_success() {
310 let status = resp.status();
311 let body = resp.text().await.unwrap_or_default();
312 return Err(format!("Commit push failed ({status}): {body}").into());
313 }
314 Ok(resp.json().await?)
315 }
316
317 pub async fn stream_event(
318 &self,
319 org_slug: &str,
320 repo_id: &str,
321 req: &tracevault_core::streaming::StreamEventRequest,
322 ) -> Result<tracevault_core::streaming::StreamEventResponse, Box<dyn Error>> {
323 let mut builder = self.client.post(format!(
324 "{}/api/v1/orgs/{}/repos/{}/stream",
325 self.base_url, org_slug, repo_id
326 ));
327 if let Some(key) = &self.api_key {
328 builder = builder.header("Authorization", format!("Bearer {key}"));
329 }
330 let resp = builder.json(req).send().await?;
331 if !resp.status().is_success() {
332 let status = resp.status();
333 let body = resp.text().await.unwrap_or_default();
334 return Err(format!("Stream failed ({status}): {body}").into());
335 }
336 Ok(resp.json().await?)
337 }
338
339 pub async fn check_policies(
340 &self,
341 org_slug: &str,
342 repo_id: &uuid::Uuid,
343 req: CheckPoliciesRequest,
344 ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
345 let mut builder = self.client.post(format!(
346 "{}/api/v1/orgs/{}/repos/{}/policies/check",
347 self.base_url, org_slug, repo_id
348 ));
349 if let Some(key) = &self.api_key {
350 builder = builder.header("Authorization", format!("Bearer {key}"));
351 }
352
353 let resp = builder.json(&req).send().await?;
354
355 if !resp.status().is_success() {
356 let status = resp.status();
357 let body = resp.text().await.unwrap_or_default();
358 return Err(format!("Policy check failed ({status}): {body}").into());
359 }
360
361 let result: CheckPoliciesResponse = resp.json().await?;
362 Ok(result)
363 }
364}
365
366pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
370 use crate::credentials::Credentials;
371
372 let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
374
375 let creds = Credentials::load();
377
378 let config_path = crate::config::TracevaultConfig::config_path(project_root);
380 let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
381
382 let config_server_url = config_content
383 .lines()
384 .find(|l| l.starts_with("server_url"))
385 .and_then(|l| l.split('=').nth(1))
386 .map(|s| s.trim().trim_matches('"').to_string());
387
388 let config_api_key = config_content
389 .lines()
390 .find(|l| l.starts_with("api_key"))
391 .and_then(|l| l.split('=').nth(1))
392 .map(|s| s.trim().trim_matches('"').to_string());
393
394 let server_url = std::env::var("TRACEVAULT_SERVER_URL")
396 .ok()
397 .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
398 .or(config_server_url);
399
400 let token = env_key
402 .or_else(|| creds.map(|c| c.token))
403 .or(config_api_key);
404
405 (server_url, token)
406}