nibkeep_cli/
environment.rs1use std::io::{self, IsTerminal, Write};
5use std::path::{Path, PathBuf};
6use std::sync::mpsc;
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9use getrandom::SysRng;
10use nibkeep_crypto::rand_core::{CryptoRng, UnwrapErr};
11use nibkeep_node::at_login::{self, LoginEntry};
12use nibkeep_node::{NodeError, PassphraseParams};
13use nibkeep_passwords::{Board, ClipboardError};
14use zeroize::Zeroizing;
15
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct Account {
19 pub name: Option<String>,
21 pub full_name: Option<String>,
23}
24
25pub trait Environment {
27 type Rng: CryptoRng;
29
30 fn rng(&mut self) -> &mut Self::Rng;
32
33 fn now(&self) -> u64;
35
36 fn offset_minutes(&self) -> i32;
38
39 fn time_zone(&self) -> jiff::tz::TimeZone {
42 jiff::tz::Offset::from_seconds(self.offset_minutes() * 60)
43 .map_or(jiff::tz::TimeZone::UTC, jiff::tz::TimeZone::fixed)
44 }
45
46 fn passphrase(&mut self, prompt: &str) -> io::Result<Zeroizing<String>>;
52
53 fn passphrase_params(&self) -> PassphraseParams;
55
56 fn computer_name(&self) -> String;
58
59 fn account(&self) -> Account;
61
62 fn current_dir(&self) -> io::Result<PathBuf>;
69
70 fn default_library(&self) -> Option<PathBuf>;
73
74 fn ceiling(&self) -> Option<PathBuf> {
78 None
79 }
80
81 fn keystore(&mut self) -> bool;
84
85 fn languages(&self) -> Vec<String>;
88
89 fn downloads(&self) -> Option<PathBuf> {
91 None
92 }
93
94 fn note(&mut self, line: &str) {
97 eprintln!("nib: {}", crate::printable(line));
98 }
99
100 fn ask(&mut self, question: &str) -> io::Result<Option<String>> {
107 let _ = question;
108 Ok(None)
109 }
110
111 fn can_ask(&self) -> bool {
114 false
115 }
116
117 fn clipboard(&mut self) -> Result<Box<dyn Board>, ClipboardError> {
123 Err(ClipboardError::new("there is none here"))
124 }
125
126 fn interruptible(&mut self) {}
130
131 fn wait(&mut self, duration: Duration) -> bool {
134 std::thread::sleep(duration);
135 false
136 }
137
138 fn stop_on_interrupt(&mut self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
141 let _ = stop;
142 }
143
144 fn state_folder(&self) -> Option<PathBuf> {
148 None
149 }
150
151 fn sync_program(&self) -> Option<PathBuf> {
153 None
154 }
155
156 fn nib_program(&self) -> Option<PathBuf> {
158 None
159 }
160
161 fn ai_client(&self, program: &str) -> Option<std::process::Command> {
165 let _ = program;
166 None
167 }
168
169 fn git(&self) -> std::process::Command {
172 let mut git = std::process::Command::new("git");
173 clear_git_variables(&mut git);
174 git
175 }
176
177 fn login_entry(&self) -> Option<LoginEntry> {
179 None
180 }
181
182 fn open_firewall(&mut self) -> Firewall {
185 Firewall::NotHere
186 }
187
188 fn sync_version(&self, program: &Path) -> Option<String> {
190 at_login::service_version(program)
191 }
192
193 fn start_sync(&mut self, program: &Path) -> Result<(), NodeError> {
200 at_login::start_service(program)
201 }
202}
203
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub enum Firewall {
207 NotHere,
209 Open,
211 Opened,
213 Refused,
215}
216
217pub struct System {
220 rng: UnwrapErr<SysRng>,
221 keystore: Option<bool>,
223 interruptions: Option<mpsc::Receiver<()>>,
225}
226
227impl System {
228 #[must_use]
231 pub fn new() -> Self {
232 Self {
233 rng: UnwrapErr(SysRng),
234 keystore: None,
235 interruptions: None,
236 }
237 }
238}
239
240impl Default for System {
241 fn default() -> Self {
242 Self::new()
243 }
244}
245
246impl Environment for System {
247 type Rng = UnwrapErr<SysRng>;
248
249 fn rng(&mut self) -> &mut Self::Rng {
250 &mut self.rng
251 }
252
253 fn now(&self) -> u64 {
254 SystemTime::now()
255 .duration_since(UNIX_EPOCH)
256 .map_or(0, |since| {
257 u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
258 })
259 }
260
261 fn offset_minutes(&self) -> i32 {
262 jiff::tz::TimeZone::system()
263 .to_offset(jiff::Timestamp::now())
264 .seconds()
265 / 60
266 }
267
268 fn time_zone(&self) -> jiff::tz::TimeZone {
269 jiff::tz::TimeZone::system()
270 }
271
272 fn passphrase(&mut self, prompt: &str) -> io::Result<Zeroizing<String>> {
273 rpassword::prompt_password(prompt).map(Zeroizing::new)
274 }
275
276 fn passphrase_params(&self) -> PassphraseParams {
277 PassphraseParams::LOW_MEMORY
279 }
280
281 fn computer_name(&self) -> String {
282 gethostname::gethostname().to_string_lossy().into_owned()
283 }
284
285 fn account(&self) -> Account {
286 let lossy = |name: std::ffi::OsString| name.to_string_lossy().into_owned();
289 Account {
290 name: whoami::username_os().ok().map(lossy),
291 full_name: whoami::realname_os().ok().map(lossy),
292 }
293 }
294
295 fn current_dir(&self) -> io::Result<PathBuf> {
296 std::env::current_dir()
297 }
298
299 fn default_library(&self) -> Option<PathBuf> {
300 std::env::var_os("NIBKEEP_LIBRARY")
301 .filter(|folder| !folder.is_empty())
302 .map(PathBuf::from)
303 }
304
305 fn ceiling(&self) -> Option<PathBuf> {
306 std::env::var_os("NIBKEEP_CEILING")
309 .map(PathBuf::from)
310 .filter(|folder| folder.is_absolute())
311 .map(|folder| nibkeep_node::resolved_path(&folder).unwrap_or(folder))
312 }
313
314 fn keystore(&mut self) -> bool {
315 *self
318 .keystore
319 .get_or_insert_with(|| !at_login::app::kept_away() && platform_keystore())
320 }
321
322 fn downloads(&self) -> Option<PathBuf> {
323 directories::UserDirs::new()
324 .and_then(|directories| directories.download_dir().map(PathBuf::from))
325 }
326
327 fn state_folder(&self) -> Option<PathBuf> {
328 #[cfg(not(any(target_os = "android", target_os = "ios")))]
329 return at_login::settings_folder();
330 #[cfg(any(target_os = "android", target_os = "ios"))]
331 None
332 }
333
334 fn login_entry(&self) -> Option<LoginEntry> {
335 LoginEntry::platform()
336 }
337
338 fn open_firewall(&mut self) -> Firewall {
339 #[cfg(windows)]
340 {
341 use nibkeep_node::at_login::firewall;
342 if firewall::has_rule() {
343 Firewall::Open
344 } else if firewall::add_rule() {
345 Firewall::Opened
346 } else {
347 Firewall::Refused
348 }
349 }
350 #[cfg(not(windows))]
351 Firewall::NotHere
352 }
353
354 fn sync_program(&self) -> Option<PathBuf> {
355 let name = format!(
356 "{}{}",
357 at_login::SERVICE_PROGRAM,
358 std::env::consts::EXE_SUFFIX
359 );
360 let program = std::env::current_exe().ok()?.with_file_name(name);
361 program.is_file().then_some(program)
362 }
363
364 fn nib_program(&self) -> Option<PathBuf> {
365 std::env::current_exe().ok()
366 }
367
368 fn ai_client(&self, program: &str) -> Option<std::process::Command> {
369 let name = format!("{program}{}", std::env::consts::EXE_SUFFIX);
370 let found = std::env::split_paths(&std::env::var_os("PATH")?)
371 .map(|folder| folder.join(&name))
372 .find(|path| path.is_file())?;
373 Some(std::process::Command::new(found))
374 }
375
376 fn can_ask(&self) -> bool {
377 io::stdin().is_terminal() && io::stderr().is_terminal()
378 }
379
380 fn ask(&mut self, question: &str) -> io::Result<Option<String>> {
381 if !self.can_ask() {
383 return Ok(None);
384 }
385 let mut stderr = io::stderr();
386 write!(stderr, "{}", crate::printable(question))?;
387 stderr.flush()?;
388 let mut answer = String::new();
389 if io::stdin().read_line(&mut answer)? == 0 {
390 return Ok(None);
391 }
392 Ok(Some(answer.trim().to_owned()))
393 }
394
395 fn clipboard(&mut self) -> Result<Box<dyn Board>, ClipboardError> {
396 #[cfg(not(any(target_os = "android", target_os = "ios")))]
397 return Ok(Box::new(nibkeep_passwords::SystemBoard::new()?));
398 #[cfg(any(target_os = "android", target_os = "ios"))]
399 Err(ClipboardError::new("nib has no clipboard on phones"))
400 }
401
402 fn interruptible(&mut self) {
403 if self.interruptions.is_none() {
408 let (interrupted, interruptions) = mpsc::channel();
409 if ctrlc::set_handler(move || {
410 let _ = interrupted.send(());
411 })
412 .is_ok()
413 {
414 self.interruptions = Some(interruptions);
415 }
416 }
417 }
418
419 fn stop_on_interrupt(&mut self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
420 if self.interruptions.is_none() {
421 let _ = ctrlc::set_handler(move || {
422 stop.store(true, std::sync::atomic::Ordering::SeqCst);
423 });
424 }
425 }
426
427 fn wait(&mut self, duration: Duration) -> bool {
428 self.interruptible();
429 if let Some(interruptions) = &self.interruptions {
430 interruptions.recv_timeout(duration).is_ok()
431 } else {
432 std::thread::sleep(duration);
433 false
434 }
435 }
436
437 fn languages(&self) -> Vec<String> {
438 #[cfg(unix)]
440 if let Ok(ranked) = std::env::var("LANGUAGE")
441 && !ranked.is_empty()
442 {
443 return ranked.split(':').map(str::to_owned).collect();
444 }
445 sys_locale::get_locales().collect()
446 }
447}
448
449#[must_use]
451pub fn platform_keystore() -> bool {
452 #[cfg(target_os = "macos")]
453 let store = apple_native_keyring_store::keychain::Store::new();
454 #[cfg(target_os = "windows")]
455 let store = windows_native_keyring_store::Store::new();
456 #[cfg(all(
457 unix,
458 not(any(target_os = "macos", target_os = "ios", target_os = "android"))
459 ))]
460 let store = zbus_secret_service_keyring_store::Store::new();
461 #[cfg(any(
462 target_os = "macos",
463 target_os = "windows",
464 all(
465 unix,
466 not(any(target_os = "macos", target_os = "ios", target_os = "android"))
467 )
468 ))]
469 {
470 match store {
471 Ok(store) => {
472 keyring_core::set_default_store(store);
473 true
474 }
475 Err(_) => false,
476 }
477 }
478 #[cfg(not(any(
479 target_os = "macos",
480 target_os = "windows",
481 all(
482 unix,
483 not(any(target_os = "macos", target_os = "ios", target_os = "android"))
484 )
485 )))]
486 false
487}
488
489pub use nibkeep_git::clear_variables as clear_git_variables;