dx-driven 0.1.0

Professional AI-assisted development orchestrator with binary-first architecture
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! # 1Password Integration
//!
//! 1Password CLI wrapper for secrets management.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::onepassword::{OnePasswordClient, OnePasswordConfig};
//!
//! let config = OnePasswordConfig::from_file("~/.dx/config/onepassword.sr")?;
//! let client = OnePasswordClient::new(&config)?;
//!
//! // Get a secret
//! let secret = client.get_item("API Key", "Development").await?;
//!
//! // Get a specific field
//! let password = client.get_field("API Key", "password", "Development").await?;
//! ```

use crate::error::{DrivenError, Result};
use serde::{Deserialize, Serialize};

/// 1Password configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnePasswordConfig {
    /// Whether 1Password integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Default vault
    pub default_vault: Option<String>,
    /// Service account token (for automation)
    pub service_account_token: Option<String>,
    /// Account shorthand
    pub account: Option<String>,
}

fn default_true() -> bool {
    true
}

impl Default for OnePasswordConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_vault: None,
            service_account_token: None,
            account: None,
        }
    }
}

impl OnePasswordConfig {
    /// Load from .sr config file
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| DrivenError::Io(e))?;
        Self::parse_sr(&content)
    }

    fn parse_sr(_content: &str) -> Result<Self> {
        Ok(Self::default())
    }

    /// Resolve environment variables
    pub fn resolve_env_vars(&mut self) {
        if self.service_account_token.is_none() {
            self.service_account_token = std::env::var("OP_SERVICE_ACCOUNT_TOKEN").ok();
        }
    }
}

/// 1Password vault
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Vault {
    /// Vault ID
    pub id: String,
    /// Vault name
    pub name: String,
    /// Content version
    pub content_version: Option<u64>,
}

/// 1Password item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Item {
    /// Item ID
    pub id: String,
    /// Item title
    pub title: String,
    /// Vault ID
    pub vault_id: String,
    /// Category
    pub category: ItemCategory,
    /// Tags
    #[serde(default)]
    pub tags: Vec<String>,
    /// Fields
    #[serde(default)]
    pub fields: Vec<Field>,
    /// URLs
    #[serde(default)]
    pub urls: Vec<ItemUrl>,
    /// Created at
    pub created_at: Option<String>,
    /// Updated at
    pub updated_at: Option<String>,
}

/// Item category
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ItemCategory {
    Login,
    Password,
    SecureNote,
    CreditCard,
    Identity,
    Document,
    ApiCredential,
    Database,
    Server,
    SshKey,
    SoftwareLicense,
    Email,
    Custom,
    #[serde(other)]
    Unknown,
}

/// Item field
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Field {
    /// Field ID
    pub id: String,
    /// Field label
    pub label: String,
    /// Field value (may be concealed)
    pub value: Option<String>,
    /// Field type
    #[serde(rename = "type")]
    pub field_type: FieldType,
    /// Purpose (username, password, etc.)
    pub purpose: Option<String>,
    /// Section
    pub section: Option<FieldSection>,
}

/// Field type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FieldType {
    String,
    Concealed,
    Email,
    Url,
    Date,
    MonthYear,
    Phone,
    Otp,
    File,
    #[serde(other)]
    Unknown,
}

/// Field section
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldSection {
    pub id: String,
    pub label: Option<String>,
}

/// Item URL
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItemUrl {
    pub label: Option<String>,
    pub primary: bool,
    pub href: String,
}

/// 1Password client
pub struct OnePasswordClient {
    config: OnePasswordConfig,
}

impl OnePasswordClient {
    /// Create a new 1Password client
    pub fn new(config: &OnePasswordConfig) -> Result<Self> {
        let mut config = config.clone();
        config.resolve_env_vars();

        Ok(Self { config })
    }

