返回 CodeWhale
claude_org.rs
根目录 / crates / account-cli / src / claude_org.rs
1 use chrono::{DateTime, Utc};
2 use codewhale_config::credentials::CLAUDE_ORG_LINK_COMMAND;
3
4 use super::*;
5
6 const TOKEN_PATH: &str = "/api/claude-billing/token";
7 const LINK_PATH: &str = "/api/claude-billing/link";
8 const STATUS_PATH: &str = "/api/claude-billing";
9 const LINK_START_PATH: &str = "/api/claude-billing/start";
10 const TOKEN_REFRESH_MARGIN_SECS: i64 = 120;
11 const LINK_POLL_INTERVAL: Duration = Duration::from_secs(3);
12
13 #[derive(Debug, Args)]
14 pub(crate) struct ClaudeOrgArgs {
15 #[command(subcommand)]
16 command: ClaudeOrgCommand,
17 }
18
19 #[derive(Debug, Subcommand)]
20 enum ClaudeOrgCommand {
21 /// Link a Claude Platform organization so Anthropic bills it directly.
22 Link(ClaudeOrgLinkArgs),
23 /// Show whether a Claude Platform organization is linked.
24 Status,
25 /// Remove the Claude Platform organization link.
26 Unlink,
27 }
28
29 #[derive(Debug, Args)]
30 struct ClaudeOrgLinkArgs {
31 /// Print the authorization URL without trying to open a browser.
32 #[arg(long, default_value_t = false)]
33 no_open: bool,
34 /// Maximum time to wait for the browser authorization to finish.
35 #[arg(
36 long = "timeout-seconds",
37 default_value_t = DEFAULT_LOGIN_TIMEOUT_SECONDS,
38 value_parser = clap::value_parser!(u64).range(1..=MAX_LOGIN_TIMEOUT_SECONDS)
39 )]
40 timeout_seconds: u64,
41 }
42
43 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
44 pub enum ClaudeOrgErrorKind {
45 NotSignedIn,
46 NotLinked,
47 RelinkRequired,
48 Disabled,
49 AlreadyLinkedElsewhere,
50 Unavailable,
51 Invalid,
52 }
53
54 #[derive(Debug)]
55 pub struct ClaudeOrgError {
56 pub kind: ClaudeOrgErrorKind,
57 message: String,
58 }
59
60 impl ClaudeOrgError {
61 #[must_use]
62 pub fn with_message(kind: ClaudeOrgErrorKind, message: impl Into<String>) -> Self {
63 Self {
64 kind,
65 message: message.into(),
66 }
67 }
68
69 #[must_use]
70 pub fn new(kind: ClaudeOrgErrorKind) -> Self {
71 let message = match kind {
72 ClaudeOrgErrorKind::NotSignedIn => {
73 "Sign in to Codewhale to use your linked Claude organization: run `codewhale login`."
74 .to_string()
75 }
76 ClaudeOrgErrorKind::NotLinked => format!(
77 "No Claude organization is linked to your Codewhale account. Link one with `{CLAUDE_ORG_LINK_COMMAND}`."
78 ),
79 ClaudeOrgErrorKind::RelinkRequired => format!(
80 "Your Claude organization link ended. Link again with `{CLAUDE_ORG_LINK_COMMAND}`."
81 ),
82 ClaudeOrgErrorKind::Disabled => {
83 "Claude organization billing is not available for this Codewhale account."
84 .to_string()
85 }
86 ClaudeOrgErrorKind::AlreadyLinkedElsewhere => {
87 "This Claude organization is already linked to another Codewhale account."
88 .to_string()
89 }
90 ClaudeOrgErrorKind::Unavailable => {
91 "Claude organization billing is temporarily unavailable at Codewhale. Try again shortly."
92 .to_string()
93 }
94 ClaudeOrgErrorKind::Invalid => {
95 "The Codewhale service returned an invalid Claude organization token.".to_string()
96 }
97 };
98 Self { kind, message }
99 }
100 }
101
102 impl std::fmt::Display for ClaudeOrgError {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.write_str(&self.message)
105 }
106 }
107
108 impl std::error::Error for ClaudeOrgError {}
109
110 #[derive(Clone)]
111 pub struct ClaudeOrgToken {
112 pub account: Option<(String, String)>,
113 pub access_token: String,
114 pub expires_at: DateTime<Utc>,
115 pub base_url: String,
116 pub anthropic_version: String,
117 pub user_profile_id: Option<String>,
118 }
119
120 impl std::fmt::Debug for ClaudeOrgToken {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 f.debug_struct("ClaudeOrgToken")
123 .field("access_token", &"<redacted>")
124 .field("expires_at", &self.expires_at)
125 .field("base_url", &self.base_url)
126 .field("anthropic_version", &self.anthropic_version)
127 .field("user_profile_id", &self.user_profile_id)
128 .finish()
129 }
130 }
131
132 impl ClaudeOrgToken {
133 #[must_use]
134 pub fn is_fresh_at(&self, now: DateTime<Utc>) -> bool {
135 self.expires_at.timestamp() - now.timestamp() > TOKEN_REFRESH_MARGIN_SECS
136 }
137 }
138
139 #[derive(Deserialize)]
140 #[serde(rename_all = "camelCase")]
141 struct TokenWire {
142 token_type: String,
143 access_token: String,
144 expires_at: String,
145 base_url: String,
146 anthropic_version: String,
147 user_profile_id: Option<String>,
148 }
149
150 #[derive(Deserialize)]
151 #[serde(rename_all = "camelCase")]
152 struct LinkStart {
153 authorization_url: String,
154 }
155
156 #[derive(Clone, Debug, Deserialize)]
157 #[serde(rename_all = "camelCase")]
158 pub struct ClaudeOrgLinkStatus {
159 pub available: bool,
160 pub linked: bool,
161 pub linked_at: Option<String>,
162 #[serde(default)]
163 last_link_failure: Option<LinkFailureWire>,
164 }
165
166 #[derive(Clone, Debug, Deserialize)]
167 struct LinkFailureWire {
168 code: String,
169 at: String,
170 }
171
172 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
173 pub enum ClaudeOrgLinkFailure {
174 Declined,
175 AlreadyLinkedElsewhere,
176 Failed,
177 }
178
179 const LINK_FAILURE_CLOCK_SKEW_SECS: i64 = 60;
180
181 impl ClaudeOrgLinkStatus {
182 #[must_use]
183 pub fn failure_since(&self, started: DateTime<Utc>) -> Option<ClaudeOrgLinkFailure> {
184 if self.linked {
185 return None;
186 }
187 let failure = self.last_link_failure.as_ref()?;
188 let at = DateTime::parse_from_rfc3339(&failure.at)
189 .ok()?
190 .with_timezone(&Utc);
191 if at.timestamp() < started.timestamp() - LINK_FAILURE_CLOCK_SKEW_SECS {
192 return None;
193 }
194 Some(match failure.code.as_str() {
195 "declined" => ClaudeOrgLinkFailure::Declined,
196 "already_linked_elsewhere" => ClaudeOrgLinkFailure::AlreadyLinkedElsewhere,
197 _ => ClaudeOrgLinkFailure::Failed,
198 })
199 }
200 }
201
202 #[derive(Deserialize)]
203 #[serde(rename_all = "camelCase")]
204 struct UnlinkResult {
205 revoked: bool,
206 message: Option<String>,
207 }
208
209 pub(crate) fn claude_org_token_from_response(
210 response: &CloudResponse,
211 ) -> std::result::Result<ClaudeOrgToken, ClaudeOrgError> {
212 if response.status != 200 {
213 return Err(claude_org_error(response));
214 }
215 let invalid = || ClaudeOrgError::new(ClaudeOrgErrorKind::Invalid);
216 let wire: TokenWire = serde_json::from_slice(&response.body).map_err(|_| invalid())?;
217 let header_safe = |value: &str| {
218 !value.is_empty()
219 && value.len() <= 8192
220 && value.bytes().all(|byte| byte.is_ascii_graphic())
221 };
222 if !wire.token_type.eq_ignore_ascii_case("bearer")
223 || !header_safe(&wire.access_token)
224 || !header_safe(&wire.anthropic_version)
225 || wire.anthropic_version.len() > 64
226 {
227 return Err(invalid());
228 }
229 let base = Url::parse(&wire.base_url).map_err(|_| invalid())?;
230 if base.scheme() != "https" || base.host_str().is_none_or(str::is_empty) {
231 return Err(invalid());
232 }
233 if wire
234 .user_profile_id
235 .as_deref()
236 .is_some_and(|id| !valid_user_profile_id(id))
237 {
238 return Err(invalid());
239 }
240 let expires_at = DateTime::parse_from_rfc3339(&wire.expires_at)
241 .map_err(|_| invalid())?
242 .with_timezone(&Utc);
243 Ok(ClaudeOrgToken {
244 account: None,
245 access_token: wire.access_token,
246 expires_at,
247 base_url: wire.base_url,
248 anthropic_version: wire.anthropic_version,
249 user_profile_id: wire.user_profile_id,
250 })
251 }
252
253 fn valid_user_profile_id(id: &str) -> bool {
254 id.strip_prefix("uprof_").is_some_and(|rest| {
255 (1..=96).contains(&rest.len())
256 && rest
257 .bytes()
258 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
259 })
260 }
261
262 fn validate_link_start_url(value: &str, api_base: &str) -> Result<Url> {
263 let unsafe_url = || anyhow!("The Codewhale service returned an unsafe Claude link URL");
264 let url = Url::parse(value).map_err(|_| unsafe_url())?;
265 let api = Url::parse(api_base).context("invalid Codewhale account API base URL")?;
266 let loopback_test_api = api.scheme() == "http" && api.host_str().is_some_and(is_loopback_host);
267 let scheme_ok = url.scheme() == "https" || (loopback_test_api && url.scheme() == "http");
268 if value != url.as_str()
269 || !scheme_ok
270 || url.host_str().is_none()
271 || url.host_str() != api.host_str()
272 || url.port_or_known_default() != api.port_or_known_default()
273 || !url.username().is_empty()
274 || url.password().is_some()
275 || url.fragment().is_some()
276 || url.path() != LINK_START_PATH
277 {
278 return Err(unsafe_url());
279 }
280 Ok(url)
281 }
282
283 fn response_code(response: &CloudResponse) -> Option<String> {
284 response_error(response)
285 .downcast_ref::<CloudHttpError>()
286 .and_then(|error| error.code().map(str::to_string))
287 }
288
289 fn claude_org_error(response: &CloudResponse) -> ClaudeOrgError {
290 let kind = match (response.status, response_code(response).as_deref()) {
291 (401, _) => ClaudeOrgErrorKind::NotSignedIn,
292 (_, Some("claude_not_linked")) => ClaudeOrgErrorKind::NotLinked,
293 (_, Some("claude_relink_required")) => ClaudeOrgErrorKind::RelinkRequired,
294 (_, Some("claude_billing_disabled")) | (404, None) => ClaudeOrgErrorKind::Disabled,
295 (_, Some("claude_already_linked")) => ClaudeOrgErrorKind::AlreadyLinkedElsewhere,
296 (_, Some("claude_refresh_busy")) => ClaudeOrgErrorKind::Unavailable,
297 (500..=599, _) => ClaudeOrgErrorKind::Unavailable,
298 _ => ClaudeOrgErrorKind::Invalid,
299 };
300 ClaudeOrgError::new(kind)
301 }
302
303 fn expect_claude_org_json<T: DeserializeOwned>(response: CloudResponse) -> Result<T> {
304 if !(200..300).contains(&response.status) {
305 let error = claude_org_error(&response);
306 if error.kind == ClaudeOrgErrorKind::Invalid {
307 return Err(response_error(&response));
308 }
309 return Err(error.into());
310 }
311 parse_json_body(&response.body)
312 }
313
314 impl AccountClient {
315 pub fn claude_org_token(&self) -> std::result::Result<ClaudeOrgToken, ClaudeOrgError> {
316 let mut rejected: Option<String> = None;
317 loop {
318 let lease = self
319 .fresh_auth(rejected.as_deref())
320 .map_err(|_| ClaudeOrgError::new(ClaudeOrgErrorKind::Unavailable))?
321 .ok_or_else(|| ClaudeOrgError::new(ClaudeOrgErrorKind::NotSignedIn))?;
322 let bearer = lease.bundle.access_token.clone();
323 let response = self
324 .transport
325 .execute(CloudRequest {
326 method: HttpMethod::Post,
327 path: TOKEN_PATH.into(),
328 bearer: Some(bearer.clone()),
329 body: Some(b"{}".to_vec()),
330 })
331 .map_err(|_| ClaudeOrgError::new(ClaudeOrgErrorKind::Unavailable))?;
332 if response.status == 401 && rejected.is_none() {
333 rejected = Some(bearer);
334 continue;
335 }
336 let mut token = claude_org_token_from_response(&response)?;
337 token.account = lease.bundle.user.as_ref().and_then(|user| {
338 (!user.id.trim().is_empty()).then(|| (self.api_base.clone(), user.id.clone()))
339 });
340 return Ok(token);
341 }
342 }
343
344 pub fn claude_org_link_status(
345 &self,
346 ) -> std::result::Result<ClaudeOrgLinkStatus, ClaudeOrgError> {
347 self.signed_in()?;
348 link_status(&self.client()).map_err(|error| self.classify(error))
349 }
350
351 pub fn claude_org_start_link(&self) -> std::result::Result<String, ClaudeOrgError> {
352 self.signed_in()?;
353 start_link(&self.client(), &self.api_base)
354 .map(|url| url.to_string())
355 .map_err(|error| self.classify(error))
356 }
357
358 fn signed_in(&self) -> std::result::Result<(), ClaudeOrgError> {
359 self.fresh_auth(None)
360 .map_err(|_| ClaudeOrgError::new(ClaudeOrgErrorKind::Unavailable))?
361 .map(|_| ())
362 .ok_or_else(|| ClaudeOrgError::new(ClaudeOrgErrorKind::NotSignedIn))
363 }
364
365 fn classify(&self, error: anyhow::Error) -> ClaudeOrgError {
366 if outcome_unknown(&error) {
367 return ClaudeOrgError::new(ClaudeOrgErrorKind::Unavailable);
368 }
369 match error.downcast::<ClaudeOrgError>() {
370 Ok(error) => error,
371 Err(_) if self.signed_in().is_err() => {
372 ClaudeOrgError::new(ClaudeOrgErrorKind::NotSignedIn)
373 }
374 Err(error) => {
375 ClaudeOrgError::with_message(ClaudeOrgErrorKind::Invalid, error.to_string())
376 }
377 }
378 }
379 }
380
381 fn link_status<T: CloudTransport>(client: &CloudClient<'_, T>) -> Result<ClaudeOrgLinkStatus> {
382 expect_claude_org_json(client.execute_authenticated(HttpMethod::Get, STATUS_PATH, None)?)
383 }
384
385 fn start_link<T: CloudTransport>(client: &CloudClient<'_, T>, api_base: &str) -> Result<Url> {
386 let start: LinkStart = expect_claude_org_json(client.execute_authenticated(
387 HttpMethod::Post,
388 LINK_PATH,
389 Some(b"{}".to_vec()),
390 )?)?;
391 validate_link_start_url(&start.authorization_url, api_base)
392 }
393
394 fn transient_poll_error(error: &anyhow::Error) -> bool {
395 outcome_unknown(error)
396 || error
397 .downcast_ref::<ClaudeOrgError>()
398 .is_some_and(|error| error.kind == ClaudeOrgErrorKind::Unavailable)
399 }
400
401 pub(crate) fn run_claude_org<T: CloudTransport, W: Write>(
402 args: ClaudeOrgArgs,
403 client: &CloudClient<'_, T>,
404 api_base: &str,
405 out: &mut W,
406 opener: &mut dyn FnMut(String) -> bool,
407 sleeper: &mut dyn FnMut(Duration),
408 ) -> Result<()> {
409 let unavailable = || anyhow::Error::new(ClaudeOrgError::new(ClaudeOrgErrorKind::Disabled));
410 match args.command {
411 ClaudeOrgCommand::Link(link) => {
412 let before = link_status(client)?;
413 if !before.available {
414 return Err(unavailable());
415 }
416 if before.linked {
417 writeln!(
418 out,
419 "A Claude organization is already linked to your Codewhale account."
420 )?;
421 writeln!(
422 out,
423 "Run `codewhale account claude-org unlink` first to link a different one."
424 )?;
425 return Ok(());
426 }
427 let started = Utc::now();
428 let url = start_link(client, api_base)?;
429 writeln!(out, "Link a Claude Platform organization")?;
430 writeln!(out, "Open: {url}")?;
431 if !link.no_open && !opener(url.to_string()) {
432 writeln!(out, "Browser could not be opened; use the URL above.")?;
433 }
434 writeln!(out, "Waiting for the link to finish in your browser...")?;
435 let deadline = std::time::Instant::now() + Duration::from_secs(link.timeout_seconds);
436 let mut tolerated_error = false;
437 loop {
438 sleeper(LINK_POLL_INTERVAL);
439 match link_status(client) {
440 Ok(status) if !status.available => return Err(unavailable()),
441 Ok(status) if status.failure_since(started).is_some() => {
442 return Err(match status.failure_since(started) {
443 Some(ClaudeOrgLinkFailure::Declined) => anyhow!(
444 "The Claude organization link was declined in the browser. Run `{CLAUDE_ORG_LINK_COMMAND}` to try again."
445 ),
446 Some(ClaudeOrgLinkFailure::AlreadyLinkedElsewhere) => {
447 ClaudeOrgError::new(ClaudeOrgErrorKind::AlreadyLinkedElsewhere)
448 .into()
449 }
450 _ => anyhow!(
451 "The Claude organization link failed. Run `{CLAUDE_ORG_LINK_COMMAND}` to try again."
452 ),
453 });
454 }
455 Ok(status) if status.linked => {
456 writeln!(
457 out,
458 "Linked. Anthropic now bills your Claude organization directly for requests Codewhale sends with it."
459 )?;
460 writeln!(
461 out,
462 "To use it, set `auth_mode = \"claude-org\"` under `[providers.anthropic]` in your Codewhale config."
463 )?;
464 return Ok(());
465 }
466 Ok(_) => tolerated_error = false,
467 Err(error) if !tolerated_error && transient_poll_error(&error) => {
468 tolerated_error = true;
469 }
470 Err(error) => return Err(error),
471 }
472 if std::time::Instant::now() >= deadline {
473 bail!(
474 "The Claude organization link did not finish in time. Run `{CLAUDE_ORG_LINK_COMMAND}` to try again."
475 );
476 }
477 }
478 }
479 ClaudeOrgCommand::Status => {
480 let status = link_status(client)?;
481 if !status.available {
482 writeln!(
483 out,
484 "Claude organization billing is not available for this Codewhale account."
485 )?;
486 } else if status.linked {
487 match status.linked_at.as_deref().map(printable) {
488 Some(at) if !at.is_empty() => {
489 writeln!(out, "Claude organization linked (since {at}).")?
490 }
491 _ => writeln!(out, "Claude organization linked.")?,
492 }
493 } else {
494 writeln!(out, "No Claude organization is linked.")?;
495 writeln!(out, "Run `{CLAUDE_ORG_LINK_COMMAND}` to link one.")?;
496 }
497 Ok(())
498 }
499 ClaudeOrgCommand::Unlink => {
500 let result: UnlinkResult = expect_claude_org_json(client.execute_authenticated(
501 HttpMethod::Delete,
502 STATUS_PATH,
503 None,
504 )?)?;
505 writeln!(
506 out,
507 "Claude organization unlinked from your Codewhale account."
508 )?;
509 if !result.revoked {
510 writeln!(
511 out,
512 "Anthropic did not confirm the revocation; remove Codewhale under Linked platforms in the Claude Console if it is still listed."
513 )?;
514 }
515 if let Some(message) = result.message.as_deref().map(printable)
516 && !message.is_empty()
517 {
518 writeln!(out, "{message}")?;
519 }
520 Ok(())
521 }
522 }
523 }
524
524 lines RUST