Skip to main content

nibkeep_cli/
environment.rs

1//! What commands need from the world: randomness, the time, passphrases, keystores and the
2//! clipboard.
3
4use 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/// The person's account on this computer, which names the user of a new library.
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct Account {
19	/// The account's name, as `whoami` prints it, if the system names one.
20	pub name: Option<String>,
21	/// The person's full name, if the system knows it.
22	pub full_name: Option<String>,
23}
24
25/// What commands need from the world.
26pub trait Environment {
27	/// The kind of random number generator.
28	type Rng: CryptoRng;
29
30	/// A cryptographically secure random number generator.
31	fn rng(&mut self) -> &mut Self::Rng;
32
33	/// The wall clock time, in milliseconds since 1970 (UTC).
34	fn now(&self) -> u64;
35
36	/// The device's offset from UTC, in minutes, at the current time.
37	fn offset_minutes(&self) -> i32;
38
39	/// The device's time zone, by which times are read and shown: a fixed offset from UTC,
40	/// [`Environment::offset_minutes`], unless the environment knows the zone's rules.
41	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	/// Asks the person for a passphrase.
47	///
48	/// # Errors
49	///
50	/// Returns an error if the passphrase cannot be read.
51	fn passphrase(&mut self, prompt: &str) -> io::Result<Zeroizing<String>>;
52
53	/// How much work deriving a key from a new passphrase takes.
54	fn passphrase_params(&self) -> PassphraseParams;
55
56	/// The computer's name, the default name of a device.
57	fn computer_name(&self) -> String;
58
59	/// The person's account on this computer, after which a new library's user is named.
60	fn account(&self) -> Account;
61
62	/// The current folder: `nib init` makes it a library, and the other commands look for
63	/// their library in it and in the folders it is in.
64	///
65	/// # Errors
66	///
67	/// Returns an error if the current folder cannot be found, such as one deleted since.
68	fn current_dir(&self) -> io::Result<PathBuf>;
69
70	/// The folder of the library that commands work in outside every library's folder, if
71	/// the person names one: `NIBKEEP_LIBRARY`.
72	fn default_library(&self) -> Option<PathBuf>;
73
74	/// A folder in which, and above which, commands do not look for their library, as
75	/// Git's `GIT_CEILING_DIRECTORIES` says: tests keep to their own folders with it, and the
76	/// end-to-end tests name it in `NIBKEEP_CEILING`.
77	fn ceiling(&self) -> Option<PathBuf> {
78		None
79	}
80
81	/// Whether the platform has a keystore to keep a library's keys in, connecting to it
82	/// the first time.
83	fn keystore(&mut self) -> bool;
84
85	/// The languages the system is set to, first the one it uses, as the platform names
86	/// them, such as `en_US.UTF-8` or `en-US`.
87	fn languages(&self) -> Vec<String>;
88
89	/// This device's downloads folder, as the platform names it, if it has one.
90	fn downloads(&self) -> Option<PathBuf> {
91		None
92	}
93
94	/// Tells the person something beside what the command writes: on standard error, so
95	/// that output that other programs read stays as it is.
96	fn note(&mut self, line: &str) {
97		eprintln!("nib: {}", crate::printable(line));
98	}
99
100	/// Asks the person a question on the terminal, and returns the answer, or `None` if
101	/// there is no terminal to ask on, as for a script or an AI agent.
102	///
103	/// # Errors
104	///
105	/// Returns an error if the answer cannot be read.
106	fn ask(&mut self, question: &str) -> io::Result<Option<String>> {
107		let _ = question;
108		Ok(None)
109	}
110
111	/// Whether [`Environment::ask`] has someone to ask, as before showing a code that would
112	/// be spent without an answer.
113	fn can_ask(&self) -> bool {
114		false
115	}
116
117	/// The clipboard, to copy secrets to: none, unless the environment has one.
118	///
119	/// # Errors
120	///
121	/// Returns an error if there is no clipboard, such as on a computer without a display.
122	fn clipboard(&mut self) -> Result<Box<dyn Board>, ClipboardError> {
123		Err(ClipboardError::new("there is none here"))
124	}
125
126	/// Makes an interruption, as with Ctrl+C, end the next wait rather than `nib`, from now
127	/// on: before `nib` copies a secret, so that an interruption never leaves it on the
128	/// clipboard.
129	fn interruptible(&mut self) {}
130
131	/// Waits for `duration`, or until the person interrupts `nib`, as with Ctrl+C, whichever
132	/// comes first. Returns whether the person interrupted it.
133	fn wait(&mut self, duration: Duration) -> bool {
134		std::thread::sleep(duration);
135		false
136	}
137
138	/// Makes an interruption, as with Ctrl+C, set `stop` rather than end `nib`: for a
139	/// command that runs until stopped, and lets go of what it holds as it ends.
140	fn stop_on_interrupt(&mut self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
141		let _ = stop;
142	}
143
144	/// This computer's folder of NibKeep's state, where the list of libraries synced from
145	/// login is ([technical design](../../../docs/Technical-design.md#106-syncing-from-login)): `None`
146	/// where there is none.
147	fn state_folder(&self) -> Option<PathBuf> {
148		None
149	}
150
151	/// The copy of `nibkeep-sync` installed beside `nib`, if there is one.
152	fn sync_program(&self) -> Option<PathBuf> {
153		None
154	}
155
156	/// The program of `nib` itself, which AI clients run as a library's server.
157	fn nib_program(&self) -> Option<PathBuf> {
158		None
159	}
160
161	/// A command of the AI client's program `program`, such as `claude`, if it is installed
162	/// here, to tell the client of a server or take it away: none unless the environment
163	/// finds it.
164	fn ai_client(&self, program: &str) -> Option<std::process::Command> {
165		let _ = program;
166		None
167	}
168
169	/// The person's own Git, with their settings and credentials, as a command to give
170	/// arguments to ([technical design](../../../docs/Technical-design.md#15-trees)).
171	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	/// The login entry that starts `nibkeep-sync`, where the platform has one.
178	fn login_entry(&self) -> Option<LoginEntry> {
179		None
180	}
181
182	/// Lets the person's other devices reach this computer through its firewall, where
183	/// `nib` does that, as on Windows, asking for the administrator's consent.
184	fn open_firewall(&mut self) -> Firewall {
185		Firewall::NotHere
186	}
187
188	/// The engine's version that a copy of `nibkeep-sync` tells, or `None` if it is gone.
189	fn sync_version(&self, program: &Path) -> Option<String> {
190		at_login::service_version(program)
191	}
192
193	/// Starts a copy of `nibkeep-sync`, apart from `nib`, so that it runs on when `nib`
194	/// ends.
195	///
196	/// # Errors
197	///
198	/// Returns an error if it cannot be started.
199	fn start_sync(&mut self, program: &Path) -> Result<(), NodeError> {
200		at_login::start_service(program)
201	}
202}
203
204/// What `nib` did about the firewall, so that the person's other devices reach `nibkeep-sync`.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub enum Firewall {
207	/// Nothing: `nib` changes no firewall here, as on Linux and macOS.
208	NotHere,
209	/// Nothing: the rule is there already.
210	Open,
211	/// It added the rule, with the administrator's consent.
212	Opened,
213	/// The rule is not there: the person refused, or could not consent.
214	Refused,
215}
216
217/// The real world: the operating system's randomness, clock and keystore, and the
218/// terminal.
219pub struct System {
220	rng: UnwrapErr<SysRng>,
221	/// Whether there is a keystore, once a command asked.
222	keystore: Option<bool>,
223	/// The interruptions, once `nib` takes them instead of ending.
224	interruptions: Option<mpsc::Receiver<()>>,
225}
226
227impl System {
228	/// The real world. The platform's keystore is connected to only when a command needs
229	/// it.
230	#[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		// Every command derives the key again, so the parameters for little memory.
278		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		// Read as the system gives them, so that a name in another encoding still names the
287		// user.
288		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		// A full path, through no link, as the current folder's are, which it is compared
307		// with.
308		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		// Tests keep nib from the computer's keystore, as they keep the apps: with
316		// `NIBKEEP_NO_KEYSTORE`, there is none.
317		*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		// Only a person at a terminal answers; a program that runs nib has no say.
382		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		// Ctrl+C, and a terminal closed on Linux and macOS, end the wait instead of nib: on
404		// Windows and macOS what nib copied would otherwise stay on the clipboard. Windows
405		// ends a program whose console window is closed without waiting for it, so there the
406		// copy stays until something else is copied.
407		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		// GNU systems rank the languages of messages in LANGUAGE, as `en_US:ru`.
439		#[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/// Makes the platform's keystore the one that libraries use. Returns whether there is one.
450#[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
489/// Clears from a command of Git the variables that would make it work on another repository
490/// than the folder it is given, as a hook or an alias of Git that runs `nib` sets them.
491pub use nibkeep_git::clear_variables as clear_git_variables;