zeptoclaw 0.9.0

Ultra-lightweight personal AI assistant
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! OAuth authentication module for LLM providers.
//!
//! Provides browser-based OAuth 2.0 + PKCE authentication as an alternative
//! to API keys. OAuth tokens take priority over API keys when both are available.
//!
//! **Warning:** Using OAuth subscription tokens for API access may violate provider
//! Terms of Service. This module includes graceful fallback to API keys when
//! OAuth tokens are rejected.

pub mod claude_import;
pub mod codex_import;
pub mod oauth;
pub mod refresh;
pub mod store;

use serde::{Deserialize, Serialize};

/// Claude Code's OAuth client ID, used when importing subscription tokens
/// obtained via `claude auth token`.
pub const CLAUDE_CODE_CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";

// ============================================================================
// Auth Method
// ============================================================================

/// Authentication method for a provider.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AuthMethod {
    /// Traditional API key authentication (default).
    #[default]
    #[serde(alias = "api_key")]
    ApiKey,
    /// OAuth 2.0 browser-based authentication.
    OAuth,
    /// Try OAuth first, fall back to API key.
    Auto,
}

impl AuthMethod {
    /// Parse from an optional string (as stored in config).
    pub fn from_option(s: Option<&str>) -> Self {
        match s {
            Some("oauth") => Self::OAuth,
            Some("auto") => Self::Auto,
            Some("api_key") | Some("apikey") => Self::ApiKey,
            _ => Self::ApiKey,
        }
    }
}

// ============================================================================
// Resolved Credential
// ============================================================================

/// A resolved credential ready for use in API calls.
///
/// This is the output of the credential resolution process that considers
/// OAuth tokens, API keys, and the configured auth method.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedCredential {
    /// Traditional API key.
    ApiKey(String),
    /// OAuth Bearer token with optional expiry.
    BearerToken {
        access_token: String,
        expires_at: Option<i64>,
    },
}

impl ResolvedCredential {
    /// Returns the credential value (API key or access token).
    pub fn value(&self) -> &str {
        match self {
            Self::ApiKey(key) => key,
            Self::BearerToken { access_token, .. } => access_token,
        }
    }

    /// Returns `true` if this is a Bearer token credential.
    pub fn is_bearer(&self) -> bool {
        matches!(self, Self::BearerToken { .. })
    }

    /// Returns `true` if this is an API key credential.
    pub fn is_api_key(&self) -> bool {
        matches!(self, Self::ApiKey(_))
    }
}

// ============================================================================
// OAuth Token Set
// ============================================================================

/// Stored OAuth token set for a provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthTokenSet {
    /// Provider name (e.g., "anthropic").
    pub provider: String,
    /// OAuth access token.
    pub access_token: String,
    /// OAuth refresh token (for renewing expired access tokens).
    pub refresh_token: Option<String>,
    /// Unix timestamp when the access token expires.
    pub expires_at: Option<i64>,
    /// Token type (typically "Bearer").
    pub token_type: String,
    /// Granted scopes.
    pub scope: Option<String>,
    /// Unix timestamp when the token was obtained.
    pub obtained_at: i64,
    /// Client ID used for this OAuth session (needed for refresh).
    pub client_id: Option<String>,
}

impl OAuthTokenSet {
    /// Returns `true` if the access token has expired.
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.expires_at {
            let now = chrono::Utc::now().timestamp();
            now >= expires_at
        } else {
            false // No expiry = never expires
        }
    }

    /// Returns `true` if the token will expire within the given number of seconds.
    pub fn expires_within(&self, seconds: i64) -> bool {
        if let Some(expires_at) = self.expires_at {
            let now = chrono::Utc::now().timestamp();
            now + seconds >= expires_at
        } else {
            false
        }
    }

    /// Returns a human-readable description of time until expiry.
    pub fn expires_in_human(&self) -> String {
        if let Some(expires_at) = self.expires_at {
            let now = chrono::Utc::now().timestamp();
            let remaining = expires_at - now;
            if remaining <= 0 {
                "expired".to_string()
            } else if remaining < 60 {
                format!("{}s", remaining)
            } else if remaining < 3600 {
                format!("{}m", remaining / 60)
            } else {
                format!("{}h {}m", remaining / 3600, (remaining % 3600) / 60)
            }
        } else {
            "no expiry".to_string()
        }
    }
}

