bw/
main.rs

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
use bitwarden_cli::{install_color_eyre, text_prompt_when_none, Color};
use bitwarden_core::{auth::RegisterRequest, ClientSettings};
use bitwarden_generators::{
    GeneratorClientsExt, PassphraseGeneratorRequest, PasswordGeneratorRequest,
};
use clap::{command, Args, CommandFactory, Parser, Subcommand};
use color_eyre::eyre::Result;
use inquire::Password;
use render::Output;

mod auth;
mod render;

#[derive(Parser, Clone)]
#[command(name = "Bitwarden CLI", version, about = "Bitwarden CLI", long_about = None)]
struct Cli {
    // Optional as a workaround for https://github.com/clap-rs/clap/issues/3572
    #[command(subcommand)]
    command: Option<Commands>,

    #[arg(short = 'o', long, global = true, value_enum, default_value_t = Output::JSON)]
    output: Output,

    #[arg(short = 'c', long, global = true, value_enum, default_value_t = Color::Auto)]
    color: Color,
}

#[derive(Subcommand, Clone)]
enum Commands {
    Login(LoginArgs),

    #[command(long_about = "Register")]
    Register {
        #[arg(short = 'e', long, help = "Email address")]
        email: Option<String>,

        name: Option<String>,

        password_hint: Option<String>,

        #[arg(short = 's', long, global = true, help = "Server URL")]
        server: Option<String>,
    },

    #[command(long_about = "Manage vault items")]
    Item {
        #[command(subcommand)]
        command: ItemCommands,
    },

    #[command(long_about = "Pull the latest vault data from the server")]
    Sync {},

    #[command(long_about = "Password and passphrase generators")]
    Generate {
        #[command(subcommand)]
        command: GeneratorCommands,
    },
}

#[derive(Args, Clone)]
struct LoginArgs {
    #[command(subcommand)]
    command: LoginCommands,

    #[arg(short = 's', long, global = true, help = "Server URL")]
    server: Option<String>,
}

#[derive(Subcommand, Clone)]
enum LoginCommands {
    Password {
        #[arg(short = 'e', long, help = "Email address")]
        email: Option<String>,
    },
    ApiKey {
        client_id: Option<String>,
        client_secret: Option<String>,
    },
    Device {
        #[arg(short = 'e', long, help = "Email address")]
        email: Option<String>,
        device_identifier: Option<String>,
    },
}

#[derive(Subcommand, Clone)]
enum ItemCommands {
    Get { id: String },
    Create {},
}

#[derive(Subcommand, Clone)]
enum GeneratorCommands {
    Password(PasswordGeneratorArgs),
    Passphrase(PassphraseGeneratorArgs),
}

#[derive(Args, Clone)]
struct PasswordGeneratorArgs {
    #[arg(short = 'l', long, action, help = "Include lowercase characters (a-z)")]
    lowercase: bool,

    #[arg(short = 'u', long, action, help = "Include uppercase characters (A-Z)")]
    uppercase: bool,

    #[arg(short = 'n', long, action, help = "Include numbers (0-9)")]
    numbers: bool,

    #[arg(
        short = 's',
        long,
        action,
        help = "Include special characters (!@#$%^&*)"
    )]
    special: bool,

    #[arg(long, default_value = "16", help = "Length of generated password")]
    length: u8,
}

#[derive(Args, Clone)]
struct PassphraseGeneratorArgs {
    #[arg(long, default_value = "3", help = "Number of words in the passphrase")]
    words: u8,
    #[arg(long, default_value = " ", help = "Separator between words")]
    separator: char,
    #[arg(long, action, help = "Capitalize the first letter of each word")]
    capitalize: bool,
    #[arg(long, action, help = "Include a number in one of the words")]
    include_number: bool,
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();

    process_commands().await
}

async fn process_commands() -> Result<()> {
    let cli = Cli::parse();

    install_color_eyre(cli.color)?;

    let Some(command) = cli.command else {
        let mut cmd = Cli::command();
        cmd.print_help()?;
        return Ok(());
    };

    match command.clone() {
        Commands::Login(args) => {
            let settings = args.server.map(|server| ClientSettings {
                api_url: format!("{}/api", server),
                identity_url: format!("{}/identity", server),
                ..Default::default()
            });
            let client = bitwarden_core::Client::new(settings);

            match args.command {
                // FIXME: Rust CLI will not support password login!
                LoginCommands::Password { email } => {
                    auth::login_password(client, email).await?;
                }
                LoginCommands::ApiKey {
                    client_id,
                    client_secret,
                } => auth::login_api_key(client, client_id, client_secret).await?,
                LoginCommands::Device {
                    email,
                    device_identifier,
                } => {
                    auth::login_device(client, email, device_identifier).await?;
                }
            }
            return Ok(());
        }
        Commands::Register {
            email,
            name,
            password_hint,
            server,
        } => {
            let settings = server.map(|server| ClientSettings {
                api_url: format!("{}/api", server),
                identity_url: format!("{}/identity", server),
                ..Default::default()
            });
            let client = bitwarden_core::Client::new(settings);

            let email = text_prompt_when_none("Email", email)?;
            let password = Password::new("Password").prompt()?;

            client
                .auth()
                .register(&RegisterRequest {
                    email,
                    name,
                    password,
                    password_hint,
                })
                .await?;
        }
        _ => {}
    }

    // Not login, assuming we have a config
    let client = bitwarden_core::Client::new(None);

    // And finally we process all the commands which require authentication
    match command {
        Commands::Login(_) => unreachable!(),
        Commands::Register { .. } => unreachable!(),
        Commands::Item { command: _ } => todo!(),
        Commands::Sync {} => todo!(),
        Commands::Generate { command } => match command {
            GeneratorCommands::Password(args) => {
                let password = client.generator().password(PasswordGeneratorRequest {
                    lowercase: args.lowercase,
                    uppercase: args.uppercase,
                    numbers: args.numbers,
                    special: args.special,
                    length: args.length,
                    ..Default::default()
                })?;

                println!("{}", password);
            }
            GeneratorCommands::Passphrase(args) => {
                let passphrase = client.generator().passphrase(PassphraseGeneratorRequest {
                    num_words: args.words,
                    word_separator: args.separator.to_string(),
                    capitalize: args.capitalize,
                    include_number: args.include_number,
                })?;

                println!("{}", passphrase);
            }
        },
    };

    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}