    /// Check if CLI is available
    pub async fn is_available(&self) -> bool {
        use tokio::process::Command;

        Command::new("op")
            .arg("--version")
            .output()
            .await
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Check if signed in
    pub async fn is_signed_in(&self) -> bool {
        self.run_op(&["account", "get"]).await.is_ok()
    }

    // Vault operations

    /// List vaults
    pub async fn list_vaults(&self) -> Result<Vec<Vault>> {
        let output = self.run_op(&["vault", "list", "--format=json"]).await?;
        serde_json::from_str(&output)
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    /// Get vault by name or ID
    pub async fn get_vault(&self, name_or_id: &str) -> Result<Vault> {
        let output = self.run_op(&["vault", "get", name_or_id, "--format=json"]).await?;
        serde_json::from_str(&output)
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    // Item operations

    /// List items in a vault
    pub async fn list_items(&self, vault: Option<&str>) -> Result<Vec<Item>> {
        let vault_name = vault
            .map(String::from)
            .or_else(|| self.config.default_vault.clone());

        let mut args = vec!["item", "list", "--format=json"];
        if let Some(ref v) = vault_name {
            args.push("--vault");
            args.push(v);
        }

        let output = self.run_op(&args).await?;
        serde_json::from_str(&output)
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    /// Get an item by title or ID
    pub async fn get_item(&self, name_or_id: &str, vault: Option<&str>) -> Result<Item> {
        let vault_name = vault
            .map(String::from)
            .or_else(|| self.config.default_vault.clone());

        let mut args = vec!["item", "get", name_or_id, "--format=json"];
        if let Some(ref v) = vault_name {
            args.push("--vault");
            args.push(v);
        }

        let output = self.run_op(&args).await?;
        serde_json::from_str(&output)
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    /// Get a specific field value
    pub async fn get_field(&self, item: &str, field: &str, vault: Option<&str>) -> Result<String> {
        let vault_name = vault
            .map(String::from)
            .or_else(|| self.config.default_vault.clone());

        let field_ref = format!("op://{}/{}/{}", 
            vault_name.as_deref().unwrap_or("Private"),
            item,
            field
        );

        self.read_reference(&field_ref).await
    }

    /// Get password for an item
    pub async fn get_password(&self, item: &str, vault: Option<&str>) -> Result<String> {
        self.get_field(item, "password", vault).await
    }

    /// Get username for an item
    pub async fn get_username(&self, item: &str, vault: Option<&str>) -> Result<String> {
        self.get_field(item, "username", vault).await
    }

    /// Get OTP code for an item
    pub async fn get_otp(&self, item: &str, vault: Option<&str>) -> Result<String> {
        let vault_name = vault
            .map(String::from)
            .or_else(|| self.config.default_vault.clone());

        let mut args = vec!["item", "get", item, "--otp"];
        if let Some(ref v) = vault_name {
            args.push("--vault");
            args.push(v);
        }

        self.run_op(&args).await
    }

    /// Read a secret reference (op://vault/item/field)
    pub async fn read_reference(&self, reference: &str) -> Result<String> {
        self.run_op(&["read", reference]).await
    }

    /// Inject secrets into a template
    pub async fn inject(&self, template: &str) -> Result<String> {
        use tokio::process::Command;

        let mut cmd = Command::new("op");
        cmd.args(["inject"]);

        if let Some(ref token) = self.config.service_account_token {
            cmd.env("OP_SERVICE_ACCOUNT_TOKEN", token);
        }

        let child = cmd
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| DrivenError::Process(format!("Failed to spawn op: {}", e)))?;

        use tokio::io::AsyncWriteExt;
        
        let mut stdin = child.stdin.ok_or_else(|| {
            DrivenError::Process("Failed to open stdin".into())
        })?;
        
        stdin.write_all(template.as_bytes()).await
            .map_err(|e| DrivenError::Io(e))?;
        drop(stdin);

        let output = child.wait_with_output().await
            .map_err(|e| DrivenError::Io(e))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(DrivenError::Process(format!("op inject failed: {}", stderr)));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Create a new item
    pub async fn create_item(
        &self,
        category: ItemCategory,
        title: &str,
        vault: Option<&str>,
        fields: Vec<(&str, &str)>,
    ) -> Result<Item> {
        let vault_name = vault
            .map(String::from)
            .or_else(|| self.config.default_vault.clone());

        let category_str = match category {
            ItemCategory::Login => "login",
            ItemCategory::Password => "password",
            ItemCategory::SecureNote => "secure note",
            ItemCategory::ApiCredential => "api credential",
            ItemCategory::Database => "database",
            ItemCategory::Server => "server",
            _ => "login",
        };

        let mut args = vec![
            "item".to_string(),
            "create".to_string(),
            "--category".to_string(),
            category_str.to_string(),
            "--title".to_string(),
            title.to_string(),
            "--format=json".to_string(),
        ];

        if let Some(ref v) = vault_name {
            args.push("--vault".to_string());
            args.push(v.clone());
        }

        for (label, value) in fields {
            args.push(format!("{}={}", label, value));
        }

        let args_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        let output = self.run_op(&args_refs).await?;
        
        serde_json::from_str(&output)
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    /// Delete an item
    pub async fn delete_item(&self, item: &str, vault: Option<&str>) -> Result<()> {
        let vault_name = vault
            .map(String::from)
            .or_else(|| self.config.default_vault.clone());

        let mut args = vec!["item", "delete", item];
        if let Some(ref v) = vault_name {
            args.push("--vault");
            args.push(v);
        }

        self.run_op(&args).await?;
        Ok(())
    }

    /// Generate a password
    pub async fn generate_password(&self, length: u8, symbols: bool) -> Result<String> {
        let mut recipe = format!("letters,digits,{}", length);
        if symbols {
            recipe.push_str(",symbols");
        }

        self.run_op(&["item", "get", "--generate-password", &recipe]).await
    }

    /// Search items
    pub async fn search(&self, query: &str) -> Result<Vec<Item>> {
        let output = self.run_op(&[
            "item", "list", 
            "--format=json",
            "--tags", query,
        ]).await;

        if let Ok(o) = output {
            let items: Vec<Item> = serde_json::from_str(&o)
                .unwrap_or_default();
            return Ok(items);
        }

        // Fallback: list all and filter
        let all_items = self.list_items(None).await?;
        let query_lower = query.to_lowercase();
        
        Ok(all_items
            .into_iter()
            .filter(|i| {
                i.title.to_lowercase().contains(&query_lower)
                    || i.tags.iter().any(|t| t.to_lowercase().contains(&query_lower))
            })
            .collect())
    }

    async fn run_op(&self, args: &[&str]) -> Result<String> {
        use tokio::process::Command;

        let mut cmd = Command::new("op");
        cmd.args(args);

        // Add service account token if available
        if let Some(ref token) = self.config.service_account_token {
            cmd.env("OP_SERVICE_ACCOUNT_TOKEN", token);
        }

        // Add account if specified
        if let Some(ref account) = self.config.account {
            cmd.args(["--account", account]);
        }

        let output = cmd
            .output()
            .await
            .map_err(|e| DrivenError::Process(format!("Failed to run op: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(DrivenError::Process(format!("op command failed: {}", stderr)));
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }
}

/// Build a secret reference
pub fn secret_ref(vault: &str, item: &str, field: &str) -> String {
    format!("op://{}/{}/{}", vault, item, field)
}

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

    #[test]
    fn test_default_config() {
        let config = OnePasswordConfig::default();
        assert!(config.enabled);
    }

    #[test]
    fn test_secret_ref() {
        let ref_str = secret_ref("Private", "GitHub", "token");
        assert_eq!(ref_str, "op://Private/GitHub/token");
    }
}