// ============================================================================
// Provider OAuth configuration
// ============================================================================

/// Provider-specific OAuth configuration.
#[derive(Debug, Clone)]
pub struct ProviderOAuthConfig {
    /// Provider name.
    pub provider: String,
    /// OAuth token endpoint URL.
    pub token_url: String,
    /// OAuth authorization endpoint URL.
    pub authorize_url: String,
    /// Client name for dynamic registration.
    pub client_name: String,
    /// Scopes to request.
    pub scopes: Vec<String>,
}

/// Returns the OAuth configuration for a supported provider.
///
/// Note: Some providers may not have a publicly available OAuth flow for API
/// access yet. If a provider's OAuth endpoints or behavior change upstream,
/// `auth login` may fail and users should fall back to API key authentication.
pub fn provider_oauth_config(provider: &str) -> Option<ProviderOAuthConfig> {
    match provider {
        "anthropic" => Some(ProviderOAuthConfig {
            provider: "anthropic".to_string(),
            token_url: "https://console.anthropic.com/v1/oauth/token".to_string(),
            authorize_url: "https://console.anthropic.com/oauth/authorize".to_string(),
            client_name: "ZeptoClaw".to_string(),
            scopes: vec![],
        }),
        "google" => Some(ProviderOAuthConfig {
            provider: "google".to_string(),
            token_url: "https://oauth2.googleapis.com/token".to_string(),
            authorize_url: "https://accounts.google.com/o/oauth2/v2/auth".to_string(),
            client_name: "ZeptoClaw".to_string(),
            scopes: vec![
                "https://www.googleapis.com/auth/gmail.modify".to_string(),
                "https://www.googleapis.com/auth/calendar".to_string(),
            ],
        }),
        "openai" => Some(ProviderOAuthConfig {
            provider: "openai".to_string(),
            token_url: "https://auth.openai.com/oauth/token".to_string(),
            authorize_url: "https://auth.openai.com/oauth/authorize".to_string(),
            client_name: "ZeptoClaw".to_string(),
            scopes: vec![
                "openid".to_string(),
                "email".to_string(),
                "profile".to_string(),
            ],
        }),
        _ => None,
    }
}

