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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only
use crate::{Permission, add_http};
use anyhow::bail;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as b64};
use clap::Subcommand;
use ordinary_api::client::{AccountMeta, OrdinaryApiClient};
use qrcodegen::{QrCode, QrCodeEcc};
use std::env::home_dir;
use time::format_description::BorrowedFormatItem;
use time::{UtcDateTime, format_description};
pub static GMT_FORMAT: std::sync::LazyLock<Vec<BorrowedFormatItem<'static>>> =
std::sync::LazyLock::new(|| {
format_description::parse(
"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT",
)
.expect("failed to create format")
});
/// account management subcommands
#[derive(Subcommand, Debug)]
pub enum Accounts {
/// register a new account
Register {
/// url where `orindaryd` is running
host: String,
/// name of your account with the host
account: String,
/// password for your new account
#[arg(long)]
password: Option<String>,
/// base64 encoded invite token
#[arg(long)]
invite: Option<String>,
},
/// log in to an existing account
Login {
/// url where `orindaryd` is running
host: String,
/// name of your account with the host
account: String,
/// password for your existing account
#[arg(long)]
password: Option<String>,
/// 6 digit TOTP MFA code
#[arg(long)]
mfa: Option<String>,
},
/// log out of a logged in account
Logout,
Access {
#[command(subcommand)]
access: Access,
},
/// password management
Password {
#[command(subcommand)]
password: Password,
},
/// MFA management
Mfa {
#[command(subcommand)]
mfa: Mfa,
},
/// recovery code management
RecoveryCodes {
#[command(subcommand)]
recovery_codes: RecoveryCodes,
},
/// invite another user to a project
Invite {
/// name of the account to be invited & registered
account: String,
/// domain for the invited application
domain: String,
/// which permissions to include in their set
permissions: Vec<Permission>,
},
/// display info for current account
///
/// format: <host> <account> <project> <permissions> <session exp>
Current,
/// list all logged in accounts
List,
/// switch to a different logged in account
Switch {
/// API domain where `orindaryd` is running
domain: String,
/// name of the account you'd like to switch to
account: String,
},
}
/// access management subcommands
#[derive(Subcommand, Debug)]
pub enum Access {
/// get access
Get {
/// how long the client signature is valid for
#[arg(short, long)]
min: Option<u16>,
},
}
/// password management subcommands
#[derive(Subcommand, Debug)]
pub enum Password {
/// reset your password
Reset {
/// existing password
#[arg(long)]
password: Option<String>,
/// new password to be set
#[arg(long)]
new_password: Option<String>,
/// 6 digit TOTP MFA code
#[arg(long)]
mfa: Option<String>,
},
/// recover your password
Forgot {
/// new password to be set
#[arg(long)]
new_password: Option<String>,
/// 11 character recovery code
#[arg(long)]
recovery_code: Option<String>,
},
}
/// MFA management subcommands
#[derive(Subcommand, Debug)]
pub enum Mfa {
/// reset MFA TOTP secret
Reset {
/// account password
#[arg(long)]
password: Option<String>,
/// 6 digit TOTP MFA code
#[arg(long)]
mfa: Option<String>,
},
/// recovery MFA TOTP secret
Lost {
/// account password
#[arg(long)]
password: Option<String>,
/// 11 character recovery code
#[arg(long)]
recovery_code: Option<String>,
},
}
/// recovery code management subcommands
#[derive(Subcommand, Debug)]
pub enum RecoveryCodes {
/// reset recovery codes
Reset {
/// account password
#[arg(long)]
password: Option<String>,
/// 6 digit TOTP MFA code
#[arg(long)]
mfa: Option<String>,
},
}
fn switch_account(host: &str, domain: &str, account: &str) -> anyhow::Result<()> {
tracing::debug!("switching accounts");
let cli_path = home_dir()
.expect("failed to get home dir")
.join(".ordinary")
.join("cli");
if !cli_path.exists() {
fs_err::create_dir_all(&cli_path)?;
}
let host = if let Some(stripped) = host.strip_prefix("https://") {
stripped
} else if let Some(stripped) = host.strip_prefix("http://") {
stripped
} else {
host
};
let domain = if let Some(stripped) = domain.strip_prefix("https://") {
stripped
} else if let Some(stripped) = domain.strip_prefix("http://") {
stripped
} else {
domain
};
let account_path = cli_path.join("account");
fs_err::write(account_path, format!("{account}@{domain}@{host}"))?;
Ok(())
}
pub fn get_current_account(insecure: bool) -> anyhow::Result<AccountMeta> {
tracing::debug!("getting current account");
let account_path = home_dir()
.expect("failed to get home dir")
.join(".ordinary")
.join("cli")
.join("account");
if !account_path.exists() {
bail!("not logged in")
}
let pair = fs_err::read_to_string(account_path)?;
let split_pair = pair.split('@').collect::<Vec<&str>>();
let mut account_meta =
OrdinaryApiClient::get_account(split_pair[2], split_pair[1], split_pair[0])?;
account_meta.host = add_http(&account_meta.host, insecure);
Ok(account_meta)
}
impl Accounts {
#[allow(clippy::too_many_lines)]
pub async fn handle(
&self,
api_domain: Option<&str>,
accept_invalid_certs: bool,
insecure: bool,
) -> anyhow::Result<()> {
match self {
Self::Register {
host,
account,
password,
invite,
} => {
let client = OrdinaryApiClient::new(
host,
account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
// todo: pull from elsewhere if None
let password = password.to_owned().unwrap_or_default();
let invite = invite.to_owned().unwrap_or_default();
let (totp, recovery_codes_str) = client.register(&password, &invite).await?;
Self::print_mfa(&totp.get_url())?;
Self::print_recovery_codes(&recovery_codes_str);
println!("\nlog in: `ordinary accounts login --help`");
}
Self::Login {
host,
account,
password,
mfa,
} => {
let client = OrdinaryApiClient::new(
host,
account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
// todo: pull from elsewhere if None
let password = password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
client.login(&password, &mfa).await?;
switch_account(host, api_domain.unwrap_or(host), account)?;
}
Self::Logout => {
println!("todo: logout");
}
Self::Access { access } => match access {
Access::Get { min } => {
let AccountMeta {
host,
name: account,
..
} = get_current_account(insecure)?;
let client = OrdinaryApiClient::new(
&host,
&account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
let access_token = client.get_access(min.map(|m| u32::from(m) * 60)).await?;
let b64_token = b64.encode(access_token);
println!("{b64_token}");
}
},
Self::Password { password } => {
let AccountMeta {
host,
name: account,
..
} = get_current_account(insecure)?;
let client = OrdinaryApiClient::new(
&host,
&account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
match password {
Password::Reset {
password,
new_password,
mfa,
} => {
// todo: pull from elsewhere if None
let password = password.to_owned().unwrap_or_default();
let new_password = new_password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
client
.reset_password(&password, &mfa, &new_password)
.await?;
}
Password::Forgot {
new_password,
recovery_code,
} => {
let AccountMeta {
host,
name: account,
..
} = get_current_account(insecure)?;
let client = OrdinaryApiClient::new(
&host,
&account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
// todo: pull from elsewhere if None
let new_password = new_password.to_owned().unwrap_or_default();
let recovery_code = recovery_code.to_owned().unwrap_or_default();
client
.forgot_password(&new_password, &recovery_code)
.await?;
}
}
}
Self::Mfa { mfa } => {
let AccountMeta {
host,
name: account,
..
} = get_current_account(insecure)?;
let client = OrdinaryApiClient::new(
&host,
&account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
match mfa {
Mfa::Reset { password, mfa } => {
let password = password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
let totp = client.mfa_totp_reset(&password, &mfa).await?;
Self::print_mfa(&totp.get_url())?;
}
Mfa::Lost {
password,
recovery_code,
} => {
let password = password.to_owned().unwrap_or_default();
let recovery_code = recovery_code.to_owned().unwrap_or_default();
let totp = client.mfa_totp_reset(&password, &recovery_code).await?;
Self::print_mfa(&totp.get_url())?;
}
}
}
Self::RecoveryCodes { recovery_codes } => {
let AccountMeta {
host,
name: account,
..
} = get_current_account(insecure)?;
let client = OrdinaryApiClient::new(
&host,
&account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
match recovery_codes {
RecoveryCodes::Reset { password, mfa } => {
let password = password.to_owned().unwrap_or_default();
let mfa = mfa.to_owned().unwrap_or_default();
let recovery_codes_str =
client.recovery_codes_reset(&password, &mfa).await?;
Self::print_recovery_codes(&recovery_codes_str);
}
}
}
Self::Invite {
account: their_account,
domain,
permissions,
} => {
let AccountMeta {
host,
name: account,
project,
..
} = get_current_account(insecure)?;
let client = OrdinaryApiClient::new(
&host,
&account,
api_domain,
accept_invalid_certs,
crate::USER_AGENT,
)?;
if !project.is_empty() && &project != domain {
bail!("projects do not match");
}
let invite_token = client
.invite_api_account(
domain,
their_account,
permissions
.iter()
.map(Permission::as_u8)
.collect::<Vec<u8>>(),
)
.await?;
println!("INVITE TOKEN: {invite_token}");
}
Self::Current => {
let curr = get_current_account(insecure)?;
let accounts = OrdinaryApiClient::list_accounts()?
.iter()
.filter(|&account| account.name == curr.name && account.domain == curr.domain)
.cloned()
.collect::<Vec<AccountMeta>>();
Self::account_meta_to_readable(accounts)?;
}
Self::List => {
Self::account_meta_to_readable(OrdinaryApiClient::list_accounts()?)?;
}
Self::Switch { domain, account } => {
let host = OrdinaryApiClient::get_host(domain, account)?;
switch_account(&host, domain, account)?;
}
}
Ok(())
}
fn print_recovery_codes(recovery_codes_str: &str) {
let mut recovery_code = String::new();
let mut recovery_codes: Vec<String> = vec![];
for (i, c) in recovery_codes_str.chars().enumerate() {
if i > 0 && i % 11 == 0 {
recovery_codes.push(recovery_code.clone());
recovery_code = c.to_string();
} else if i == recovery_codes_str.len() - 1 {
recovery_code.push(c);
recovery_codes.push(recovery_code.clone());
} else {
recovery_code.push(c);
}
}
println!("recovery codes:");
for code in recovery_codes {
println!("- {code}");
}
}
fn print_mfa(mfa_url: &str) -> anyhow::Result<()> {
let qr: QrCode = QrCode::encode_text(mfa_url, QrCodeEcc::Medium)?;
let border: i32 = 4;
for y in -border..qr.size() + border {
for x in -border..qr.size() + border {
let c: char = if qr.get_module(x, y) { '█' } else { ' ' };
print!("{c}{c}");
}
println!();
}
println!("{mfa_url}");
Ok(())
}
fn account_meta_to_readable(accounts: Vec<AccountMeta>) -> anyhow::Result<()> {
use comfy_table::Table;
let mut table = Table::new();
table.set_header(vec![
"API account",
"API domain",
"Host",
"App domain",
"App permissions",
"Token expiration",
"Token ID",
]);
for account in accounts {
let mut perms_str = String::new();
for permission in account.permissions {
perms_str.push_str(Permission::from_u8(permission).as_str());
perms_str.push(' ');
}
perms_str.pop();
let exp = UtcDateTime::from_unix_timestamp(account.refresh_exp.cast_signed())?;
let exp_fmt = exp.format(&GMT_FORMAT)?;
table.add_row(vec![
account.name,
account.domain,
format!("http(s)://{}", account.host),
account.project,
perms_str,
exp_fmt,
account.id,
]);
}
println!("{table}");
Ok(())
}
}