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
|
use anyhow::{Result, anyhow};
use clap::Subcommand;
use itertools::Itertools;
use mullvad_management_interface::MullvadProxyClient;
use mullvad_types::{account::AccountNumber, device::DeviceState};
use std::io::{self, Write};
const NOT_LOGGED_IN_MESSAGE: &str = "Not logged in on any account";
const REVOKED_MESSAGE: &str = "The current device has been revoked";
#[derive(Subcommand, Debug)]
pub enum Account {
/// Create and log in on a new account
Create,
/// Log in on an account
Login {
/// The Mullvad account number to configure the client with
account: Option<String>,
},
/// Log out of the current account
Logout,
/// Display information about the current account
Get {
/// Enable verbose output
#[arg(long, short = 'v')]
verbose: bool,
},
/// List devices associated with an account
ListDevices {
/// Mullvad account number (current account if not specified)
#[arg(long, short = 'a')]
account: Option<String>,
/// Enable verbose output
#[arg(long, short = 'v')]
verbose: bool,
},
/// Revoke a device associated with an account
RevokeDevice {
/// Name or UID of the device to revoke
device: String,
/// Mullvad account number (current account if not specified)
#[arg(long, short = 'a')]
account: Option<String>,
},
/// Redeem a voucher
Redeem {
/// Voucher code to submit
voucher: String,
},
}
impl Account {
pub async fn handle(self) -> Result<()> {
let mut rpc = MullvadProxyClient::new().await?;
match self {
Account::Create => Self::create(&mut rpc).await,
Account::Login { account } => {
Self::login(
&mut rpc,
unwrap_or_from_stdin(account, "Enter an account number: ").await,
)
.await
}
Account::Logout => Self::logout(&mut rpc).await,
Account::Get { verbose } => Self::get(&mut rpc, verbose).await,
Account::ListDevices { account, verbose } => {
Self::list_devices(&mut rpc, account, verbose).await
}
Account::RevokeDevice { device, account } => {
Self::revoke_device(&mut rpc, device, account).await
}
Account::Redeem { voucher } => Self::redeem_voucher(&mut rpc, voucher).await,
}
}
async fn create(rpc: &mut MullvadProxyClient) -> Result<()> {
rpc.create_new_account().await?;
println!("New account created!");
Self::get(rpc, false).await
}
async fn login(rpc: &mut MullvadProxyClient, account_number: AccountNumber) -> Result<()> {
rpc.login_account(account_number.clone()).await?;
println!("Mullvad account \"{account_number}\" set");
Ok(())
}
async fn logout(rpc: &mut MullvadProxyClient) -> Result<()> {
rpc.logout_account().await?;
println!("Removed device from Mullvad account");
Ok(())
}
async fn get(rpc: &mut MullvadProxyClient, verbose: bool) -> Result<()> {
let _ = rpc.update_device().await;
let state = rpc.get_device().await?;
match state {
DeviceState::LoggedIn(device) => {
println!("{:<20}{}", "Mullvad account:", device.account_number);
let data = rpc.get_account_data(device.account_number).await?;
println!(
"{:<20}{}",
"Expires at:",
data.expiry.with_timezone(&chrono::Local)
);
if verbose {
println!("{:<20}{}", "Account id:", data.id);
}
println!("{:<20}{}", "Device name:", device.device.pretty_name());
if verbose {
println!("{:<20}{}", "Device id:", device.device.id);
println!("{:<20}{}", "Device pubkey:", device.device.pubkey);
println!("{:<20}{}", "Device created:", device.device.created);
}
}
DeviceState::LoggedOut => {
println!("{NOT_LOGGED_IN_MESSAGE}");
}
DeviceState::Revoked => {
println!("{REVOKED_MESSAGE}");
if let Some(account_number) = rpc.get_account_history().await? {
println!("Mullvad account: {account_number}");
}
}
}
Ok(())
}
async fn list_devices(
rpc: &mut MullvadProxyClient,
account: Option<String>,
verbose: bool,
) -> Result<()> {
let account_number = account_else_current(rpc, account).await?;
let mut device_list = rpc.list_devices(account_number).await?;
println!("Devices on the account:");
device_list.sort_unstable_by_key(|dev| dev.created.timestamp());
for device in device_list {
if verbose {
println!();
println!("Name : {}", device.pretty_name());
println!("Id : {}", device.id);
println!("Public key: {}", device.pubkey);
println!(
"Created : {}",
device.created.with_timezone(&chrono::Local)
);
} else {
println!("{}", device.pretty_name());
}
}
Ok(())
}
async fn revoke_device(
rpc: &mut MullvadProxyClient,
device: String,
account: Option<String>,
) -> Result<()> {
let account_number = account_else_current(rpc, account).await?;
let device_list = rpc.list_devices(account_number.clone()).await?;
let device_id = device_list
.into_iter()
.find(|dev| {
dev.name.eq_ignore_ascii_case(&device) || dev.id.eq_ignore_ascii_case(&device)
})
.map(|dev| dev.id)
.ok_or(mullvad_management_interface::Error::DeviceNotFound)?;
rpc.remove_device(account_number, device_id).await?;
println!("Removed device");
Ok(())
}
async fn redeem_voucher(rpc: &mut MullvadProxyClient, mut voucher: String) -> Result<()> {
voucher.retain(|c| c.is_alphanumeric());
let submission = rpc.submit_voucher(voucher).await?;
println!(
"Added {} to the account",
format_duration(submission.time_added)
);
println!(
"New expiry date: {}",
submission.new_expiry.with_timezone(&chrono::Local),
);
Ok(())
}
}
async fn account_else_current(
rpc: &mut MullvadProxyClient,
account_number: Option<String>,
) -> Result<String> {
match account_number {
Some(account) => Ok(account),
None => {
let state = rpc.get_device().await?;
match state {
DeviceState::LoggedIn(account) => Ok(account.account_number),
_ => Err(anyhow!("Log in or specify an account")),
}
}
}
}
async fn unwrap_or_from_stdin(val: Option<String>, prompt_str: &'static str) -> String {
if let Some(val) = val {
return val;
}
tokio::task::spawn_blocking(|| from_stdin(prompt_str))
.await
.unwrap()
}
fn from_stdin(prompt_str: &'static str) -> String {
let mut val = String::new();
io::stdout()
.write_all(prompt_str.as_bytes())
.expect("Failed to write to STDOUT");
let _ = io::stdout().flush();
io::stdin()
.read_line(&mut val)
.expect("Failed to read from STDIN");
val.split_whitespace().join("")
}
fn format_duration(seconds: u64) -> String {
let dur = chrono::Duration::seconds(seconds as i64);
if dur.num_days() > 0 {
format!("{} days", dur.num_days())
} else if dur.num_hours() > 0 {
format!("{} hours", dur.num_hours())
} else if dur.num_minutes() > 0 {
format!("{} minutes", dur.num_minutes())
} else {
format!("{} seconds", dur.num_seconds())
}
}
|