/// Returns a list of providers that support OAuth authentication.
pub fn oauth_supported_providers() -> &'static [&'static str] {
    &["anthropic", "google", "openai"]
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_auth_method_default() {
        assert_eq!(AuthMethod::default(), AuthMethod::ApiKey);
    }

    #[test]
    fn test_auth_method_from_option() {
        assert_eq!(AuthMethod::from_option(None), AuthMethod::ApiKey);
        assert_eq!(AuthMethod::from_option(Some("oauth")), AuthMethod::OAuth);
        assert_eq!(AuthMethod::from_option(Some("auto")), AuthMethod::Auto);
        assert_eq!(AuthMethod::from_option(Some("api_key")), AuthMethod::ApiKey);
        assert_eq!(AuthMethod::from_option(Some("apikey")), AuthMethod::ApiKey);
        assert_eq!(AuthMethod::from_option(Some("unknown")), AuthMethod::ApiKey);
    }

    #[test]
    fn test_auth_method_serde_roundtrip() {
        let methods = vec![AuthMethod::ApiKey, AuthMethod::OAuth, AuthMethod::Auto];
        for method in methods {
            let json = serde_json::to_string(&method).unwrap();
            let parsed: AuthMethod = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, method);
        }
    }

    #[test]
    fn test_resolved_credential_api_key() {
        let cred = ResolvedCredential::ApiKey("sk-test".to_string());
        assert!(cred.is_api_key());
        assert!(!cred.is_bearer());
        assert_eq!(cred.value(), "sk-test");
    }

    #[test]
    fn test_resolved_credential_bearer() {
        let cred = ResolvedCredential::BearerToken {
            access_token: "token-123".to_string(),
            expires_at: Some(9999999999),
        };
        assert!(cred.is_bearer());
        assert!(!cred.is_api_key());
        assert_eq!(cred.value(), "token-123");
    }

    #[test]
    fn test_token_set_not_expired() {
        let token = OAuthTokenSet {
            provider: "anthropic".to_string(),
            access_token: "test".to_string(),
            refresh_token: None,
            expires_at: Some(chrono::Utc::now().timestamp() + 3600),
            token_type: "Bearer".to_string(),
            scope: None,
            obtained_at: chrono::Utc::now().timestamp(),
            client_id: None,
        };
        assert!(!token.is_expired());
        assert!(!token.expires_within(300));
    }

    #[test]
    fn test_token_set_expired() {
        let token = OAuthTokenSet {
            provider: "anthropic".to_string(),
            access_token: "test".to_string(),
            refresh_token: None,
            expires_at: Some(chrono::Utc::now().timestamp() - 100),
            token_type: "Bearer".to_string(),
            scope: None,
            obtained_at: chrono::Utc::now().timestamp() - 4000,
            client_id: None,
        };
        assert!(token.is_expired());
    }

    #[test]
    fn test_token_set_expires_within() {
        let token = OAuthTokenSet {
            provider: "anthropic".to_string(),
            access_token: "test".to_string(),
            refresh_token: None,
            expires_at: Some(chrono::Utc::now().timestamp() + 200),
            token_type: "Bearer".to_string(),
            scope: None,
            obtained_at: chrono::Utc::now().timestamp(),
            client_id: None,
        };
        assert!(!token.is_expired());
        assert!(token.expires_within(300)); // 200s left < 300s threshold
        assert!(!token.expires_within(100)); // 200s left > 100s threshold
    }

    #[test]
    fn test_token_set_no_expiry() {
        let token = OAuthTokenSet {
            provider: "anthropic".to_string(),
            access_token: "test".to_string(),
            refresh_token: None,
            expires_at: None,
            token_type: "Bearer".to_string(),
            scope: None,
            obtained_at: chrono::Utc::now().timestamp(),
            client_id: None,
        };
        assert!(!token.is_expired());
        assert!(!token.expires_within(99999));
        assert_eq!(token.expires_in_human(), "no expiry");
    }

    #[test]
    fn test_expires_in_human() {
        let now = chrono::Utc::now().timestamp();

        let token = OAuthTokenSet {
            provider: "test".to_string(),
            access_token: "t".to_string(),
            refresh_token: None,
            expires_at: Some(now - 10),
            token_type: "Bearer".to_string(),
            scope: None,
            obtained_at: now,
            client_id: None,
        };
        assert_eq!(token.expires_in_human(), "expired");

        let token2 = OAuthTokenSet {
            expires_at: Some(now + 7200 + 1800),
            ..token.clone()
        };
        assert!(token2.expires_in_human().contains("h"));
    }

    #[test]
    fn test_provider_oauth_config_anthropic() {
        let config = provider_oauth_config("anthropic");
        assert!(config.is_some());
        let config = config.unwrap();
        assert_eq!(config.provider, "anthropic");
        assert!(config.token_url.contains("anthropic.com"));
    }

    #[test]
    fn test_provider_oauth_config_unsupported() {
        assert!(provider_oauth_config("unknown_provider").is_none());
        assert!(provider_oauth_config("github").is_none());
    }

    #[test]
    fn test_oauth_supported_providers() {
        let providers = oauth_supported_providers();
        assert!(providers.contains(&"anthropic"));
        assert!(providers.contains(&"openai"));
        assert!(!providers.contains(&"github"));
    }

    #[test]
    fn test_provider_oauth_config_google() {
        let config = provider_oauth_config("google");
        assert!(config.is_some());
        let config = config.unwrap();
        assert_eq!(config.provider, "google");
        assert!(config.authorize_url.contains("accounts.google.com"));
        assert!(config.token_url.contains("googleapis.com") || config.token_url.contains("google"));
        assert!(!config.scopes.is_empty());
    }

    #[test]
    fn test_oauth_supported_providers_includes_google() {
        let providers = oauth_supported_providers();
        assert!(providers.contains(&"google"));
    }

    #[test]
    fn test_provider_oauth_config_openai() {
        let config = provider_oauth_config("openai").expect("openai should have OAuth config");
        assert_eq!(config.provider, "openai");
        assert_eq!(
            config.authorize_url,
            "https://auth.openai.com/oauth/authorize"
        );
        assert_eq!(config.token_url, "https://auth.openai.com/oauth/token");
        assert!(!config.scopes.is_empty());
    }

    #[test]
    fn test_oauth_supported_providers_includes_openai() {
        let providers = oauth_supported_providers();
        assert!(
            providers.contains(&"openai"),
            "openai must be in oauth_supported_providers"
        );
    }
}