1mod clients;
9mod environment;
10mod mcp;
11mod output;
12mod trees;
13mod types;
14
15pub use trees::TreeCommand;
16
17use std::cell::RefCell;
18use std::collections::BTreeMap;
19use std::io::{self, Write};
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22use std::sync::atomic::AtomicBool;
23use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
24
25use clap::{Args, Parser, Subcommand, ValueEnum};
26use getrandom::SysRng;
27use getrandom::rand_core::UnwrapErr;
28use nibkeep_base::{EntityId, SpaceId};
29use nibkeep_crypto::RecoveryCode;
30use nibkeep_model::{FieldName, Languages, ParseLanguagesError, Tag, TypeName};
31use nibkeep_node::{
32 Backup, BackupEdit, DeviceRole, Kept, MoveHistory, MoveSecrets, Needs, NewBackup, NewRule,
33 Place, PolicyEdit, at_login,
34};
35use nibkeep_node::{Checkout, Dating, Edit, EntityView, LanguagesFor, NewLibrary};
36use nibkeep_node::{
37 Holding, KeysError, Library, MemberRole, NewProtection, NodeError, PairingCode, Protection,
38 Replica, Role, SecretsState, Unlocker,
39};
40use nibkeep_std::{FILE, PHOTO, VIDEO};
41use nibkeep_time::{Day, Edtf};
42
43pub use environment::{
44 Account, Environment, Firewall, System, clear_git_variables, platform_keystore,
45};
46pub use mcp::McpServer;
47use nibkeep_node::pointer::{
48 self, Found, LIBRARY_DATA, PointerError, holds_library,
49 resolved_as_far_as_it_exists as resolved,
50};
51
52use nibkeep_node::KEYSTORE_SERVICE;
54
55const APP: &str = "nib";
57
58impl From<PointerError> for CliError {
60 fn from(error: PointerError) -> Self {
61 match error {
62 PointerError::Bad { file, why } => Self::BadPointer { file, why },
63 PointerError::Stray { file, library } => Self::StrayPointer { file, library },
64 PointerError::InTheWay(file) => Self::PointerInTheWay(file),
65 PointerError::NotWritten { file, error } => Self::PointerNotWritten { file, error },
66 PointerError::NotTakenAway { file, error } => Self::PointerNotTakenAway { file, error },
67 PointerError::Library(error) => error.into(),
68 }
69 }
70}
71
72#[derive(Debug, Parser)]
74#[command(name = "nib", bin_name = "nib", version = env!("NIB_VERSION"), about)]
76pub struct Cli {
77 #[arg(long, global = true, value_name = "FOLDER")]
82 pub library: Option<PathBuf>,
83 #[arg(long, global = true, value_name = "SPACE")]
87 pub space: Option<String>,
88 #[arg(long, global = true)]
90 pub json: bool,
91 #[arg(long, global = true, hide = true)]
94 pub timings: bool,
95 #[arg(
99 long,
100 global = true,
101 value_name = "FILE",
102 env = "NIBKEEP_PASSPHRASE_FILE"
103 )]
104 pub passphrase_file: Option<PathBuf>,
105 #[command(subcommand)]
107 pub command: Command,
108}
109
110impl Cli {
111 fn network(&self, accept: bool) -> nibkeep_node::NetworkOptions {
114 let port = match &self.command {
115 Command::Sync { port, .. } if accept => *port,
116 Command::Device {
117 command: DeviceCommand::Pair { port, .. },
118 }
119 | Command::Space {
120 command: SpaceCommand::Invite { port, .. },
121 } if accept => port.port,
122 _ => 0,
123 };
124 nibkeep_node::NetworkOptions {
125 discovery: true,
126 port: (port != 0).then_some(port),
127 accept,
128 }
129 }
130}
131
132#[derive(Debug, Args)]
134pub struct Port {
135 #[arg(
138 long,
139 value_name = "PORT",
140 env = "NIBKEEP_PORT",
141 default_value_t = nibkeep_node::DEFAULT_PORT
142 )]
143 pub port: u16,
144}
145
146const OVERVIEW: &[(&str, &[&str])] = &[
148 (
149 "Library",
150 &[
151 "init",
152 "status",
153 "verify",
154 "languages",
155 "protect",
156 "export",
157 "import",
158 ],
159 ),
160 (
161 "Entities",
162 &[
163 "new", "show", "edit", "list", "find", "history", "merge", "move", "purge", "type",
164 ],
165 ),
166 (
167 "Trees",
168 &[
169 "commit", "mv", "rm", "log", "diff", "blame", "restore", "revert", "update", "pull",
170 "clone",
171 ],
172 ),
173 ("Files and secrets", &["file", "policy", "secret"]),
174 ("Devices and sharing", &["sync", "device", "space", "mcp"]),
175 ("Safekeeping", &["backup", "recovery", "purges"]),
176];
177
178#[must_use]
181pub fn command() -> clap::Command {
182 use clap::CommandFactory;
183 use std::fmt::Write as _;
184 let command = Cli::command();
185 let styles = command.get_styles();
186 let (header, literal) = (styles.get_header(), styles.get_literal());
187 let width = OVERVIEW
188 .iter()
189 .flat_map(|(_, names)| names.iter())
190 .map(|name| name.len())
191 .max()
192 .unwrap_or(0);
193 let mut overview = String::new();
194 let mut aliases = Vec::new();
195 for (heading, names) in OVERVIEW {
196 let _ = writeln!(overview, "{header}{heading}:{header:#}");
197 for name in *names {
198 let about = command
199 .find_subcommand(name)
200 .and_then(clap::Command::get_about)
201 .map_or_else(String::new, ToString::to_string);
202 let _ = writeln!(overview, " {literal}{name:width$}{literal:#} {about}");
203 if let Some(sub) = command.find_subcommand(name) {
204 aliases.extend(
205 sub.get_visible_aliases()
206 .map(|alias| format!("{alias} for {name}")),
207 );
208 }
209 }
210 overview.push('\n');
211 }
212 if !aliases.is_empty() {
213 let last = aliases.len() - 1;
216 let words =
217 "Other names, as other version control systems have them:"
218 .split(' ')
219 .map(str::to_owned)
220 .chain(aliases.iter().enumerate().map(|(index, alias)| {
221 format!("{alias}{}", if index == last { "." } else { "," })
222 }));
223 let mut line = String::new();
224 for word in words {
225 if !line.is_empty() && line.len() + 1 + word.len() > 80 {
226 overview.push_str(&line);
227 overview.push('\n');
228 line.clear();
229 }
230 if !line.is_empty() {
231 line.push(' ');
232 }
233 line.push_str(&word);
234 }
235 overview.push_str(&line);
236 overview.push('\n');
237 }
238 overview.push_str("nib help COMMAND, or nib COMMAND --help, tells more of each.\n\n");
239 let template = format!(
241 "{{before-help}}{{about-with-newline}}\n{{usage-heading}} {{usage}}\n\n{overview}{header}Options:{header:#}\n{{options}}{{after-help}}"
242 );
243 command.help_template(template)
244}
245
246fn clock<E: Environment>(environment: &E) -> impl Fn() -> u64 + use<E> {
251 let system = || {
252 SystemTime::now()
253 .duration_since(UNIX_EPOCH)
254 .map_or(0, |since| {
255 i128::try_from(since.as_millis()).unwrap_or(i128::MAX)
256 })
257 };
258 let offset = i128::from(environment.now()) - system();
259 move || u64::try_from(system() + offset).unwrap_or(0)
260}
261
262#[derive(Debug, Subcommand)]
264pub enum Command {
265 #[command(group(
291 clap::ArgGroup::new("making")
292 .args(["name", "join", "device", "passphrase", "languages", "allow_fat"])
293 .multiple(true)
294 ))]
295 Init {
296 #[arg(conflicts_with = "making")]
298 folder: Option<PathBuf>,
299 #[arg(short, long, conflicts_with = "making")]
301 message: Option<String>,
302 #[arg(long, conflicts_with = "making")]
304 yes: bool,
305 #[arg(long)]
310 name: Option<String>,
311 #[arg(long)]
313 device: Option<String>,
314 #[arg(long)]
317 passphrase: bool,
318 #[arg(
322 long,
323 value_name = "RANGES",
324 value_parser = parse_languages,
325 conflicts_with = "join"
326 )]
327 languages: Option<Languages>,
328 #[arg(long, value_name = "CODE", value_parser = parse_code, conflicts_with = "name")]
331 join: Option<PairingCode>,
332 #[arg(long, requires = "join", conflicts_with = "name")]
337 secrets: bool,
338 #[arg(long)]
344 allow_fat: bool,
345 },
346 Languages {
351 #[arg(value_name = "RANGES")]
353 ranges: Option<String>,
354 #[arg(long, conflicts_with = "app")]
356 device: bool,
357 #[arg(long)]
359 app: bool,
360 #[arg(long, conflicts_with = "ranges")]
362 clear: bool,
363 },
364 #[command(visible_alias = "st")]
372 Status {
373 #[arg(long)]
375 library_wide: bool,
376 #[arg(long, conflicts_with = "library_wide")]
380 secrets: bool,
381 },
382 Verify {
386 #[arg(long, value_name = "FOLDER")]
389 export: Option<PathBuf>,
390 #[arg(long, conflicts_with = "export")]
394 drive_checked: bool,
395 },
396 New {
401 #[arg(value_name = "TYPES")]
405 kind: String,
406 values: Vec<String>,
408 #[arg(long, value_name = "TAG", value_parser = parse_tag)]
411 language: Option<Tag>,
412 },
413 Show {
415 entity: String,
417 #[arg(long, value_name = "DAY", value_parser = parse_day)]
419 on: Option<Day>,
420 #[arg(long, value_name = "WHEN", value_parser = parse_moment)]
425 as_of: Option<Moment>,
426 },
427 Move {
434 entity: String,
436 #[arg(long, value_name = "SPACE")]
438 to: String,
439 #[arg(long)]
441 without_history: bool,
442 #[arg(long)]
446 keep_behind: bool,
447 #[arg(long)]
451 leave_secrets: bool,
452 #[arg(long)]
455 yes: bool,
456 },
457 Merge {
462 entity: String,
464 #[arg(required_unless_present = "undo")]
467 other: Option<String>,
468 #[arg(long)]
470 undo: bool,
471 },
472 Export {
478 folder: PathBuf,
480 #[arg(long)]
484 current: bool,
485 },
486 Import {
502 #[arg(required = true, value_name = "PATH")]
505 paths: Vec<PathBuf>,
506 #[arg(long, value_name = "SOURCE")]
509 from: Option<String>,
510 },
511 History {
515 entity: String,
517 field: Option<String>,
519 },
520 Edit(EditArgs),
529 Purge {
537 #[arg(required_unless_present = "behind")]
539 entity: Option<String>,
540 #[arg(required_unless_present = "behind")]
542 value: Option<String>,
543 #[arg(long, conflicts_with = "value")]
547 behind: bool,
548 #[arg(long)]
550 yes: bool,
551 },
552 Find {
559 #[arg(required = true)]
561 words: Vec<String>,
562 #[arg(long)]
564 all: bool,
565 },
566 List {
574 #[arg(value_name = "TYPE")]
576 kind: Option<String>,
577 #[arg(long = "where", value_name = "FIELD=VALUE")]
581 conditions: Vec<String>,
582 #[arg(long, value_name = "FIELD")]
586 sort: Option<String>,
587 #[arg(long, value_name = "DAY", value_parser = parse_day)]
590 on: Option<Day>,
591 },
592 Type {
594 #[command(subcommand)]
596 command: TypeCommand,
597 },
598 File {
602 #[command(subcommand)]
604 command: FileCommand,
605 },
606 #[command(flatten)]
608 Trees(TreeCommand),
609 Protect {
615 #[arg(long)]
617 passphrase: bool,
618 #[arg(long)]
620 secrets: bool,
621 },
622 Secret {
628 #[command(subcommand)]
630 command: SecretCommand,
631 },
632 Policy {
639 #[command(subcommand)]
641 command: PolicyCommand,
642 },
643 Space {
648 #[command(subcommand)]
650 command: SpaceCommand,
651 },
652 Device {
656 #[command(subcommand)]
658 command: DeviceCommand,
659 },
660 Backup {
667 #[command(subcommand)]
669 command: BackupCommand,
670 },
671 Recovery {
678 #[command(subcommand)]
680 command: RecoveryCommand,
681 },
682 Purges {
691 #[command(subcommand)]
693 command: Option<PurgesCommand>,
694 },
695 #[command(visible_alias = "push")]
701 Sync {
702 #[arg(long, conflicts_with = "wait")]
707 serve: bool,
708 #[arg(long, value_name = "SECONDS", default_value_t = 10)]
711 wait: u64,
712 #[arg(long, value_name = "SWITCH", conflicts_with_all = ["serve", "wait"])]
717 at_login: Option<Switch>,
718 #[arg(
722 long,
723 value_name = "PORT",
724 env = "NIBKEEP_PORT",
725 default_value_t = nibkeep_node::DEFAULT_PORT
726 )]
727 port: u16,
728 },
729 Pull {
735 #[arg(long, value_name = "SECONDS", default_value_t = 10)]
737 wait: u64,
738 #[arg(long)]
740 partial: bool,
741 #[arg(long, conflicts_with = "no_clone")]
743 clone: bool,
744 #[arg(long)]
746 no_clone: bool,
747 },
748 #[command(subcommand_required = true, arg_required_else_help = true)]
753 Mcp {
754 #[command(subcommand)]
756 action: McpAction,
757 },
758 #[command(flatten)]
760 Absent(Absent),
761}
762
763#[derive(Debug, Subcommand)]
765pub enum McpAction {
766 Serve {
777 #[arg(long, value_name = "NAME")]
780 agent: Option<String>,
781 #[arg(long, value_name = "SECONDS", default_value_t = 2)]
783 wait: u64,
784 },
785 Enable {
792 #[arg(long, value_name = "CLIENT", conflicts_with = "print")]
794 client: Option<String>,
795 #[arg(long)]
798 print: bool,
799 },
800 Disable {
805 #[arg(long, value_name = "CLIENT")]
807 client: Option<String>,
808 },
809}
810
811#[derive(Debug, Subcommand)]
814pub enum Absent {
815 #[command(hide = true)]
817 Add(Rest),
818 #[command(hide = true)]
820 Checkout(Rest),
821 #[command(hide = true)]
823 Branch(Rest),
824 #[command(hide = true)]
826 Tag(Rest),
827 #[command(hide = true)]
829 Stash(Rest),
830 #[command(hide = true)]
832 Reset(Rest),
833 #[command(hide = true)]
835 Rebase(Rest),
836 #[command(hide = true)]
838 Fetch(Rest),
839}
840
841impl Absent {
842 const fn instead(&self) -> (&'static str, &'static str) {
844 const NO_BRANCHES: &str = "a tree has no branches or tags: what devices change apart competes, and nib update merges it";
845 match self {
846 Self::Add(_) => (
847 "add",
848 "nib commit takes in new files, and leaves out what .nibignore names",
849 ),
850 Self::Checkout(_) => (
851 "checkout",
852 "nib clone writes a tree into a folder, and nib restore writes a file as it was",
853 ),
854 Self::Branch(_) => ("branch", NO_BRANCHES),
855 Self::Tag(_) => ("tag", NO_BRANCHES),
856 Self::Rebase(_) => ("rebase", NO_BRANCHES),
857 Self::Stash(_) => (
858 "stash",
859 "a tree has no stash: nib restore writes a file as it was, and keeps your edits beside it",
860 ),
861 Self::Reset(_) => (
862 "reset",
863 "nib restore writes a file as it was, and nib revert undoes a revision",
864 ),
865 Self::Fetch(_) => (
866 "fetch",
867 "nib sync brings what your other devices recorded without writing it, and nib pull writes it too",
868 ),
869 }
870 }
871}
872
873#[derive(Debug, Args)]
875pub struct Rest {
876 #[arg(trailing_var_arg = true, allow_hyphen_values = true, hide = true)]
878 rest: Vec<String>,
879}
880
881#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
883pub enum Switch {
884 On,
886 Off,
888}
889
890#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
892pub enum NewSpacesArg {
893 Take,
895 Ask,
897}
898
899#[derive(Debug, Subcommand)]
901pub enum SpaceCommand {
902 New {
910 name: String,
912 #[arg(long)]
914 group: bool,
915 #[arg(long = "on", value_name = "DEVICE")]
919 on: Vec<String>,
920 },
921 AddGroup {
928 space: String,
930 group: String,
932 #[arg(long, value_enum, default_value_t = RoleArg::Editor)]
934 role: RoleArg,
935 },
936 RemoveGroup {
940 space: String,
942 group: String,
944 },
945 Agree {
949 group: String,
951 space: String,
953 },
954 Withdraw {
959 group: String,
961 space: String,
963 },
964 List,
971 Take {
977 #[arg(value_name = "SPACE")]
980 wanted: String,
981 },
982 Drop {
995 #[arg(value_name = "SPACE")]
998 wanted: String,
999 },
1000 Allow {
1004 space: String,
1006 device: String,
1008 },
1009 Show {
1019 space: String,
1021 },
1022 Rename {
1024 space: String,
1026 name: String,
1028 },
1029 Invite {
1036 space: String,
1038 #[arg(long, value_enum, default_value_t = RoleArg::Editor)]
1040 role: RoleArg,
1041 #[arg(long = "as", value_name = "PERSON")]
1044 person: Option<String>,
1045 #[arg(long)]
1047 yes: bool,
1048 #[command(flatten)]
1050 port: Port,
1051 },
1052 Join {
1058 code: PairingCode,
1060 #[arg(long)]
1062 yes: bool,
1063 #[arg(long = "on", value_name = "DEVICE")]
1066 on: Vec<String>,
1067 },
1068 AiAgents {
1073 space: String,
1075 #[arg(value_enum)]
1077 switch: Option<Switch>,
1078 },
1079 Link {
1085 space: String,
1087 member: String,
1089 person: Option<String>,
1091 },
1092 Leave {
1100 space: String,
1102 #[arg(long)]
1104 yes: bool,
1105 },
1106 Remove {
1114 space: String,
1116 member: String,
1119 #[arg(long)]
1121 yes: bool,
1122 },
1123 LetIn {
1127 space: String,
1129 member: String,
1131 },
1132 MakeDirect {
1138 space: String,
1140 member: String,
1142 #[arg(long, value_enum, default_value_t = RoleArg::Editor)]
1144 role: RoleArg,
1145 },
1146 Confirm {
1151 space: String,
1153 },
1154 Claim {
1161 space: String,
1163 #[arg(long)]
1165 yes: bool,
1166 },
1167 Reject {
1173 space: String,
1175 member: String,
1177 },
1178 Accept {
1185 space: String,
1187 member: String,
1189 #[arg(long)]
1191 yes: bool,
1192 },
1193 Role {
1195 space: String,
1197 member: String,
1199 #[arg(value_enum)]
1201 role: RoleArg,
1202 },
1203}
1204
1205#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
1207pub enum RoleArg {
1208 Viewer,
1210 Editor,
1212 Admin,
1214}
1215
1216impl RoleArg {
1217 const fn role(self) -> MemberRole {
1219 match self {
1220 Self::Viewer => MemberRole::Viewer,
1221 Self::Editor => MemberRole::Editor,
1222 Self::Admin => MemberRole::Admin,
1223 }
1224 }
1225}
1226
1227#[derive(Debug, Subcommand)]
1229pub enum PurgesCommand {
1230 Stop {
1237 purge: String,
1239 #[arg(long, value_name = "BACKUP")]
1242 on: Option<String>,
1243 #[arg(long)]
1245 yes: bool,
1246 },
1247 End {
1253 purge: String,
1255 #[arg(long, value_name = "BACKUP")]
1258 on: Option<String>,
1259 #[arg(long)]
1261 yes: bool,
1262 },
1263}
1264
1265#[derive(Debug, Subcommand)]
1267pub enum RecoveryCommand {
1268 New {
1274 #[arg(long)]
1277 secrets: bool,
1278 #[arg(long)]
1281 revoke_older: bool,
1282 },
1283 Confirm {
1287 #[arg(long)]
1290 secrets: bool,
1291 #[arg(long)]
1294 revoke_older: bool,
1295 },
1296 List,
1300 Check {
1302 #[arg(long)]
1304 secrets: bool,
1305 },
1306 Revoke {
1311 code: String,
1313 #[arg(long)]
1315 yes: bool,
1316 },
1317 Restore {
1330 #[arg(value_name = "SOURCE")]
1332 source: Option<PathBuf>,
1333 #[arg(long, value_name = "DEVICE")]
1338 keep: Vec<String>,
1339 #[command(flatten)]
1341 new: NewDevice,
1342 },
1343 FromCopy {
1352 #[command(flatten)]
1354 new: NewDevice,
1355 },
1356}
1357
1358#[derive(Debug, Args)]
1360pub struct NewDevice {
1361 #[arg(long)]
1363 pub device: Option<String>,
1364 #[arg(long)]
1366 pub passphrase: bool,
1367 #[arg(long)]
1372 pub allow_fat: bool,
1373}
1374
1375#[derive(Debug, Subcommand)]
1377pub enum BackupCommand {
1378 New {
1383 folder: PathBuf,
1385 #[arg(long)]
1387 name: Option<String>,
1388 #[arg(long = "of", value_name = "SPACE")]
1391 spaces: Vec<String>,
1392 #[arg(long = "policy", value_name = "POLICY")]
1396 policies: Vec<String>,
1397 #[arg(long)]
1400 away: bool,
1401 #[arg(long, value_name = "DAYS", value_parser = parse_waits)]
1406 waits: Option<Waits>,
1407 },
1408 List,
1413 Update {
1418 backup: Option<String>,
1420 #[arg(long, value_name = "FOLDER")]
1422 at: Option<PathBuf>,
1423 },
1424 Edit {
1429 backup: String,
1431 #[arg(long)]
1433 name: Option<String>,
1434 #[arg(long = "of", value_name = "SPACE")]
1436 spaces: Vec<String>,
1437 #[arg(
1439 long = "policy",
1440 value_name = "POLICY",
1441 conflicts_with = "every_policy"
1442 )]
1443 policies: Vec<String>,
1444 #[arg(long)]
1446 every_policy: bool,
1447 #[arg(long, conflicts_with = "home")]
1449 away: bool,
1450 #[arg(long)]
1452 home: bool,
1453 #[arg(long, value_name = "DAYS", value_parser = parse_waits)]
1456 waits: Option<Waits>,
1457 },
1458 Remove {
1462 backup: String,
1464 },
1465}
1466
1467#[derive(Debug, Subcommand)]
1469pub enum DeviceCommand {
1470 Pair {
1479 #[arg(long, value_name = "NAME")]
1484 ai_agent: Option<String>,
1485 #[arg(long, conflicts_with = "ai_agent")]
1488 phone: bool,
1489 #[arg(long = "in", value_name = "SPACE")]
1496 spaces: Vec<String>,
1497 #[arg(long, conflicts_with = "ai_agent")]
1501 give_secrets: bool,
1502 #[command(flatten)]
1504 port: Port,
1505 },
1506 List,
1511 Revoke {
1518 device: String,
1521 #[arg(long)]
1523 yes: bool,
1524 #[arg(long)]
1527 codes: bool,
1528 },
1529 Mark {
1537 device: String,
1539 #[arg(long, conflicts_with = "everyday")]
1541 archive: bool,
1542 #[arg(long)]
1544 everyday: bool,
1545 #[arg(long, conflicts_with = "home")]
1547 away: bool,
1548 #[arg(long)]
1550 home: bool,
1551 #[arg(long, value_name = "SIZE", value_parser = parse_keeps)]
1555 keeps: Option<Keeps>,
1556 #[arg(long, value_name = "DAYS", value_parser = parse_waits)]
1561 waits: Option<Waits>,
1562 #[arg(long, value_enum, value_name = "take|ask")]
1567 new_spaces: Option<NewSpacesArg>,
1568 },
1569 Review,
1574 Accept {
1580 device: String,
1583 #[arg(long)]
1585 yes: bool,
1586 },
1587}
1588
1589#[derive(Debug, Args)]
1591pub struct EditArgs {
1592 entity: String,
1594 #[arg(required_unless_present_any = ["delete", "restore"])]
1596 changes: Vec<String>,
1597 #[arg(long, value_name = "DATE", value_parser = parse_edtf)]
1600 date: Option<Edtf>,
1601 #[arg(long, value_name = "DAY", value_parser = parse_day)]
1604 on: Option<Day>,
1605 #[arg(long, conflicts_with = "restore")]
1607 delete: bool,
1608 #[arg(long)]
1610 restore: bool,
1611 #[arg(long, value_name = "TAG", value_parser = parse_tag)]
1614 language: Option<Tag>,
1615 #[arg(long, conflicts_with = "form_of")]
1619 form: bool,
1620 #[arg(long, value_name = "VALUE")]
1622 form_of: Option<String>,
1623}
1624
1625#[derive(Clone, Copy, Debug)]
1627enum Forms<'a> {
1628 No,
1630 OfTheOnly,
1632 Of(&'a str),
1634}
1635
1636#[derive(Debug, Subcommand)]
1638pub enum TypeCommand {
1639 Add {
1645 name: String,
1647 fields: Vec<String>,
1654 },
1655 Show {
1657 name: String,
1659 },
1660 List,
1662}
1663
1664#[derive(Debug, Subcommand)]
1666pub enum FileCommand {
1667 Add {
1685 #[arg(required = true)]
1687 paths: Vec<PathBuf>,
1688 #[arg(long)]
1690 secret: bool,
1691 #[arg(long, value_name = "ENTITY", requires = "secret")]
1693 to: Vec<String>,
1694 #[arg(long, value_name = "SOURCE", conflicts_with = "secret")]
1698 from: Option<String>,
1699 },
1700 Checkout {
1708 file: String,
1710 path: Option<PathBuf>,
1712 },
1713 Where {
1720 file: String,
1722 },
1723 #[command(hide = true)]
1732 Thumbnail {
1733 file: String,
1735 path: PathBuf,
1737 },
1738 Thumbnails,
1744 Pin {
1750 file: String,
1752 #[arg(long)]
1754 device: Option<String>,
1755 },
1756 Unpin {
1761 file: String,
1763 #[arg(long)]
1765 device: Option<String>,
1766 },
1767 Checkin {
1774 copy: String,
1776 #[arg(long)]
1778 keep: bool,
1779 #[arg(long)]
1782 force: bool,
1783 },
1784}
1785
1786#[derive(Debug, Subcommand)]
1789pub enum SecretCommand {
1790 Set {
1798 entity: String,
1800 field: String,
1802 #[arg(long)]
1804 generate: bool,
1805 #[command(flatten)]
1807 recipe: RecipeArgs,
1808 },
1809 Copy {
1816 entity: String,
1818 field: String,
1820 #[arg(long, value_name = "SECONDS", default_value_t = nibkeep_passwords::CLEAR_AFTER.as_secs())]
1822 clear_after: u64,
1823 },
1824 Generate {
1828 #[command(flatten)]
1830 recipe: RecipeArgs,
1831 },
1832 Code {
1837 entity: String,
1839 field: Option<String>,
1841 },
1842 Show {
1844 entity: String,
1846 field: String,
1848 },
1849 History {
1853 entity: String,
1855 field: String,
1857 },
1858 Clear {
1862 entity: String,
1864 field: String,
1866 },
1867 Purge {
1872 entity: String,
1874 field: String,
1876 #[arg(long)]
1878 yes: bool,
1879 },
1880 Ask {
1893 from: String,
1895 },
1896 Give {
1904 device: String,
1906 },
1907 FromCopy,
1915 Save {
1921 file: String,
1923 path: Option<PathBuf>,
1925 },
1926}
1927
1928#[derive(Debug, Clone, PartialEq, Eq, Args)]
1931#[expect(
1932 clippy::struct_excessive_bools,
1933 reason = "one flag for each kind of character, as nibkeep_passwords::Recipe has"
1934)]
1935pub struct RecipeArgs {
1936 #[arg(long)]
1938 pub length: Option<usize>,
1939 #[arg(long)]
1941 pub no_lowercase: bool,
1942 #[arg(long)]
1944 pub no_uppercase: bool,
1945 #[arg(long)]
1947 pub no_digits: bool,
1948 #[arg(long)]
1950 pub no_symbols: bool,
1951 #[arg(long)]
1953 pub unambiguous: bool,
1954}
1955
1956impl RecipeArgs {
1957 fn recipe(&self) -> nibkeep_passwords::Recipe {
1959 let default = nibkeep_passwords::Recipe::default();
1960 nibkeep_passwords::Recipe {
1961 length: self.length.unwrap_or(default.length),
1962 lowercase: !self.no_lowercase,
1963 uppercase: !self.no_uppercase,
1964 digits: !self.no_digits,
1965 symbols: !self.no_symbols,
1966 unambiguous: self.unambiguous,
1967 }
1968 }
1969
1970 fn given(&self) -> bool {
1972 self.length.is_some()
1973 || self.no_lowercase
1974 || self.no_uppercase
1975 || self.no_digits
1976 || self.no_symbols
1977 || self.unambiguous
1978 }
1979}
1980
1981#[derive(Debug, Subcommand)]
1984pub enum PolicyCommand {
1985 List,
1987 Show {
1989 policy: String,
1991 },
1992 New {
1994 name: String,
1996 #[arg(long, default_value_t = 1)]
1998 copies: u32,
1999 #[arg(long, default_value_t = 0)]
2001 away: u32,
2002 #[arg(long, default_value_t = 0)]
2004 archived: u32,
2005 #[arg(long)]
2007 in_place: bool,
2008 },
2009 Edit {
2011 policy: String,
2013 #[arg(long)]
2015 name: Option<String>,
2016 #[arg(long)]
2018 copies: Option<u32>,
2019 #[arg(long)]
2021 away: Option<u32>,
2022 #[arg(long)]
2024 archived: Option<u32>,
2025 #[arg(long, conflicts_with = "store")]
2027 in_place: bool,
2028 #[arg(long)]
2030 store: bool,
2031 },
2032 Remove {
2037 policy: String,
2039 },
2040 Rule {
2042 #[command(subcommand)]
2044 command: RuleCommand,
2045 },
2046 Set {
2050 entity: String,
2052 #[arg(required_unless_present = "clear")]
2054 policy: Option<String>,
2055 #[arg(long, conflicts_with = "policy")]
2057 clear: bool,
2058 },
2059 Why {
2061 entity: String,
2063 },
2064 Check,
2068}
2069
2070#[derive(Debug, Subcommand)]
2072pub enum RuleCommand {
2073 New {
2077 policy: String,
2079 #[arg(long = "type", value_name = "TYPE")]
2081 of_type: Option<String>,
2082 #[arg(long, value_name = "FIELD")]
2084 has: Option<String>,
2085 #[arg(long, value_name = "FOLDER")]
2087 folder: Option<PathBuf>,
2088 #[arg(long, value_name = "TYPE")]
2090 media_type: Option<String>,
2091 #[arg(long, value_name = "SIZE", value_parser = parse_size)]
2093 larger_than: Option<u64>,
2094 #[arg(long, value_name = "SIZE", value_parser = parse_size)]
2096 asks_above: Option<u64>,
2097 #[command(flatten)]
2099 place: PlaceArgs,
2100 },
2101 Remove {
2103 rule: String,
2105 },
2106 Move {
2108 rule: String,
2110 #[command(flatten)]
2112 place: PlaceArgs,
2113 },
2114}
2115
2116#[derive(Debug, Args)]
2118pub struct PlaceArgs {
2119 #[arg(long, conflicts_with_all = ["last", "before", "after"])]
2121 first: bool,
2122 #[arg(long, conflicts_with_all = ["before", "after"])]
2124 last: bool,
2125 #[arg(long, value_name = "RULE", conflicts_with = "after")]
2127 before: Option<String>,
2128 #[arg(long, value_name = "RULE")]
2130 after: Option<String>,
2131}
2132
2133const LINKS_SHOWN: usize = 10;
2135
2136#[derive(Debug, thiserror::Error)]
2138#[non_exhaustive]
2139pub enum CliError {
2140 #[error("{0}")]
2142 Import(String),
2143 #[error(
2146 "{0} has no thumbnail: the device that added it could not read its format, or it is no picture"
2147 )]
2148 NoThumbnail(String),
2149 #[error("{} exists already", .0.display())]
2151 Exists(PathBuf),
2152 #[error(
2154 "this folder is not in a library; if it is a tree's folder that lost its .nib file, run nib init FOLDER in your library's folder; otherwise make a library with nib init, or give one with --library or NIBKEEP_LIBRARY"
2155 )]
2156 NotInLibrary,
2157 #[error("there is no library in {}", .0.display())]
2159 NoLibraryIn(PathBuf),
2160 #[error(
2163 "nib may not read {folder}: {error}; on a Mac, allow your terminal to reach removable volumes, in System Settings, Privacy & Security, Files and Folders",
2164 folder = .0.display(),
2165 error = .1
2166 )]
2167 NoAccess(PathBuf, #[source] io::Error),
2168 #[error("there is no library in {}, which NIBKEEP_LIBRARY names", .0.display())]
2170 NoDefaultLibrary(PathBuf),
2171 #[error("NIBKEEP_LIBRARY names {}, which is not a full path", .0.display())]
2173 RelativeDefault(PathBuf),
2174 #[error(
2176 "a library was started in {}, but not finished; remove that folder to start again",
2177 .0.display()
2178 )]
2179 Unfinished(PathBuf),
2180 #[error(
2183 "the library in {} is a copy, made on another computer or drive, or in another folder, and is never used here as the device it was; to make this computer a device of its own, add it from another of your devices with nib device pair there and nib init --join here, which takes in what the copy holds, or, where no other device of yours can, use nib recovery from-copy",
2184 .0.display()
2185 )]
2186 IsCopy(PathBuf),
2187 #[error("no secrets were taken from a copy")]
2190 NoSecretsInCopies,
2191 #[error("there is no copy of a library in {}", .0.display())]
2193 NoCopy(PathBuf),
2194 #[error("{} holds copies of several libraries' devices; keep the one to use", .0.display())]
2196 SeveralCopies(PathBuf),
2197 #[error(
2200 "{} holds a copy of a library made on another computer or drive, or in another folder; join that library with nib init --join, or start one elsewhere",
2201 .0.display()
2202 )]
2203 CopiedHere(PathBuf),
2204 #[error(
2207 "{} is on a drive whose file system keeps no journal, as FAT32 and exFAT, which most USB sticks have: a library there can be damaged after the drive is removed without ejecting it, or loses its power; keep the library on another drive, or run again with --allow-fat to keep it there, and check the drive for errors after any such removal",
2208 .0.display()
2209 )]
2210 NoJournal(PathBuf),
2211 #[error(
2214 "the library in {} was not closed: its drive was removed without ejecting it, or lost its power, while the library was open, or a program that had it open was stopped, so its files may be damaged; check the drive for errors first, with Scan and fix on Windows, First Aid on a Mac or fsck on Linux, then run nib verify --drive-checked",
2215 .0.display()
2216 )]
2217 UncleanRemoval(PathBuf),
2218 #[error("{} is in a library's own folder .nib; start the library elsewhere", .0.display())]
2220 InLibraryData(PathBuf),
2221 #[error("the current folder cannot be found: {0}")]
2223 NoCurrentFolder(#[source] io::Error),
2224 #[error(transparent)]
2226 Languages(#[from] ParseLanguagesError),
2227 #[error("--form adds and removes forms with field+=value and field-=value; there are none")]
2229 NoForms,
2230 #[error("{entity} and {into} are one entity already")]
2232 OneAlready {
2233 entity: String,
2235 into: String,
2237 },
2238 #[error("no entity was merged into {0}")]
2240 NothingMerged(String),
2241 #[error("say which entity to set apart from {entity}: {candidates}")]
2243 WhichMerged {
2244 entity: String,
2246 candidates: String,
2248 },
2249 #[error("no entity merged into {entity} is {other}")]
2251 NotMergedInto {
2252 entity: String,
2254 other: String,
2256 },
2257 #[error("the entity never had a field {0}")]
2259 NoHistory(String),
2260 #[error("the moment cannot be used: {0}")]
2262 Moment(String),
2263 #[error("the library had no record of {entity} by {when}")]
2265 NotYet {
2266 entity: String,
2268 when: String,
2270 },
2271 #[error("the passphrases differ")]
2273 PassphrasesDiffer,
2274 #[error(
2276 "{} was checked out from a version that is no longer the file's own; --force records its edits on top, and history keeps both",
2277 .0.display()
2278 )]
2279 Stale(PathBuf),
2280 #[error("{}", files_failed(*.0))]
2282 FilesFailed(usize),
2283 #[error(
2286 "{name} is not on this device, and no device that holds it was found on the network: {}",
2287 holders.join(", ")
2288 )]
2289 NotFetched {
2290 name: String,
2292 holders: Vec<String>,
2294 },
2295 #[error(
2298 "{name} is not on this device, and did not come from {}, which hold it as their accounts say; they may have lost it, which nib verify there tells",
2299 holders.join(", ")
2300 )]
2301 NotGiven {
2302 name: String,
2304 holders: Vec<String>,
2306 },
2307 #[error("{}", syncs_failed(*.0))]
2309 SyncsFailed(usize),
2310 #[error("{0} did not sync in time; it may be busy with a long sync")]
2312 NotAnswered(String),
2313 #[error(
2315 "AI agents are not allowed on this library here; allow them with nib mcp enable in its folder"
2316 )]
2317 NotAnAiAgent,
2318 #[error(
2320 "nib knows no AI client {0}; it knows Claude Code (claude) and Codex (codex), and --print gives the line for any other"
2321 )]
2322 UnknownAiClient(String),
2323 #[error(
2325 "nib mcp serve asks for nothing on a terminal; give the library's passphrase with --passphrase-file"
2326 )]
2327 NoTerminal,
2328 #[error("the values differ")]
2330 ValuesDiffer,
2331 #[error("the value is empty")]
2333 EmptyValue,
2334 #[error(
2336 "{0} is secret: nib secret set asks for its value without showing it, and nib secret clear clears it"
2337 )]
2338 SecretField(nibkeep_model::FieldName),
2339 #[error(
2341 "{0} is secret, and its values are not given on the command line: nib secret purge asks for one without showing it, and {0}= purges every value it has had"
2342 )]
2343 SecretGiven(nibkeep_model::FieldName),
2344 #[error("{0} is secret: nib secret history shows the values it has had")]
2346 SecretHistory(nibkeep_model::FieldName),
2347 #[error("{} is a folder; nib file add --secret adds files one by one", .0.display())]
2349 SecretFolder(PathBuf),
2350 #[error(
2352 "{0} is a secret file, of which NibKeep records no copies; nib secret save writes one that nothing keeps track of"
2353 )]
2354 SecretFileCheckout(String),
2355 #[error("{0} is not secret; nib show and nib edit read and set it")]
2357 NotSecret(nibkeep_model::FieldName),
2358 #[error(transparent)]
2360 Generator(#[from] nibkeep_passwords::GeneratorError),
2361 #[error(transparent)]
2363 OneTime(#[from] nibkeep_passwords::OneTimeError),
2364 #[error(transparent)]
2366 Clipboard(#[from] nibkeep_passwords::ClipboardError),
2367 #[error("--length and the --no- options say what --generate makes; give --generate too")]
2369 RecipeWithoutGenerate,
2370 #[error(
2372 "{0} holds the secret of one-time codes, which the site gives; --generate makes passwords"
2373 )]
2374 GeneratedOneTimeCode(nibkeep_model::FieldName),
2375 #[error("there is no rule {0}; nib policy list numbers the rules")]
2377 NoRule(String),
2378 #[error("say where the rule goes: --first, --last, --before RULE or --after RULE")]
2380 WhereTo,
2381 #[error("the library holds no secrets yet; nib secret set stores the first")]
2383 NoSecrets,
2384 #[error("{entity} has no value of {field}")]
2386 NoSecretValue {
2387 entity: String,
2389 field: nibkeep_model::FieldName,
2391 },
2392 #[error("the passphrase is empty")]
2394 EmptyPassphrase,
2395 #[error("the passphrase file {} cannot be read: {error}", path.display())]
2397 PassphraseFile {
2398 path: PathBuf,
2400 error: io::Error,
2402 },
2403 #[error("others can read the passphrase file {}; make it yours alone, such as with chmod 600", .0.display())]
2405 PassphraseFileOpen(PathBuf),
2406 #[error(
2408 "syncing from login needs the library's keys in the keystore, as nobody is there to type a passphrase at login; nib protect puts them there"
2409 )]
2410 AtLoginPassphrase,
2411 #[error("there is no home folder here to keep the list of libraries synced from login in")]
2413 NoStateFolder,
2414 #[error(
2416 "nibkeep-sync, which syncs from login, is not installed beside nib; cargo install --path apps/nib installs both"
2417 )]
2418 NoSyncProgram,
2419 #[error("the library's keys are in the platform's keystore, which is not available")]
2421 NoKeystore,
2422 #[error("the platform's keystore failed ({0}); start the library with --passphrase instead")]
2424 Keystore(NodeError),
2425 #[error(
2427 "there is no platform keystore here; nib protect --passphrase protects with a passphrase"
2428 )]
2429 NoKeystoreToProtect,
2430 #[error(
2432 "the platform's keystore failed ({0}); nib protect --passphrase protects with a passphrase"
2433 )]
2434 KeystoreToProtect(NodeError),
2435 #[error("{0} is not a valid name")]
2437 Name(String),
2438 #[error(
2441 "{name} is a standard name, which only the standard vocabulary gives; choose another \
2442 {what} name, such as one starting with local."
2443 )]
2444 StandardName {
2445 name: String,
2447 what: &'static str,
2449 },
2450 #[error(
2452 "a field is name:kind, with flags such as :many, :lww, :secret or :role after it, not {0}"
2453 )]
2454 Field(String),
2455 #[error("there is no kind of value called {kind}; the kinds are {kinds}")]
2457 Kind {
2458 kind: String,
2460 kinds: String,
2462 },
2463 #[error(
2465 "there is no flag {0} for a field; the flags are many, lww, secret, role, stands-for, search-through, code, unit= and reverse="
2466 )]
2467 Flag(String),
2468 #[error("{0}")]
2470 Flags(String),
2471 #[error("there is no type {0}; define it with nib type add")]
2473 NoType(TypeName),
2474 #[error("{name} could be any of the types {candidates}")]
2476 AmbiguousType {
2477 name: String,
2479 candidates: String,
2481 },
2482 #[error(
2484 "{types} has no field {field}; give its full name, such as local.{field}, for a field that no type defines"
2485 )]
2486 NoField {
2487 field: String,
2489 types: String,
2491 },
2492 #[error("{field} could be any of the fields {candidates}")]
2494 AmbiguousField {
2495 field: String,
2497 candidates: String,
2499 },
2500 #[error("an entity's types are given with type+=TYPE and taken away with type-=TYPE")]
2502 TypeSet,
2503 #[error("a value is field=value, not {0}")]
2505 Assignment(String),
2506 #[error("{}", unsound(*.0))]
2508 Unsound(usize),
2509 #[error("{}", unsound_export(*.0))]
2511 UnsoundExport(usize),
2512 #[error("nothing was purged; add --yes to purge for good")]
2514 Unconfirmed,
2515 #[error("nothing was moved; add --yes to move them all")]
2517 UnconfirmedMove,
2518 #[error("no tree was started; add --yes to start it")]
2520 UnconfirmedStart,
2521 #[error("{} holds no Git repository with a commit to pin", .0.display())]
2523 NoGitCommit(PathBuf),
2524 #[error("{} is in no tree's folder on this device; nib init makes it one", .0.display())]
2526 NotInTree(PathBuf),
2527 #[error(
2530 "{} is in no tree's folder on this device: name a tree with --tree, or see an entity's values with nib history",
2531 .0.display()
2532 )]
2533 NoTreeHere(PathBuf),
2534 #[error(
2537 "neither {} nor the current folder is in a library: run nib init FOLDER in your library's folder, nib init alone to make a library here, or nib init --join CODE to join yours from another device",
2538 .0.display()
2539 )]
2540 NoLibraryForTree(PathBuf),
2541 #[error("{} should name the library of the tree in its folder, but {why}", .file.display())]
2543 BadPointer {
2544 file: PathBuf,
2546 why: String,
2548 },
2549 #[error(
2552 "{} names the library in {}, which keeps no tree in that folder on this device: nib init there makes the folder a tree, and deleting the file leaves the folder out of the library",
2553 .file.display(),
2554 .library.display()
2555 )]
2556 StrayPointer {
2557 file: PathBuf,
2559 library: PathBuf,
2561 },
2562 #[error(
2565 "{} names the library for the commands of the tree in its folder; run this in the library's folder, or name the library with --library",
2566 .0.display()
2567 )]
2568 ThroughPointer(PathBuf),
2569 #[error(
2572 "{} is no file: nib keeps a file there that names the library of a tree outside the library's folder",
2573 .0.display()
2574 )]
2575 PointerInTheWay(PathBuf),
2576 #[error(
2578 "{} could not be written: {error}; the tree is there, and nib init {} in the library's folder writes the file again",
2579 .file.display(),
2580 pointer::folder_of(.file)
2581 )]
2582 PointerNotWritten {
2583 file: PathBuf,
2585 error: io::Error,
2587 },
2588 #[error(
2591 "{} could not be deleted: {error}; the tree is there, and once the file is gone, commands in {} find the library",
2592 .file.display(),
2593 pointer::folder_of(.file)
2594 )]
2595 PointerNotTakenAway {
2596 file: PathBuf,
2598 error: io::Error,
2600 },
2601 #[error("the system names no account for you: give your name with nib init --name YOUR-NAME")]
2603 NoAccountName,
2604 #[error("there is no {verb} command: {instead}")]
2606 NoSuchCommand {
2607 verb: &'static str,
2609 instead: &'static str,
2611 },
2612 #[error(
2614 "{0} is no revision: nib revert undoes a revision, and nib restore {0} writes a file as it was"
2615 )]
2616 RevertTakesRevision(String),
2617 #[error("nothing was revoked; add --yes to revoke for good")]
2619 UnconfirmedRevoke,
2620 #[error("only {0} says whether it takes new spaces: run nib device mark --new-spaces there")]
2622 NewSpacesElsewhere(String),
2623 #[error("that was no recovery code; nothing was changed")]
2625 NotARecoveryCode,
2626 #[error(
2629 "the library here still unlocks with this computer's keystore: there is nothing to recover, and a recovery would only revoke it"
2630 )]
2631 StillUnlocks,
2632 #[error("the library names no such recovery code")]
2634 UnknownRecoveryCode,
2635 #[error("nothing was accepted; add --yes to accept them")]
2637 UnconfirmedAccept,
2638 #[error("you did not leave; add --yes to leave")]
2640 UnconfirmedLeave,
2641 #[error("nobody was removed; add --yes to remove them")]
2643 UnconfirmedRemove,
2644 #[error("nothing was claimed; add --yes to claim the admin role")]
2646 UnconfirmedClaim,
2647 #[error(
2650 "nobody can be asked whether to add whoever joins, as there is no terminal; run it on a terminal, or add --yes to add whoever joins with the code"
2651 )]
2652 UnconfirmedInvite,
2653 #[error("{0} is both set and cleared")]
2655 SetAndCleared(nibkeep_model::FieldName),
2656 #[error("{field} takes {expected}")]
2658 Value {
2659 field: nibkeep_model::FieldName,
2661 expected: &'static str,
2663 },
2664 #[error(
2666 "{reference} could be any of {count} entities; give the ID, or its start:\n{candidates}"
2667 )]
2668 Ambiguous {
2669 reference: String,
2671 count: usize,
2673 candidates: String,
2675 },
2676 #[error(transparent)]
2678 Node(#[from] NodeError),
2679 #[error(transparent)]
2681 Io(#[from] std::io::Error),
2682}
2683
2684#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2687pub struct Timings {
2688 pub waiting: Option<Duration>,
2690 pub unlock: Option<Duration>,
2693 pub open: Option<Duration>,
2695 pub work: Duration,
2697 pub print: Duration,
2699}
2700
2701impl Timings {
2702 fn parts(&self) -> Vec<(&'static str, Duration)> {
2704 let mut parts = Vec::new();
2705 for (name, part) in [
2706 ("waiting", self.waiting),
2707 ("unlock", self.unlock),
2708 ("open", self.open),
2709 ] {
2710 if let Some(duration) = part {
2711 parts.push((name, duration));
2712 }
2713 }
2714 parts.push(("work", self.work));
2715 parts.push(("print", self.print));
2716 parts
2717 }
2718
2719 #[must_use]
2723 pub fn describe(&self, json: bool) -> String {
2724 let parts = self.parts();
2725 if json {
2726 let object: serde_json::Map<String, serde_json::Value> = parts
2727 .iter()
2728 .map(|(part, duration)| (format!("{part}_seconds"), duration.as_secs_f64().into()))
2729 .collect();
2730 return serde_json::Value::Object(object).to_string();
2731 }
2732 parts
2733 .iter()
2734 .map(|(part, duration)| format!("{part} {:.3} s", duration.as_secs_f64()))
2735 .collect::<Vec<_>>()
2736 .join(", ")
2737 }
2738
2739 fn before_work(&self) -> Duration {
2741 [self.waiting, self.unlock, self.open]
2742 .into_iter()
2743 .flatten()
2744 .sum()
2745 }
2746}
2747
2748fn add(part: &mut Option<Duration>, duration: Duration) {
2750 *part = Some(part.unwrap_or_default() + duration);
2751}
2752
2753pub fn run<E: Environment>(
2759 cli: &Cli,
2760 environment: &mut E,
2761 output: &mut dyn Write,
2762) -> Result<(), CliError> {
2763 run_command(cli, environment, output, &mut Timings::default())
2765}
2766
2767pub fn run_timed<E: Environment>(
2773 cli: &Cli,
2774 environment: &mut E,
2775 output: &mut dyn Write,
2776) -> Result<Timings, CliError> {
2777 let started = Instant::now();
2778 let mut timings = Timings::default();
2779 let mut timed = Timed {
2780 inner: output,
2781 spent: Duration::ZERO,
2782 };
2783 run_command(cli, environment, &mut timed, &mut timings)?;
2784 timed.flush()?;
2786 timings.print = timed.spent;
2787 timings.work = started
2788 .elapsed()
2789 .saturating_sub(timings.before_work() + timings.print);
2790 Ok(timings)
2791}
2792
2793#[must_use]
2801pub fn printable(line: &str) -> std::borrow::Cow<'_, str> {
2802 fn hidden(c: char) -> bool {
2803 (c.is_control() && c != '\n')
2804 || matches!(c, '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}')
2805 }
2806 if !line.chars().any(hidden) {
2807 return line.into();
2808 }
2809 line.chars()
2810 .map(|c| {
2811 if hidden(c) {
2812 c.escape_debug().to_string()
2813 } else {
2814 c.to_string()
2815 }
2816 })
2817 .collect::<String>()
2818 .into()
2819}
2820
2821pub struct UntilUnread<W> {
2825 inner: W,
2826 unread: bool,
2827}
2828
2829impl<W> UntilUnread<W> {
2830 pub const fn new(inner: W) -> Self {
2832 Self {
2833 inner,
2834 unread: false,
2835 }
2836 }
2837
2838 fn read_or_not<T>(&mut self, done: io::Result<T>, nothing: T) -> io::Result<T> {
2840 match done {
2841 Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {
2842 self.unread = true;
2843 Ok(nothing)
2844 }
2845 done => done,
2846 }
2847 }
2848}
2849
2850impl<W: Write> Write for UntilUnread<W> {
2851 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2852 if self.unread {
2853 return Ok(bytes.len());
2854 }
2855 let written = self.inner.write(bytes);
2856 self.read_or_not(written, bytes.len())
2857 }
2858
2859 fn flush(&mut self) -> io::Result<()> {
2860 if self.unread {
2861 return Ok(());
2862 }
2863 let flushed = self.inner.flush();
2864 self.read_or_not(flushed, ())
2865 }
2866}
2867
2868struct Timed<'a> {
2870 inner: &'a mut dyn Write,
2871 spent: Duration,
2872}
2873
2874impl Write for Timed<'_> {
2875 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2876 let started = Instant::now();
2877 let written = self.inner.write(bytes);
2878 self.spent += started.elapsed();
2879 written
2880 }
2881
2882 fn flush(&mut self) -> io::Result<()> {
2883 let started = Instant::now();
2884 let flushed = self.inner.flush();
2885 self.spent += started.elapsed();
2886 flushed
2887 }
2888}
2889
2890fn run_command<E: Environment>(
2891 cli: &Cli,
2892 environment: &mut E,
2893 output: &mut dyn Write,
2894 timings: &mut Timings,
2895) -> Result<(), CliError> {
2896 nibkeep_node::name_program(APP);
2898 if let Command::Absent(absent) = &cli.command {
2899 let (verb, instead) = absent.instead();
2900 return Err(CliError::NoSuchCommand { verb, instead });
2901 }
2902 if let Command::Secret {
2903 command: SecretCommand::Generate { recipe },
2904 } = &cli.command
2905 {
2906 return generate_command(recipe, cli.json, environment, output);
2907 }
2908 let (found, making) = command_folder(cli, environment)?;
2909 place_not_through_pointer(cli, &found)?;
2910 let folder = found.folder.clone();
2911 let directory = folder.join(LIBRARY_DATA);
2912 if let Command::Mcp {
2913 action: McpAction::Serve { .. },
2914 } = &cli.command
2915 {
2916 return mcp::serve(cli, environment, output);
2917 }
2918 if making {
2919 let library = new_library(&directory, cli, environment, timings, output)?;
2920 let zone = environment.time_zone();
2921 let checks = output::Checks {
2922 status: None,
2923 name_of: &|_, _| None,
2924 zone: &zone,
2925 };
2926 let status = (
2927 &library.status()?,
2928 &[][..],
2929 &std::collections::BTreeMap::new(),
2930 );
2931 return output::status(status, checks, &folder, cli.json, output);
2932 }
2933 if let Command::Verify {
2934 drive_checked: true,
2935 ..
2936 } = &cli.command
2937 {
2938 Library::drive_checked(&directory)?;
2939 }
2940 if let Command::Sync {
2941 at_login: Some(switch),
2942 ..
2943 } = &cli.command
2944 {
2945 return at_login_command(*switch, &directory, cli, environment, timings, output);
2946 }
2947 let opened = open(
2948 &directory,
2949 cli.passphrase_file.as_deref(),
2950 environment,
2951 timings,
2952 );
2953 let mut library = opened.map_err(|error| opened_error(error, &directory))?;
2954 check_found(&library, &found, cli, environment)?;
2955 if library.told_of_syncing()? {
2956 environment.note(SYNCED_BY_PROGRAM);
2957 }
2958 if let Some(space) = &cli.space {
2959 let space = library.find_space(space)?;
2960 library.choose_space(Some(space))?;
2961 }
2962 if let Command::Sync { serve: true, .. } = &cli.command {
2963 return serve_command(library, cli, environment, output);
2964 }
2965 if let Command::Secret {
2966 command: SecretCommand::Copy {
2967 entity,
2968 field,
2969 clear_after,
2970 },
2971 } = &cli.command
2972 {
2973 let board = environment.clipboard()?;
2976 let read = read_secret(&mut library, entity, field, environment, timings)
2977 .map_err(|error| candidates_named(&library, error, environment))?;
2978 drop(library);
2979 return copy_and_clear(board, &read, *clear_after, cli.json, environment, output);
2980 }
2981 let ran = match &cli.command {
2982 Command::Backup { .. } | Command::Recovery { .. } => {
2983 safekeeping_command(&mut library, cli, environment, timings, output)
2984 }
2985 Command::Purges { command } => purges_waiting_command(
2986 &mut library,
2987 command.as_ref(),
2988 cli.json,
2989 environment,
2990 output,
2991 ),
2992 _ => library_command(&mut library, cli, &folder, environment, timings, output),
2993 };
2994 ran.map_err(|error| candidates_named(&library, error, environment))
2996}
2997
2998fn place_not_through_pointer(cli: &Cli, found: &Found) -> Result<(), CliError> {
3002 let place = matches!(
3003 &cli.command,
3004 Command::Verify {
3005 drive_checked: true,
3006 ..
3007 } | Command::Sync {
3008 at_login: Some(_),
3009 ..
3010 }
3011 );
3012 match &found.named_in {
3013 Some(file) if place => Err(CliError::ThroughPointer(file.clone())),
3014 _ => Ok(()),
3015 }
3016}
3017
3018fn check_found<E: Environment>(
3022 library: &Library,
3023 found: &Found,
3024 cli: &Cli,
3025 environment: &E,
3026) -> Result<(), CliError> {
3027 let starting = match &cli.command {
3028 Command::Init { folder, .. } => Some(match folder {
3029 Some(folder) => absolute(folder, environment)?,
3030 None => current_dir(environment)?,
3031 }),
3032 _ => None,
3033 };
3034 Ok(pointer::check(library, found, starting.as_deref())?)
3035}
3036
3037fn command_folder<E: Environment>(cli: &Cli, environment: &E) -> Result<(Found, bool), CliError> {
3042 if cli.command.makes_library() {
3043 return Ok((
3044 Found::library(new_library_folder(cli.library.as_deref(), environment)?),
3045 true,
3046 ));
3047 }
3048 if let Command::Init {
3049 folder,
3050 message,
3051 yes,
3052 ..
3053 } = &cli.command
3054 {
3055 let from = match folder {
3058 Some(folder) => absolute(folder, environment)?,
3059 None => current_dir(environment)?,
3060 };
3061 let here = environment.current_dir().ok();
3062 let places: Vec<&Path> = std::iter::once(from.as_path())
3063 .chain(here.as_deref())
3064 .collect();
3065 let given = cli.library.as_deref();
3066 let alone = folder.is_none() && message.is_none() && !yes;
3067 let found = match library_folder_from(given, &places, environment) {
3068 Err(CliError::BadPointer { file, .. }) if file == from.join(LIBRARY_DATA) => {
3071 library_folder_from(given, &places[1..], environment)
3072 }
3073 found => found,
3074 };
3075 return match found {
3076 Ok(found) => Ok((found, false)),
3077 Err(CliError::NotInLibrary | CliError::NoLibraryIn(_)) if alone => Ok((
3078 Found::library(new_library_folder(given, environment)?),
3079 true,
3080 )),
3081 Err(CliError::NotInLibrary) => Err(CliError::NoLibraryForTree(from)),
3082 Err(error) => Err(error),
3083 };
3084 }
3085 if let (
3086 Command::Sync {
3087 at_login: Some(Switch::Off),
3088 ..
3089 },
3090 Some(given),
3091 ) = (&cli.command, cli.library.as_deref())
3092 {
3093 return Ok((
3095 Found::library(resolved(absolute(given, environment)?)),
3096 false,
3097 ));
3098 }
3099 Ok((library_folder(cli.library.as_deref(), environment)?, false))
3100}
3101
3102impl Command {
3103 const fn is_of_trees(&self) -> bool {
3106 matches!(
3107 self,
3108 Self::Init { .. } | Self::Status { .. } | Self::Trees(_) | Self::Pull { .. }
3109 )
3110 }
3111
3112 const fn makes_library(&self) -> bool {
3117 matches!(
3118 self,
3119 Self::Init {
3120 name,
3121 join,
3122 device,
3123 passphrase,
3124 languages,
3125 allow_fat,
3126 ..
3127 } if name.is_some()
3128 || join.is_some()
3129 || device.is_some()
3130 || *passphrase
3131 || languages.is_some()
3132 || *allow_fat
3133 ) || matches!(
3134 self,
3135 Self::Recovery {
3136 command: RecoveryCommand::Restore { .. } | RecoveryCommand::FromCopy { .. }
3137 }
3138 )
3139 }
3140}
3141
3142fn library_folder<E: Environment>(
3147 given: Option<&Path>,
3148 environment: &E,
3149) -> Result<Found, CliError> {
3150 if given.is_some() {
3151 return library_folder_from(given, &[], environment);
3152 }
3153 library_folder_from(given, &[¤t_dir(environment)?], environment)
3154}
3155
3156fn library_folder_from<E: Environment>(
3159 given: Option<&Path>,
3160 places: &[&Path],
3161 environment: &E,
3162) -> Result<Found, CliError> {
3163 if let Some(given) = given {
3164 let folder = resolved(absolute(given, environment)?);
3165 if !holds_library(&folder) {
3166 return Err(match unreadable(&folder) {
3167 Some(error) => CliError::NoAccess(folder, error),
3168 None => CliError::NoLibraryIn(folder),
3169 });
3170 }
3171 return Ok(Found::library(folder));
3172 }
3173 let ceiling = environment.ceiling();
3174 for here in places {
3175 if let Some(found) = pointer::nearest(here, ceiling.as_deref())? {
3176 return Ok(found);
3177 }
3178 if let Some(error) = unreadable(here) {
3179 return Err(CliError::NoAccess(here.to_path_buf(), error));
3180 }
3181 }
3182 let named = environment
3183 .default_library()
3184 .ok_or(CliError::NotInLibrary)?;
3185 if !named.is_absolute() {
3187 return Err(CliError::RelativeDefault(named));
3188 }
3189 let named = resolved(named);
3190 if !holds_library(&named) {
3191 return Err(CliError::NoDefaultLibrary(named));
3192 }
3193 Ok(Found::library(named))
3194}
3195
3196fn new_library_folder<E: Environment>(
3200 given: Option<&Path>,
3201 environment: &E,
3202) -> Result<PathBuf, CliError> {
3203 let folder = match given {
3204 Some(given) => absolute(given, environment)?,
3205 None => current_dir(environment)?,
3206 };
3207 let folder = resolved(folder);
3208 if folder
3209 .components()
3210 .any(|part| part.as_os_str() == LIBRARY_DATA)
3211 {
3212 return Err(CliError::InLibraryData(folder));
3213 }
3214 Ok(folder)
3215}
3216
3217const SYNCED_BY_PROGRAM: &str = "a program that syncs folders syncs this library's folder. NibKeep syncs it with your other devices on its own, and keeps each device's copy apart, so nothing is lost. But that program puts every device's keys on every computer it syncs and with its provider, where keys protected by a passphrase can be guessed at, and a deletion or an older version on one computer reaches the others. Keep the library out of it if you can.";
3219
3220fn unfinished(directory: &Path) -> CliError {
3223 CliError::Unfinished(
3224 Library::replica_folder(directory).unwrap_or_else(|_| directory.to_owned()),
3225 )
3226}
3227
3228fn unreadable(folder: &Path) -> Option<io::Error> {
3231 match std::fs::read_dir(folder) {
3232 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Some(error),
3233 _ => None,
3234 }
3235}
3236
3237fn current_dir<E: Environment>(environment: &E) -> Result<PathBuf, CliError> {
3238 environment.current_dir().map_err(CliError::NoCurrentFolder)
3239}
3240
3241fn absolute<E: Environment>(folder: &Path, environment: &E) -> Result<PathBuf, CliError> {
3244 if folder.is_absolute() {
3245 Ok(folder.to_owned())
3246 } else {
3247 Ok(current_dir(environment)?.join(folder))
3248 }
3249}
3250
3251fn library_command<E: Environment>(
3253 library: &mut Library,
3254 cli: &Cli,
3255 folder: &Path,
3256 environment: &mut E,
3257 timings: &mut Timings,
3258 output: &mut dyn Write,
3259) -> Result<(), CliError> {
3260 let json = cli.json;
3261 match &cli.command {
3262 Command::Languages { .. } => {
3263 languages_command(library, &cli.command, json, environment, output)
3264 }
3265 Command::Show { .. }
3266 | Command::History { .. }
3267 | Command::Export { .. }
3268 | Command::Find { .. }
3269 | Command::List { .. } => reading_command(library, cli, folder, environment, output),
3270 Command::Verify { export, .. } => {
3271 verify_command(library, export.as_deref(), json, environment, output)
3272 }
3273 Command::New {
3274 kind,
3275 values,
3276 language,
3277 } => {
3278 let new = (kind.as_str(), values.as_slice(), language.as_ref());
3279 new_command(library, new, json, environment, output)
3280 }
3281 Command::Merge {
3282 entity,
3283 other,
3284 undo,
3285 } => {
3286 let merge = (entity.as_str(), other.as_deref(), *undo);
3287 merge_command(library, merge, json, environment, output)
3288 }
3289 Command::Edit(arguments) => edit_command(library, arguments, json, environment, output),
3290 Command::Move {
3291 entity,
3292 to,
3293 without_history,
3294 keep_behind,
3295 leave_secrets,
3296 yes,
3297 } => {
3298 let args = (
3299 (entity.as_str(), to.as_str(), *without_history, *yes),
3300 (*keep_behind, *leave_secrets),
3301 );
3302 move_command(library, args, json, environment, timings, output)
3303 }
3304 Command::Purge { .. } => purge_or_list(library, cli, environment, timings, output),
3305 Command::File { command } => {
3306 let file = (command, folder);
3307 file_command(library, file, cli, environment, timings, output)
3308 }
3309 Command::Policy { command } => policy_command(library, command, json, environment, output),
3310
3311 Command::Secret { command } => {
3312 secret_command(library, command, json, environment, timings, output)
3313 }
3314 Command::Protect {
3315 passphrase,
3316 secrets,
3317 } => {
3318 let protect = (*passphrase, *secrets);
3319 protect_command(library, protect, json, environment, timings, output)?;
3320 if *passphrase && !*secrets {
3322 turn_off_at_login(&folder.join(LIBRARY_DATA), environment);
3323 }
3324 Ok(())
3325 }
3326 Command::Import { paths, from } => {
3327 let import = (paths.as_slice(), from.as_deref());
3328 import_command(library, import, json, environment, output)
3329 }
3330 Command::Type { command } => type_command(library, command, json, environment, output),
3331 Command::Space { command } => space_command(library, command, cli, environment, output),
3332 Command::Device { command } => {
3333 let directory = folder.join(LIBRARY_DATA);
3334 device_command(
3335 library,
3336 (command, &directory),
3337 cli,
3338 environment,
3339 timings,
3340 output,
3341 )
3342 }
3343 Command::Sync {
3344 serve: false, wait, ..
3345 } => {
3346 let wait = Duration::from_secs(*wait);
3347 sync_command(library, cli, wait, environment, output)
3348 }
3349 Command::Sync { serve: true, .. } => unreachable!("nib sync --serve closes the library"),
3350 Command::Mcp {
3351 action: McpAction::Serve { .. },
3352 } => unreachable!("nib mcp serve opens the library itself"),
3353 Command::Mcp { action } => mcp::manage(library, action, folder, cli, environment, output),
3354 command if command.is_of_trees() => {
3355 tree_command(library, cli, folder, environment, timings, output)
3356 }
3357 _ => unreachable!("run_command runs it"),
3360 }
3361}
3362
3363fn tree_command<E: Environment>(
3365 library: &mut Library,
3366 cli: &Cli,
3367 folder: &Path,
3368 environment: &mut E,
3369 timings: &mut Timings,
3370 output: &mut dyn Write,
3371) -> Result<(), CliError> {
3372 let json = cli.json;
3373 match &cli.command {
3374 Command::Init {
3375 folder: target,
3376 message,
3377 yes,
3378 ..
3379 } => {
3380 let start = (target.as_deref(), message.as_deref(), *yes);
3381 trees::init_command(
3382 library,
3383 (folder, start),
3384 json,
3385 (environment, timings),
3386 output,
3387 )
3388 }
3389 Command::Status { secrets: true, .. } => {
3390 trees::secrets_command(library, json, environment, output)
3391 }
3392 Command::Status { library_wide, .. } => {
3393 if !*library_wide && trees::in_tree_here(library, environment)? {
3394 return trees::status_command(library, json, environment, output);
3395 }
3396 reading_command(library, cli, folder, environment, output)
3397 }
3398 Command::Trees(command) => trees::tree_command(
3399 library,
3400 (folder, command),
3401 json,
3402 (environment, timings),
3403 output,
3404 ),
3405 Command::Pull {
3406 wait,
3407 partial,
3408 clone,
3409 no_clone,
3410 } => {
3411 let wait = Duration::from_secs(*wait);
3412 let update = (*partial, *clone, *no_clone);
3413 pull_command(library, cli, (wait, update), environment, timings, output)
3414 }
3415 _ => unreachable!("only the commands of trees come here"),
3416 }
3417}
3418
3419const PAIRING_MINUTES: u64 = 10;
3421
3422const FIND_SPONSOR: Duration = Duration::from_mins(1);
3424
3425fn pair_command<E: Environment>(
3428 library: &mut Library,
3429 ((ai_agent, spaces, give_secrets), device): (
3430 (Option<&str>, &[nibkeep_base::SpaceId], bool),
3431 &nibkeep_node::NewDevice,
3432 ),
3433 cli: &Cli,
3434 environment: &mut E,
3435 timings: &mut Timings,
3436 output: &mut dyn Write,
3437) -> Result<(), CliError> {
3438 let json = cli.json;
3439 library.check_not_ai_agent("add devices")?;
3441 if ai_agent.is_none() {
3442 library.check_new_device(device)?;
3443 }
3444 if give_secrets {
3446 unlock_secrets(library, false, environment, timings)?;
3447 }
3448 let _borrowed =
3451 nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
3452 let code = PairingCode::generate(environment.rng());
3453 let network = library.network(cli.network(true))?;
3454 output::port_taken(&network, json, output)?;
3455 output::pairing_code(&code, PAIRING_MINUTES, json, output)?;
3456 let now = clock(environment);
3457 let printing = RefCell::new(output);
3460 let wrong_try = |error: &NodeError, left: usize| {
3461 let _ = output::wrong_try(error, left, json, &mut **printing.borrow_mut());
3462 };
3463 let showing = nibkeep_node::Showing {
3464 timeout: Duration::from_mins(PAIRING_MINUTES),
3465 wrong_try: &wrong_try,
3466 };
3467 let paired = match ai_agent {
3468 Some(name) => nibkeep_node::pair_ai_agent_in(
3469 library,
3470 &network,
3471 &code,
3472 (name, spaces),
3473 showing,
3474 &now,
3475 environment.rng(),
3476 ),
3477 None => nibkeep_node::pair_device(
3478 library,
3479 &network,
3480 &code,
3481 (device, give_secrets),
3482 showing,
3483 &now,
3484 environment.rng(),
3485 ),
3486 };
3487 library.lock_secrets();
3488 output::paired(&paired?, json, printing.into_inner())
3489}
3490
3491fn device_command<E: Environment>(
3493 library: &mut Library,
3494 (command, directory): (&DeviceCommand, &Path),
3495 cli: &Cli,
3496 environment: &mut E,
3497 timings: &mut Timings,
3498 output: &mut dyn Write,
3499) -> Result<(), CliError> {
3500 match command {
3501 DeviceCommand::List => {
3502 let records = library.sync_records(UnwrapErr(SysRng)).ok();
3504 let recorded = records.as_ref().and_then(|records| records.replicas().ok());
3505 let holder = records.and_then(|records| records.holder().ok().flatten());
3506 let zone = environment.time_zone();
3507 let synced = (holder.as_ref(), recorded.as_ref());
3508 let replicas = library.replicas()?;
3509 let this = replicas
3510 .iter()
3511 .find(|replica| replica.this)
3512 .map(|replica| replica.id);
3513 let at_login = at_login_state((directory, this), environment);
3514 let shown = (synced, at_login.as_ref());
3515 output::replicas(&replicas, shown, &zone, cli.json, output)
3516 }
3517 DeviceCommand::Pair {
3518 ai_agent,
3519 phone,
3520 spaces,
3521 give_secrets,
3522 ..
3523 } => {
3524 let mut chosen = Vec::new();
3525 for space in spaces {
3526 chosen.push(library.find_space(space)?);
3527 }
3528 let device = nibkeep_node::NewDevice {
3529 phone: *phone,
3530 spaces: (!spaces.is_empty()).then(|| chosen.clone()),
3531 };
3532 let pairing = (ai_agent.as_deref(), &chosen[..], *give_secrets);
3533 pair_command(
3534 library,
3535 (pairing, &device),
3536 cli,
3537 environment,
3538 timings,
3539 output,
3540 )
3541 }
3542 DeviceCommand::Revoke { device, yes, codes } => revoke_command(
3543 library,
3544 (device, *yes, *codes),
3545 cli.json,
3546 environment,
3547 output,
3548 ),
3549 DeviceCommand::Mark { .. } => mark_command(library, command, cli.json, environment, output),
3550 DeviceCommand::Review => output::set_aside(
3551 &library.set_aside()?,
3552 &library.replicas()?,
3553 cli.json,
3554 output,
3555 ),
3556 DeviceCommand::Accept { device, yes } => {
3557 accept_command(library, (device, *yes), cli.json, environment, output)
3558 }
3559 }
3560}
3561
3562fn mark_command<E: Environment>(
3564 library: &mut Library,
3565 command: &DeviceCommand,
3566 json: bool,
3567 environment: &mut E,
3568 output: &mut dyn Write,
3569) -> Result<(), CliError> {
3570 let DeviceCommand::Mark {
3571 device,
3572 archive,
3573 everyday,
3574 away,
3575 home,
3576 keeps,
3577 waits,
3578 new_spaces,
3579 } = command
3580 else {
3581 unreachable!("only nib device mark comes here");
3582 };
3583 let (chosen, name) = one_device(library, device)?;
3584 let this = library.user_and_device()?.1.id == chosen;
3586 if let Some(new_spaces) = new_spaces {
3587 if !this {
3588 return Err(CliError::NewSpacesElsewhere(
3589 name.clone().unwrap_or_else(|| device.clone()),
3590 ));
3591 }
3592 let now = environment.now();
3593 library.set_takes_new_spaces(*new_spaces == NewSpacesArg::Take, now, environment.rng())?;
3594 }
3595 let takes = if this {
3596 Some(library.takes_new_spaces()?)
3597 } else {
3598 None
3599 };
3600 let mut marks = library.device_marks(chosen)?;
3601 if let Some(Waits(waits)) = waits {
3602 marks.waits = *waits;
3603 }
3604 if *archive {
3605 marks.role = DeviceRole::Archive;
3606 }
3607 if *everyday {
3608 marks.role = DeviceRole::Everyday;
3609 }
3610 if *away {
3611 marks.away = true;
3612 }
3613 if *home {
3614 marks.away = false;
3615 }
3616 if let Some(Keeps(keeps)) = keeps {
3617 marks.keeps = *keeps;
3618 }
3619 if *archive || *everyday || *away || *home || keeps.is_some() || waits.is_some() {
3621 library.set_device_marks(chosen, marks, environment.now(), environment.rng())?;
3622 }
3623 output::device_marked(
3624 (name.as_deref(), chosen),
3625 (marks, takes, new_spaces.is_some()),
3626 json,
3627 output,
3628 )
3629}
3630
3631fn revoke_command<E: Environment>(
3634 library: &mut Library,
3635 (device, yes, codes): (&str, bool, bool),
3636 json: bool,
3637 environment: &mut E,
3638 output: &mut dyn Write,
3639) -> Result<(), CliError> {
3640 let mut replicas = library.to_revoke(device)?;
3641 let ids: Vec<_> = replicas.iter().map(|replica| replica.id).collect();
3642 let out_of_reach = library.out_of_reach(&ids).unwrap_or_default();
3645 let mut made = library.recovery_codes_made_by(&ids)?;
3647 let mut elsewhere = Vec::new();
3648 if yes && !replicas.is_empty() {
3649 let spaces = library.revoke(&ids, environment.now(), environment.rng())?;
3650 elsewhere = spaces
3651 .iter()
3652 .copied()
3653 .zip(space_names(library, &spaces))
3654 .collect();
3655 elsewhere.sort_by(|a, b| a.1.cmp(&b.1));
3656 if codes {
3657 for code in &made {
3658 let now = environment.now();
3659 library.revoke_recovery_code(&code.record.to_string(), now, environment.rng())?;
3660 }
3661 let records: Vec<_> = made.iter().map(|code| code.record).collect();
3662 made = library
3663 .recovery_codes()?
3664 .into_iter()
3665 .filter(|code| records.contains(&code.record))
3666 .collect();
3667 }
3668 replicas = library
3670 .replicas()?
3671 .into_iter()
3672 .filter(|replica| ids.contains(&replica.id))
3673 .collect();
3674 }
3675 output::revoked(
3676 &replicas,
3677 (&made, codes),
3678 (yes, &elsewhere),
3679 &out_of_reach,
3680 json,
3681 output,
3682 )?;
3683 if yes || replicas.is_empty() {
3684 Ok(())
3685 } else {
3686 Err(CliError::UnconfirmedRevoke)
3687 }
3688}
3689
3690fn accept_command<E: Environment>(
3693 library: &mut Library,
3694 (device, confirmed): (&str, bool),
3695 json: bool,
3696 environment: &mut E,
3697 output: &mut dyn Write,
3698) -> Result<(), CliError> {
3699 let named: Vec<_> = library
3700 .replicas_named(device)?
3701 .into_iter()
3702 .map(|replica| replica.id)
3703 .collect();
3704 let changes: Vec<_> = library
3705 .set_aside()?
3706 .into_iter()
3707 .filter(|aside| {
3709 aside.acceptable
3710 && aside
3711 .replica
3712 .is_some_and(|replica| named.contains(&replica))
3713 })
3714 .map(|aside| aside.change)
3715 .collect();
3716 let accepted = if confirmed {
3717 library.accept_set_aside(&changes, environment.now(), environment.rng())?
3718 } else {
3719 changes.len()
3720 };
3721 output::accepted(accepted, confirmed, json, output)?;
3722 if confirmed || accepted == 0 {
3723 Ok(())
3724 } else {
3725 Err(CliError::UnconfirmedAccept)
3726 }
3727}
3728
3729fn sync_command<E: Environment>(
3731 library: &mut Library,
3732 cli: &Cli,
3733 wait: Duration,
3734 environment: &mut E,
3735 output: &mut dyn Write,
3736) -> Result<(), CliError> {
3737 let json = cli.json;
3738 if library.peers()?.is_empty() {
3742 return Err(NodeError::NoOtherReplicas.into());
3743 }
3744 let waited = Instant::now();
3747 let _role = loop {
3748 if let Some(role) = library.take_role()? {
3749 break role;
3750 }
3751 if library.sync_records(UnwrapErr(SysRng))?.holder()?.is_some() {
3752 if let Some(asked) = ask_to_sync(library, wait, cli, environment, output)? {
3753 return asked;
3754 }
3755 continue;
3756 }
3757 if waited.elapsed() > wait + ASK_WAIT {
3758 return Err(CliError::NotAnswered("another program".to_owned()));
3759 }
3760 std::thread::sleep(Duration::from_millis(100));
3761 };
3762 let network = library.network(cli.network(false))?;
3765 output::progress("Looking for your other devicesā¦", json, output)?;
3766 let now = clock(environment);
3767 let synced = nibkeep_node::sync_with_others(library, &network, wait, &now, environment.rng())?;
3768 output::synced_with(&synced, json, output)?;
3769 if library.is_revoked()? {
3770 return Err(NodeError::Revoked.into());
3771 }
3772 match synced.iter().filter(|with| with.synced.is_err()).count() {
3773 0 => Ok(()),
3774 failed => Err(CliError::SyncsFailed(failed)),
3775 }
3776}
3777
3778fn pull_command<E: Environment>(
3782 library: &mut Library,
3783 cli: &Cli,
3784 (wait, update): (Duration, (bool, bool, bool)),
3785 environment: &mut E,
3786 timings: &mut Timings,
3787 output: &mut dyn Write,
3788) -> Result<(), CliError> {
3789 let json = cli.json;
3790 let mut synced = Vec::new();
3791 let sync = if json {
3792 sync_command(library, cli, wait, environment, &mut synced)
3793 } else {
3794 sync_command(library, cli, wait, environment, output)
3795 };
3796 let mut updated = Vec::new();
3797 if let Err(error) =
3798 trees::update_here(library, update, json, (environment, timings), &mut updated)
3799 {
3800 if let Err(failed) = &sync {
3801 environment.note(&format!("the sync failed too: {failed}"));
3802 }
3803 return Err(error);
3804 }
3805 if json {
3806 let read = |printed: &[u8]| -> Result<serde_json::Value, CliError> {
3807 if printed.iter().all(u8::is_ascii_whitespace) {
3808 return Ok(serde_json::Value::Null);
3809 }
3810 serde_json::from_slice(printed).map_err(|error| CliError::Io(io::Error::other(error)))
3811 };
3812 let pulled = serde_json::json!({ "sync": read(&synced)?, "update": read(&updated)? });
3813 output::print_json(&pulled, output)?;
3814 } else {
3815 output.write_all(&updated)?;
3816 }
3817 sync
3818}
3819
3820const ASK_WAIT: Duration = Duration::from_mins(2);
3823
3824fn ask_to_sync<E: Environment>(
3828 library: &mut Library,
3829 wait: Duration,
3830 cli: &Cli,
3831 environment: &mut E,
3832 output: &mut dyn Write,
3833) -> Result<Option<Result<(), CliError>>, CliError> {
3834 let json = cli.json;
3835 let records = library.sync_records(UnwrapErr(SysRng))?;
3836 let Some(holder) = records.holder()? else {
3837 return Ok(None);
3838 };
3839 output::progress(&format!("Asking {} to syncā¦", holder.program), json, output)?;
3840 let asked = environment.now();
3841 let ask = records.ask(None, asked)?;
3842 let waited = Instant::now();
3843 while records.answered(ask)?.is_none() {
3844 if library.take_role()?.is_some() {
3846 return Ok(None);
3847 }
3848 if waited.elapsed() > wait + ASK_WAIT {
3849 return Err(CliError::NotAnswered(holder.program));
3850 }
3851 std::thread::sleep(Duration::from_millis(100));
3852 }
3853 library.catch_up()?;
3855 let failed = output::asked(
3856 &library.peers()?,
3857 &records.synced_since(asked)?,
3858 json,
3859 output,
3860 )?;
3861 if library.is_revoked()? {
3862 return Err(NodeError::Revoked.into());
3863 }
3864 Ok(Some(match failed {
3865 0 => Ok(()),
3866 failed => Err(CliError::SyncsFailed(failed)),
3867 }))
3868}
3869
3870enum Making<'a> {
3872 New(Option<&'a str>, Option<&'a Languages>),
3874 Join(&'a PairingCode, bool),
3877 Recover(Option<&'a Path>, &'a [String]),
3880 FromCopy,
3882}
3883
3884fn new_library<E: Environment>(
3887 directory: &Path,
3888 cli: &Cli,
3889 environment: &mut E,
3890 timings: &mut Timings,
3891 output: &mut dyn Write,
3892) -> Result<Library, CliError> {
3893 let (making, device, passphrase, allow_fat) = match &cli.command {
3894 Command::Init {
3895 name,
3896 device,
3897 passphrase,
3898 languages,
3899 join,
3900 secrets,
3901 allow_fat,
3902 ..
3903 } => {
3904 let making = match (join, name) {
3905 (Some(code), _) => Making::Join(code, *secrets),
3906 (None, name) => Making::New(name.as_deref(), languages.as_ref()),
3907 };
3908 (making, device.as_deref(), *passphrase, *allow_fat)
3909 }
3910 Command::Recovery {
3911 command: RecoveryCommand::Restore { source, keep, new },
3912 } => (
3913 Making::Recover(source.as_deref(), keep),
3914 new.device.as_deref(),
3915 new.passphrase,
3916 new.allow_fat,
3917 ),
3918 Command::Recovery {
3919 command: RecoveryCommand::FromCopy { new },
3920 } => (
3921 Making::FromCopy,
3922 new.device.as_deref(),
3923 new.passphrase,
3924 new.allow_fat,
3925 ),
3926 _ => unreachable!("only nib init and nib recovery make a library"),
3927 };
3928 if allow_fat {
3929 Library::allow_fat(directory)?;
3930 }
3931 if matches!(
3933 Library::replica_folder(directory),
3934 Err(NodeError::NoLibrary | NodeError::Copied)
3935 ) {
3936 Library::check_place(directory).map_err(|error| no_journal(error.into(), directory))?;
3937 }
3938 let protection = (passphrase, cli.passphrase_file.as_deref());
3939 match making {
3940 Making::Join(code, secrets) => join_command(
3941 directory,
3942 (code, device, secrets),
3943 protection,
3944 cli,
3945 environment,
3946 timings,
3947 output,
3948 ),
3949 Making::New(name, languages) => init_command(
3950 directory,
3951 (name, device, languages),
3952 protection,
3953 environment,
3954 timings,
3955 ),
3956 Making::Recover(source, keep) => recover_command(
3957 directory,
3958 (source, device, keep),
3959 protection,
3960 cli,
3961 environment,
3962 timings,
3963 output,
3964 ),
3965 Making::FromCopy => from_copy_command(
3966 directory,
3967 device,
3968 protection,
3969 cli,
3970 environment,
3971 timings,
3972 output,
3973 ),
3974 }
3975 .map_err(|error| no_journal(error, directory))
3976}
3977
3978fn at_login_command<E: Environment>(
3985 switch: Switch,
3986 directory: &Path,
3987 cli: &Cli,
3988 environment: &mut E,
3989 timings: &mut Timings,
3990 output: &mut dyn Write,
3991) -> Result<(), CliError> {
3992 let state = environment.state_folder().ok_or(CliError::NoStateFolder)?;
3993 let directory = std::path::absolute(directory)?;
3994 let keystore = matches!(
3995 Library::protection(&directory),
3996 Ok(Protection::Keystore { .. })
3997 );
3998 if switch == Switch::Off {
3999 let replica = if keystore {
4000 open(&directory, None, environment, timings)
4001 .ok()
4002 .and_then(|library| own_replica(&library).ok())
4003 } else {
4004 None
4005 };
4006 let entry = environment.login_entry();
4007 let turned_off = at_login::turn_off(&state, (&directory, replica), entry.as_ref())?;
4008 return output::at_login_off(&turned_off, cli.json, output);
4009 }
4010 if !keystore {
4012 Library::protection(&directory).map_err(|error| opening(error, &directory))?;
4013 return Err(CliError::AtLoginPassphrase);
4014 }
4015 let program = environment.sync_program().ok_or(CliError::NoSyncProgram)?;
4016 let library = open(&directory, None, environment, timings)
4017 .map_err(|error| opened_error(error, &directory))?;
4018 let served = at_login::Served {
4019 replica: own_replica(&library)?,
4020 directory,
4021 };
4022 drop(library);
4023 let entry = environment.login_entry();
4024 let version_of = |listed: &Path| environment.sync_version(listed);
4025 let turned_on = at_login::turn_on(&state, served, (&program, &version_of), entry.as_ref())
4026 .map_err(|error| match error {
4027 NodeError::NotInKeystore => CliError::AtLoginPassphrase,
4028 other => CliError::Node(other),
4029 })?;
4030 let firewall = environment.open_firewall();
4033 if let Some(start) = &turned_on.start {
4034 environment.start_sync(start)?;
4035 }
4036 output::at_login_on(&turned_on.entry, firewall, cli.json, output)
4037}
4038
4039fn own_replica(library: &Library) -> Result<EntityId, CliError> {
4041 library
4042 .replicas()?
4043 .into_iter()
4044 .find(|replica| replica.this)
4045 .map(|replica| replica.id)
4046 .ok_or_else(|| {
4047 CliError::Node(NodeError::Damaged(
4048 "the library lists no replica of its own".to_owned(),
4049 ))
4050 })
4051}
4052
4053fn opening(error: NodeError, directory: &Path) -> CliError {
4056 match error {
4057 NodeError::Unfinished => unfinished(directory),
4058 NodeError::Copied => CliError::IsCopy(directory.to_owned()),
4059 NodeError::UncleanRemoval => CliError::UncleanRemoval(directory.to_owned()),
4060 other => CliError::Node(other),
4061 }
4062}
4063
4064fn opened_error(error: CliError, directory: &Path) -> CliError {
4066 match error {
4067 CliError::Node(error) => opening(error, directory),
4068 other => other,
4069 }
4070}
4071
4072fn turn_off_at_login<E: Environment>(directory: &Path, environment: &mut E) {
4075 let Some(state) = environment.state_folder() else {
4076 return;
4077 };
4078 let entry = environment.login_entry();
4079 let turned_off = std::path::absolute(directory)
4080 .map_err(CliError::from)
4081 .and_then(|directory| {
4082 Ok(at_login::turn_off(
4083 &state,
4084 (&directory, None),
4085 entry.as_ref(),
4086 )?)
4087 });
4088 match turned_off {
4089 Ok(turned_off) => {
4090 if turned_off.removed {
4091 environment.note(AT_LOGIN_TURNED_OFF);
4092 }
4093 if let Some(error) = &turned_off.entry_failed {
4094 environment.note(&entry_not_removed(error));
4095 }
4096 }
4097 Err(error) => environment.note(&format!(
4098 "nib: could not turn syncing from login off for this library ({error}); nibkeep-sync turns it off as it finds the passphrase"
4099 )),
4100 }
4101}
4102
4103fn entry_not_removed(error: &str) -> String {
4105 format!(
4106 "nib: the login entry could not be removed ({error}); nib sync --at-login off tries again"
4107 )
4108}
4109
4110const AT_LOGIN_TURNED_OFF: &str = "nib: syncing from login is off for this library now, as it needs the library's keys in the keystore";
4112
4113fn at_login_state<E: Environment>(
4116 (directory, replica): (&Path, Option<EntityId>),
4117 environment: &E,
4118) -> Option<at_login::AtLoginStatus> {
4119 let state = environment.state_folder()?;
4120 let directory = std::path::absolute(directory).ok()?;
4121 let entry = environment.login_entry();
4122 let status = at_login::status(&state, (&directory, replica), entry.as_ref());
4123 status.on.then_some(status)
4124}
4125
4126fn serve_command<E: Environment>(
4130 library: Library,
4131 cli: &Cli,
4132 environment: &mut E,
4133 output: &mut dyn Write,
4134) -> Result<(), CliError> {
4135 let json = cli.json;
4136 let closed = library.close();
4137 let stop = Arc::new(AtomicBool::new(false));
4138 environment.stop_on_interrupt(Arc::clone(&stop));
4139 let role = if let Some(role) = Role::take(&closed)? {
4140 role
4141 } else {
4142 let program = closed
4143 .open()?
4144 .sync_records(UnwrapErr(SysRng))?
4145 .holder()?
4146 .map_or_else(|| "Another program".to_owned(), |holder| holder.program);
4147 output::progress(
4148 &format!(
4149 "{program} syncs this device; this one takes over when it ends. Stop with Ctrl-C."
4150 ),
4151 json,
4152 output,
4153 )?;
4154 let Some(role) = Role::wait(&closed, &stop)? else {
4156 return Ok(());
4157 };
4158 role
4159 };
4160 output::progress(
4161 "Syncing this device with your other devices; stop with Ctrl-C.",
4162 json,
4163 output,
4164 )?;
4165 let now = clock(environment);
4166 let holding = Holding {
4167 program: "nib sync --serve",
4168 network: cli.network(true),
4169 known: Vec::new(),
4170 quiet: Holding::QUIET,
4171 appear_wait: Holding::APPEAR_WAIT,
4172 check: nibkeep_node::Pace::DEFAULT,
4173 stop: &stop,
4174 now: &now,
4175 };
4176 let mut printed = Ok(());
4178 nibkeep_node::hold(
4179 &closed,
4180 role,
4181 &holding,
4182 &|| UnwrapErr(SysRng),
4183 &mut |held| {
4184 if printed.is_ok() {
4185 printed = output::held(&held, json, output);
4186 if printed.is_err() {
4187 stop.store(true, std::sync::atomic::Ordering::SeqCst);
4188 }
4189 }
4190 },
4191 )?;
4192 printed
4193}
4194
4195fn join_command<E: Environment>(
4198 directory: &Path,
4199 (code, device, secrets): (&PairingCode, Option<&str>, bool),
4200 (passphrase, file): (bool, Option<&Path>),
4201 cli: &Cli,
4202 environment: &mut E,
4203 timings: &mut Timings,
4204 output: &mut dyn Write,
4205) -> Result<Library, CliError> {
4206 if Library::exists(directory) {
4209 match Library::protection(directory) {
4210 Err(NodeError::Copied) => {}
4211 Err(NodeError::Unfinished) => return Err(unfinished(directory)),
4212 _ => return Err(NodeError::Exists.into()),
4213 }
4214 }
4215 let device = device_name(device, environment);
4216 let passphrase = new_passphrase((passphrase, file), environment, timings)?;
4217 let protection = match &passphrase {
4218 Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
4219 None => NewProtection::Keystore {
4220 service: KEYSTORE_SERVICE,
4221 },
4222 };
4223 let secrets_passphrase = if secrets {
4225 let typed = ask_twice(
4226 environment,
4227 timings,
4228 (
4229 "A passphrase for the secrets on this device, not the library's: ",
4230 "The passphrase again: ",
4231 ),
4232 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4233 )?;
4234 Some(typed)
4235 } else {
4236 None
4237 };
4238 let json = cli.json;
4239 let secrets_params = environment.passphrase_params();
4240 let mut joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
4241 let beside_copies = !Library::copies_in(directory).is_empty();
4244 if let Some(typed) = secrets_passphrase.as_ref().filter(|_| !beside_copies) {
4245 let protection = NewProtection::Passphrase(typed, secrets_params);
4246 joining = joining.asking_for_secrets(protection, environment.rng());
4247 }
4248 let network = joining.network(cli.network(false))?;
4249 output::progress("Looking for the device that shows the codeā¦", json, output)?;
4250 let now = clock(environment);
4251 let joined = nibkeep_node::join(
4252 directory,
4253 joining,
4254 &network,
4255 code,
4256 &protection,
4257 FIND_SPONSOR,
4258 &now,
4259 environment.rng(),
4260 )
4261 .map_err(|error| match error {
4262 error @ NodeError::Keys(KeysError::Keystore(_)) => CliError::Keystore(error),
4263 other => CliError::Node(other),
4264 })?;
4265 let mut library = joined.library;
4267 library.lock_secrets();
4268 let secrets = if secrets {
4269 Some((library.secrets_state()?, library.is_ai_agent()?))
4270 } else {
4271 None
4272 };
4273 let copies = take_in_copies(&mut library, environment)?;
4274 if let (Some(typed), Some(copies)) = (&secrets_passphrase, &copies) {
4277 let protection = NewProtection::Passphrase(typed, secrets_params);
4278 if let Err(error) = secrets_from_copies(
4279 &mut library,
4280 &copies.folders,
4281 &protection,
4282 environment,
4283 timings,
4284 ) {
4285 environment.note(&format!(
4286 "the copy's secrets were not taken: {error}; nib secret from-copy takes them"
4287 ));
4288 }
4289 }
4290 let secrets = match secrets {
4291 Some(_) => Some((library.secrets_state()?, library.is_ai_agent()?)),
4292 None => None,
4293 };
4294 output::joined(
4295 (&joined.synced, joined.refused),
4296 secrets,
4297 copies.as_ref(),
4298 json,
4299 output,
4300 )?;
4301 Ok(library)
4302}
4303
4304fn secrets_from_copies<E: Environment>(
4308 library: &mut Library,
4309 copies: &[PathBuf],
4310 protection: &NewProtection<'_>,
4311 environment: &mut E,
4312 timings: &mut Timings,
4313) -> Result<usize, CliError> {
4314 for folder in copies {
4315 let copy = nibkeep_node::ReplicaCopy {
4316 folder: folder.clone(),
4317 replica: None,
4318 };
4319 let Ok((_, Some(kept))) = copy.protections() else {
4320 continue;
4321 };
4322 let typed;
4323 let unlocker = match kept {
4324 Protection::Keystore { .. } => Unlocker::Keystore,
4325 Protection::Passphrase { .. } => {
4326 typed = ask_once(
4327 environment,
4328 timings,
4329 "The passphrase of the copy's secrets, or nothing to leave them: ",
4330 )?;
4331 if typed.is_empty() {
4332 return Ok(0);
4333 }
4334 Unlocker::Passphrase(&typed)
4335 }
4336 };
4337 let now = environment.now();
4338 return Ok(library.take_secrets_from_copy(
4339 folder,
4340 &unlocker,
4341 protection,
4342 now,
4343 environment.rng(),
4344 )?);
4345 }
4346 Ok(0)
4347}
4348
4349fn from_copy_secrets_command<E: Environment>(
4351 library: &mut Library,
4352 json: bool,
4353 environment: &mut E,
4354 timings: &mut Timings,
4355 output: &mut dyn Write,
4356) -> Result<(), CliError> {
4357 let copies: Vec<PathBuf> = library
4358 .copies()
4359 .into_iter()
4360 .map(|copy| copy.folder)
4361 .collect();
4362 let typed = ask_twice(
4363 environment,
4364 timings,
4365 (
4366 "A passphrase for the secrets on this device, not the library's: ",
4367 "The passphrase again: ",
4368 ),
4369 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4370 )?;
4371 let protection = NewProtection::Passphrase(&typed, environment.passphrase_params());
4372 let taken = secrets_from_copies(library, &copies, &protection, environment, timings);
4373 library.lock_secrets();
4374 match taken? {
4375 0 => Err(CliError::NoSecretsInCopies),
4376 taken => output::progress(
4377 &format!("Took {taken} secrets keys from the copy: this device holds the secrets."),
4378 json,
4379 output,
4380 ),
4381 }
4382}
4383
4384fn from_copy_command<E: Environment>(
4387 directory: &Path,
4388 device: Option<&str>,
4389 (passphrase, file): (bool, Option<&Path>),
4390 cli: &Cli,
4391 environment: &mut E,
4392 timings: &mut Timings,
4393 output: &mut dyn Write,
4394) -> Result<Library, CliError> {
4395 if Library::replica_folder(directory).is_ok() {
4396 return Err(NodeError::Exists.into());
4397 }
4398 let copies = Library::copies_in(directory);
4399 let copy = match copies.as_slice() {
4400 [copy] => copy,
4401 [] => return Err(CliError::NoCopy(directory.to_owned())),
4402 _ => return Err(CliError::SeveralCopies(directory.to_owned())),
4403 };
4404 let (kept, secrets_kept) = copy.protections()?;
4405 let typed;
4406 let unlocker = match kept {
4407 Protection::Keystore { .. } => Unlocker::Keystore,
4408 Protection::Passphrase { .. } => {
4409 typed = ask_once(
4410 environment,
4411 timings,
4412 "The passphrase of the copy, the library's: ",
4413 )?;
4414 Unlocker::Passphrase(&typed)
4415 }
4416 };
4417 let device = device_name(device, environment);
4418 let new_passphrase = new_passphrase((passphrase, file), environment, timings)?;
4419 let protection = match &new_passphrase {
4420 Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
4421 None => NewProtection::Keystore {
4422 service: KEYSTORE_SERVICE,
4423 },
4424 };
4425 let mut copy_secrets = None;
4427 let secrets_typed;
4428 if let Some(kept) = secrets_kept {
4429 let typed = match kept {
4430 Protection::Keystore { .. } => None,
4431 Protection::Passphrase { .. } => Some(ask_once(
4432 environment,
4433 timings,
4434 "The passphrase of the copy's secrets, or nothing to leave them: ",
4435 )?),
4436 };
4437 if typed.as_ref().is_none_or(|typed| !typed.is_empty()) {
4438 let new = ask_twice(
4439 environment,
4440 timings,
4441 (
4442 "A passphrase for the secrets on this device, not the library's: ",
4443 "The passphrase again: ",
4444 ),
4445 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4446 )?;
4447 secrets_typed = (typed, new);
4448 copy_secrets = Some(&secrets_typed);
4449 }
4450 }
4451 let secrets_params = environment.passphrase_params();
4452 let secrets_unlocker = copy_secrets.map(|(typed, _)| match typed {
4453 Some(typed) => Unlocker::Passphrase(typed),
4454 None => Unlocker::Keystore,
4455 });
4456 let secrets_protection =
4457 copy_secrets.map(|(_, new)| NewProtection::Passphrase(new, secrets_params));
4458 let joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
4459 let now = clock(environment);
4460 let library = Library::add_from_copy(
4461 directory,
4462 (©.folder, &unlocker),
4463 joining,
4464 &protection,
4465 secrets_unlocker.as_ref().zip(secrets_protection.as_ref()),
4466 &now,
4467 environment.rng(),
4468 )?;
4469 output::progress(
4470 "Made this device a device of its own from the copy, whose device is revoked. Devices of yours that turn up later are added anew.",
4471 cli.json,
4472 output,
4473 )?;
4474 Ok(library)
4475}
4476
4477fn recover_command<E: Environment>(
4483 directory: &Path,
4484 (source, device, keep): (Option<&Path>, Option<&str>, &[String]),
4485 (passphrase, file): (bool, Option<&Path>),
4486 cli: &Cli,
4487 environment: &mut E,
4488 timings: &mut Timings,
4489 output: &mut dyn Write,
4490) -> Result<Library, CliError> {
4491 let source = match source {
4493 Some(source) => absolute(source, environment)?,
4494 None => directory.to_owned(),
4495 };
4496 let replaces = Library::exists(directory) && Library::recovery_replaces(directory, &source);
4499 if Library::exists(directory) && !replaces {
4500 match Library::protection(directory) {
4501 Err(NodeError::Copied | NodeError::RecoveryCutShort) => {}
4502 Err(NodeError::Unfinished) => return Err(unfinished(directory)),
4503 _ => return Err(NodeError::Exists.into()),
4504 }
4505 }
4506 if replaces
4509 && matches!(
4510 Library::protection(directory),
4511 Ok(Protection::Keystore { .. })
4512 )
4513 && environment.keystore()
4514 && Library::open(directory, &Unlocker::Keystore).is_ok()
4515 {
4516 return Err(CliError::StillUnlocks);
4517 }
4518 let code = typed_recovery_code("Your recovery code: ", environment, cli.json, output)?;
4519 Library::check_recovery_source(&source, &code)?;
4520 let device = device_name(device, environment);
4521 let new_passphrase = new_passphrase((passphrase, file), environment, timings)?;
4522 let protection = match &new_passphrase {
4523 Some(passphrase) => NewProtection::Passphrase(passphrase, environment.passphrase_params()),
4524 None => NewProtection::Keystore {
4525 service: KEYSTORE_SERVICE,
4526 },
4527 };
4528 let joining = nibkeep_node::Joining::new(&device, APP, environment.rng())?;
4529 let now = clock(environment);
4530 let mut recovering = Library::start_recovery(
4531 directory,
4532 (&source, &code),
4533 joining,
4534 &protection,
4535 &now,
4536 environment.rng(),
4537 )?;
4538 let kept = devices_kept(&recovering, keep, cli.json, environment)?;
4542 recovering.keep(&kept)?;
4543 let secrets_passphrase = if recovering.holds_secrets() {
4544 Some(recovered_secrets_passphrase(
4545 environment,
4546 timings,
4547 new_passphrase.as_deref().map(String::as_str),
4548 )?)
4549 } else {
4550 None
4551 };
4552 let secrets_params = environment.passphrase_params();
4553 let secrets = secrets_passphrase
4554 .as_ref()
4555 .map(|typed| NewProtection::Passphrase(typed, secrets_params));
4556 let (mut library, recovered) = recovering.finish(secrets.as_ref(), &now, environment.rng())?;
4557 library.lock_secrets();
4558 let spaces = sorted_space_names(&library, &recovered.spaces);
4559 let elsewhere = sorted_space_names(&library, &recovered.revoked_elsewhere);
4560 let old_size = match &recovered.from {
4562 nibkeep_node::RecoveredFrom::Library {
4563 set_aside, folder, ..
4564 } => folder_size(set_aside.as_ref().unwrap_or(folder)),
4565 nibkeep_node::RecoveredFrom::Backup { .. } => 0,
4566 };
4567 output::recovered(
4568 &recovered,
4569 (&spaces, &elsewhere, old_size),
4570 cli.json,
4571 output,
4572 )?;
4573 Ok(library)
4574}
4575
4576fn devices_kept<E: Environment>(
4581 recovering: &nibkeep_node::Recovering<'_>,
4582 named: &[String],
4583 json: bool,
4584 environment: &mut E,
4585) -> Result<Vec<EntityId>, CliError> {
4586 if !named.is_empty() {
4587 let mut kept = Vec::new();
4588 for target in named {
4589 kept.extend(
4590 recovering
4591 .others_named(target)?
4592 .into_iter()
4593 .map(|replica| replica.id),
4594 );
4595 }
4596 return Ok(kept);
4597 }
4598 if json || !environment.can_ask() {
4600 return Ok(Vec::new());
4601 }
4602 let mut devices: BTreeMap<EntityId, Vec<Replica>> = BTreeMap::new();
4605 for replica in recovering.others()? {
4606 let device = match replica.device {
4607 Some(device) if !replica.ai_agent => device,
4608 _ => replica.id,
4609 };
4610 devices.entry(device).or_default().push(replica);
4611 }
4612 let mut asked: Vec<(String, EntityId, Vec<Replica>)> = devices
4613 .into_iter()
4614 .map(|(device, replicas)| (output::kept_device_text(&replicas), device, replicas))
4615 .collect();
4616 asked.sort_by(|a, b| (&a.0, a.1).cmp(&(&b.0, b.1)));
4617 let alike: Vec<bool> = asked
4618 .iter()
4619 .map(|(text, ..)| asked.iter().filter(|(other, ..)| other == text).count() > 1)
4620 .collect();
4621 let mut kept = Vec::new();
4622 for ((text, device, replicas), alike) in asked.into_iter().zip(alike) {
4623 let text = if alike {
4624 format!("{text} {}", output::short(device))
4625 } else {
4626 text
4627 };
4628 let answer = environment.ask(&output::keep_question(&text))?;
4629 if answer.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"))
4630 {
4631 kept.extend(replicas.iter().map(|replica| replica.id));
4632 }
4633 }
4634 Ok(kept)
4635}
4636
4637fn recovered_secrets_passphrase<E: Environment>(
4642 environment: &mut E,
4643 timings: &mut Timings,
4644 library: Option<&str>,
4645) -> Result<zeroize::Zeroizing<String>, CliError> {
4646 let mut tries = 0;
4647 loop {
4648 tries += 1;
4649 let typed = ask_twice(
4650 environment,
4651 timings,
4652 (
4653 "Your recovery code holds your secrets. A passphrase for them on this device, not the library's: ",
4654 "The passphrase again: ",
4655 ),
4656 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
4657 );
4658 let error = match typed {
4659 Ok(typed) if library.is_some_and(|library| *typed == *library) => {
4660 CliError::Node(NodeError::LibraryPassphrase)
4661 }
4662 Ok(typed) => return Ok(typed),
4663 Err(error @ (CliError::EmptyPassphrase | CliError::PassphrasesDiffer)) => error,
4664 Err(error) => return Err(error),
4665 };
4666 if tries == 3 {
4667 return Err(error);
4668 }
4669 environment.note(&format!("{error}; type it again"));
4670 }
4671}
4672
4673fn take_in_copies<E: Environment>(
4676 library: &mut Library,
4677 environment: &mut E,
4678) -> Result<Option<output::Copies>, CliError> {
4679 let copies = library.copies();
4680 if copies.is_empty() {
4681 return Ok(None);
4682 }
4683 let now = clock(environment);
4684 let taken = library.take_in_copies(&now)?;
4685 let replicas = library.replicas()?;
4686 let mut devices: Vec<String> = copies
4687 .iter()
4688 .filter_map(|copy| {
4689 let (replica, _) = copy.replica?;
4690 let known = replicas.iter().find(|known| known.id == replica)?;
4691 known.device_name.clone().or_else(|| known.name.clone())
4692 })
4693 .collect();
4694 devices.sort();
4695 devices.dedup();
4696 let size = copies.iter().map(|copy| folder_size(©.folder)).sum();
4697 let secrets_left = library.secrets_state()? != nibkeep_node::SecretsState::Here
4699 && copies.iter().any(|copy| {
4700 copy.protections()
4701 .is_ok_and(|(_, secrets)| secrets.is_some())
4702 });
4703 Ok(Some(output::Copies {
4704 taken,
4705 secrets_left,
4706 devices,
4707 folders: copies.into_iter().map(|copy| copy.folder).collect(),
4708 size,
4709 }))
4710}
4711
4712fn folder_size(folder: &Path) -> u64 {
4714 std::fs::read_dir(folder)
4715 .into_iter()
4716 .flatten()
4717 .flatten()
4718 .map(|entry| match entry.file_type() {
4719 Ok(kind) if kind.is_dir() => folder_size(&entry.path()),
4720 _ => entry.metadata().map_or(0, |metadata| metadata.len()),
4721 })
4722 .sum()
4723}
4724
4725fn user_names<E: Environment>(
4729 given: Option<&str>,
4730 environment: &E,
4731) -> Result<(String, Option<String>), CliError> {
4732 if let Some(given) = given {
4733 return Ok((given.to_owned(), None));
4734 }
4735 let account = environment.account();
4736 let user = account
4737 .name
4738 .map(|name| name.trim().to_owned())
4739 .filter(|name| !name.is_empty())
4740 .ok_or(CliError::NoAccountName)?;
4741 let person = account
4742 .full_name
4743 .map(|name| name.trim().to_owned())
4744 .filter(|name| !name.is_empty() && *name != user);
4745 Ok((user, person))
4746}
4747
4748fn device_name<E: Environment>(given: Option<&str>, environment: &E) -> String {
4750 given.map_or_else(
4752 || {
4753 Some(environment.computer_name())
4754 .filter(|name| !name.is_empty())
4755 .unwrap_or_else(|| "device".to_owned())
4756 },
4757 str::to_owned,
4758 )
4759}
4760
4761fn parse_code(text: &str) -> Result<PairingCode, String> {
4763 text.parse()
4764 .map_err(|error: nibkeep_node::NotACode| error.to_string())
4765}
4766
4767fn syncs_failed(failed: usize) -> String {
4769 if failed == 1 {
4770 "a device could not be synced with".to_owned()
4771 } else {
4772 format!("{failed} devices could not be synced with")
4773 }
4774}
4775
4776const CANDIDATES_LISTED: usize = 10;
4778
4779fn candidates_named<E: Environment>(
4782 library: &Library,
4783 error: CliError,
4784 environment: &E,
4785) -> CliError {
4786 let CliError::Node(NodeError::Ambiguous {
4787 reference,
4788 candidates,
4789 }) = error
4790 else {
4791 return error;
4792 };
4793 let personal = library.personal_space();
4794 let day = dating(environment, environment.now(), None).day;
4795 let mut listed = Vec::new();
4796 let mut members: std::collections::BTreeMap<EntityId, Vec<nibkeep_node::Listed>> =
4798 std::collections::BTreeMap::new();
4799 for &id in candidates.iter().take(CANDIDATES_LISTED) {
4800 let space = library.space_of(id).ok().flatten().unwrap_or(personal);
4802 let (name, types) = match library.entity(space, id, day) {
4803 Ok(Some(view)) if view.id == id => (view.name, view.types),
4804 Ok(Some(view)) => {
4806 let of_view = members
4807 .entry(view.id)
4808 .or_insert_with(|| library.merged(space, view.id).unwrap_or_default());
4809 let name = of_view
4810 .iter()
4811 .find(|member| member.id == id)
4812 .and_then(|member| member.name.clone());
4813 let types = library.own_types(space, id).unwrap_or_default();
4814 (name.or(view.name), types)
4815 }
4816 _ => (None, Vec::new()),
4817 };
4818 listed.push(nibkeep_node::Listed {
4819 id,
4820 name,
4821 types,
4822 via: None,
4823 });
4824 }
4825 CliError::Ambiguous {
4826 reference,
4827 count: candidates.len(),
4828 candidates: output::candidates(&listed, candidates.len()),
4829 }
4830}
4831
4832fn files_failed(failed: usize) -> String {
4834 if failed == 1 {
4835 "a file could not be added".to_owned()
4836 } else {
4837 format!("{failed} files could not be added")
4838 }
4839}
4840
4841fn unsound_export(problems: usize) -> String {
4843 if problems == 1 {
4844 "the export has a problem".to_owned()
4845 } else {
4846 format!("the export has {problems} problems")
4847 }
4848}
4849
4850fn unsound(problems: usize) -> String {
4852 if problems == 1 {
4853 "the library has a problem".to_owned()
4854 } else {
4855 format!("the library has {problems} problems")
4856 }
4857}
4858
4859fn edits(
4863 changes: &[String],
4864 forms: Forms<'_>,
4865 view: &EntityView,
4866 library: &Library,
4867 space: nibkeep_base::SpaceId,
4868) -> Result<Vec<Edit>, CliError> {
4869 let types = library.types(space)?;
4870 let mut sets: Vec<(nibkeep_model::FieldName, Vec<nibkeep_model::Value>)> = Vec::new();
4871 let mut cleared = std::collections::BTreeSet::new();
4872 let mut others = Vec::new();
4873 let mut kinds = view.types.clone();
4875 let (mut given, mut taken) = (Vec::new(), Vec::new());
4876 let mut rest = Vec::new();
4877 for change in changes {
4878 let (left, text) = change
4879 .split_once('=')
4880 .ok_or_else(|| CliError::Assignment(change.clone()))?;
4881 let (field, how) = match (left.strip_suffix('+'), left.strip_suffix('-')) {
4882 (Some(field), _) => (field, '+'),
4883 (_, Some(field)) => (field, '-'),
4884 _ => (left, '='),
4885 };
4886 let of_types = field == nibkeep_model::fields::TYPE.as_str()
4889 || (field == "type"
4890 && matches!(
4891 types::field_named(field, &types, &kinds),
4892 Err(CliError::NoField { .. })
4893 ));
4894 if !of_types {
4895 rest.push((change, field, how, text));
4896 continue;
4897 }
4898 match how {
4899 '+' => {
4900 let name = types::type_named(text, &types)?;
4901 kinds.push(name.clone());
4902 given.push(Edit::AddType(name));
4903 }
4904 '-' => taken.push(Edit::RemoveType(types::type_of(text, &view.types, &types)?)),
4905 _ => return Err(CliError::TypeSet),
4906 }
4907 }
4908 for (change, field, how, text) in rest {
4909 let field = types::field_named(field, &types, &kinds)?;
4910 if is_secret(library, space, &field) {
4911 return Err(CliError::SecretField(field));
4912 }
4913 if text.is_empty() {
4914 if how != '=' {
4915 return Err(CliError::Assignment(change.clone()));
4916 }
4917 if sets
4918 .iter()
4919 .any(|(set, values)| *set == field && !values.is_empty())
4920 {
4921 return Err(CliError::SetAndCleared(field));
4922 }
4923 if cleared.insert(field.clone()) {
4924 sets.push((field, Vec::new()));
4925 }
4926 continue;
4927 }
4928 let value = types::value(text, &field, &types, library, space)?;
4929 match how {
4930 '+' if !matches!(forms, Forms::No) => {
4931 let of = match forms {
4932 Forms::Of(of) => Some(types::value(of, &field, &types, library, space)?),
4933 _ => None,
4934 };
4935 others.push(Edit::AddForm { field, of, value });
4936 }
4937 '-' if !matches!(forms, Forms::No) => others.push(Edit::RemoveForm(field, value)),
4938 '+' => others.push(Edit::Add(field, value)),
4939 '-' => others.push(Edit::Remove(field, value)),
4940 _ => {
4941 if cleared.contains(&field) {
4942 return Err(CliError::SetAndCleared(field));
4943 }
4944 match sets.iter_mut().find(|(set, _)| *set == field) {
4945 Some((_, values)) => values.push(value),
4946 None => sets.push((field, vec![value])),
4947 }
4948 }
4949 }
4950 }
4951 if !matches!(forms, Forms::No)
4952 && !others
4953 .iter()
4954 .any(|edit| matches!(edit, Edit::AddForm { .. } | Edit::RemoveForm(..)))
4955 {
4956 return Err(CliError::NoForms);
4957 }
4958 Ok(given
4960 .into_iter()
4961 .chain(taken)
4962 .chain(
4963 sets.into_iter()
4964 .map(|(field, values)| Edit::Set(field, values)),
4965 )
4966 .chain(others)
4967 .collect())
4968}
4969
4970fn system_languages(locales: &[String]) -> Languages {
4975 let mut ranges: Vec<String> = Vec::new();
4976 for written in locales {
4977 let script = match written.rsplit_once('@').map(|(_, modifier)| modifier) {
4979 Some("latin") => Some("Latn"),
4980 Some("cyrillic") => Some("Cyrl"),
4981 _ => None,
4982 };
4983 let locale = written.split(['.', '@']).next().unwrap_or_default();
4984 if locale.is_empty() || locale == "C" || locale == "POSIX" {
4985 continue;
4986 }
4987 let mut subtags = locale.split(['_', '-']);
4988 let mut range = subtags.next().unwrap_or_default().to_owned();
4989 let named = subtags
4990 .next()
4991 .filter(|subtag| subtag.len() == 4 && subtag.chars().all(|c| c.is_ascii_alphabetic()));
4992 if let Some(script) = named.or(script) {
4993 range = format!("{range}-{script}");
4994 }
4995 if let Ok(parsed) = range.parse::<Languages>() {
4997 let range = parsed.to_string();
4998 if !range.is_empty() && !ranges.contains(&range) {
4999 ranges.push(range);
5000 }
5001 }
5002 }
5003 ranges.join(", ").parse().unwrap_or_default()
5004}
5005
5006fn parse_languages(text: &str) -> Result<Languages, String> {
5008 text.parse()
5009 .map_err(|error: ParseLanguagesError| error.to_string())
5010}
5011
5012fn parse_tag(text: &str) -> Result<Tag, String> {
5014 Tag::parse(text).ok_or_else(|| {
5015 "a language tag is written as in BCP 47, such as en, uk or uk-Latn".to_owned()
5016 })
5017}
5018
5019fn dating<E: Environment>(environment: &E, now: u64, on: Option<Day>) -> Dating {
5022 match on {
5023 Some(day) => Dating::on(day),
5024 None => Dating::today(now, environment.offset_minutes())
5025 .or_else(|| Dating::today(now, 0))
5026 .expect("the time has a day in UTC"),
5027 }
5028}
5029
5030fn parse_day(text: &str) -> Result<Day, String> {
5032 text.parse()
5033 .map_err(|_| "a day is written as YYYY-MM-DD, such as 2000-01-01".to_owned())
5034}
5035
5036#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5039pub enum Moment {
5040 Day(jiff::civil::Date),
5042 Local(jiff::civil::DateTime),
5044 Exact(jiff::Timestamp),
5046}
5047
5048impl Moment {
5049 fn resolve(self, zone: &jiff::tz::TimeZone) -> Result<(Option<u64>, Day), CliError> {
5057 let unplaced = || CliError::Moment("it cannot be placed in local time".to_owned());
5058 let timestamp = match self {
5059 Self::Day(date) => date
5060 .tomorrow()
5061 .ok()
5062 .and_then(|next| next.to_zoned(zone.clone()).ok())
5063 .and_then(|next| {
5064 next.timestamp()
5065 .checked_sub(jiff::SignedDuration::from_millis(1))
5066 .ok()
5067 })
5068 .ok_or_else(unplaced)?,
5069 Self::Local(time) => time
5070 .to_zoned(zone.clone())
5071 .map_err(|_| unplaced())?
5072 .timestamp(),
5073 Self::Exact(timestamp) => timestamp,
5074 };
5075 let millis = u64::try_from(timestamp.as_millisecond()).ok();
5076 let date = match self {
5077 Self::Day(date) => date,
5078 _ => timestamp.to_zoned(zone.clone()).date(),
5079 };
5080 let day = Day::from_ymd(
5081 i64::from(date.year()),
5082 date.month().unsigned_abs(),
5083 date.day().unsigned_abs(),
5084 )
5085 .expect("every date of a calendar is a day");
5086 Ok((millis, day))
5087 }
5088}
5089
5090fn parse_moment(text: &str) -> Result<Moment, String> {
5092 let wrong = || {
5093 "a day such as 2026-10-10, or a moment such as 2026-10-10T20:00, with its offset such as +02:00 if not in local time"
5094 .to_owned()
5095 };
5096 if text.len() == "YYYY-MM-DD".len() {
5098 return text
5099 .parse::<jiff::civil::Date>()
5100 .map(Moment::Day)
5101 .map_err(|_| wrong());
5102 }
5103 if let Ok(timestamp) = text.parse::<jiff::Timestamp>() {
5104 return Ok(Moment::Exact(timestamp));
5105 }
5106 text.parse::<jiff::civil::DateTime>()
5107 .map(Moment::Local)
5108 .map_err(|_| wrong())
5109}
5110
5111fn parse_edtf(text: &str) -> Result<Edtf, String> {
5113 text.parse()
5114 .map_err(|error: nibkeep_time::ParseEdtfError| error.to_string())
5115}
5116
5117fn show(
5120 library: &Library,
5121 space: nibkeep_base::SpaceId,
5122 entity: nibkeep_base::EntityId,
5123 when: When,
5124 json: bool,
5125 output: &mut dyn Write,
5126) -> Result<(), CliError> {
5127 show_added(library, space, entity, &[], when, json, output)
5128}
5129
5130#[derive(Clone, Copy, Debug)]
5133struct When {
5134 day: Day,
5135 as_of: Option<u64>,
5136 given: Option<Day>,
5138}
5139
5140impl When {
5141 const fn on(day: Day) -> Self {
5143 Self {
5144 day,
5145 as_of: None,
5146 given: None,
5147 }
5148 }
5149
5150 fn given(day: Day, given: Option<Day>) -> Self {
5152 Self {
5153 given,
5154 ..Self::on(day)
5155 }
5156 }
5157}
5158
5159fn show_added(
5162 library: &Library,
5163 space: nibkeep_base::SpaceId,
5164 entity: nibkeep_base::EntityId,
5165 recorded_before: &[nibkeep_base::EntityId],
5166 when: When,
5167 json: bool,
5168 output: &mut dyn Write,
5169) -> Result<(), CliError> {
5170 let When { day, as_of, given } = when;
5171 let view: Option<EntityView> = match as_of {
5172 Some(millis) => library.entity_as_of(space, entity, day, millis)?,
5173 None => library.entity(space, entity, day)?,
5174 };
5175 let view = view.ok_or_else(|| NodeError::NoEntity(entity.to_string()))?;
5176 let links = match as_of {
5177 Some(millis) => library.links_to_as_of(space, view.id, day, millis, LINKS_SHOWN)?,
5178 None => library.links_to_anywhere(space, view.id, day, LINKS_SHOWN)?,
5179 };
5180 let merged = match as_of {
5182 Some(millis) => library.merged_as_of(space, view.id, millis)?,
5183 None => library.merged(space, view.id)?,
5184 };
5185 let name_of = |entity| match as_of {
5187 Some(millis) => library.name_as_of(space, entity, millis).ok().flatten(),
5188 None => library
5189 .name_anywhere(entity)
5190 .ok()
5191 .flatten()
5192 .or_else(|| library.name(space, entity).ok().flatten()),
5193 };
5194 let mut secret = library.secret_fields_of(space, &view.types)?;
5197 secret.retain(|field| !view.fields.iter().any(|shown| shown.field == *field));
5198 let more = match as_of {
5201 Some(_) => None,
5202 None => Some(given.map_or_default(|day| format!(" --on {day}"))),
5203 };
5204 let thumbnail = if as_of.is_none() && view.types.contains(&FILE) {
5206 library.thumbnail(space, view.id)?
5207 } else {
5208 None
5209 };
5210 let shown = output::Shown {
5211 view: &view,
5212 merged: &merged,
5213 secret: &secret,
5214 links: &links,
5215 more: more.as_deref(),
5216 recorded_before,
5217 thumbnail: thumbnail.as_ref(),
5218 };
5219 output::entity(&shown, &name_of, json, output)
5220}
5221
5222fn init_command<E: Environment>(
5225 directory: &Path,
5226 (name, device, languages): (Option<&str>, Option<&str>, Option<&Languages>),
5227 passphrase: (bool, Option<&Path>),
5228 environment: &mut E,
5229 timings: &mut Timings,
5230) -> Result<Library, CliError> {
5231 let (user, person) = user_names(name, environment)?;
5232 let device = device_name(device, environment);
5233 let languages = languages
5234 .cloned()
5235 .unwrap_or_else(|| system_languages(&environment.languages()));
5236 let new = NewLibrary::new(&user, &device, APP)
5237 .with_person(person.as_deref())
5238 .with_languages(languages);
5239 init(directory, &new, passphrase, environment, timings)
5240}
5241
5242fn show_command<E: Environment>(
5246 library: &Library,
5247 (reference, on, as_of): (&str, Option<Day>, Option<Moment>),
5248 json: bool,
5249 environment: &E,
5250 output: &mut dyn Write,
5251) -> Result<(), CliError> {
5252 let (space, entity) = library.locate_or_deleted(reference)?;
5253 let Some(diff) = library.revision_diff(space, entity, false)? else {
5254 return show_entity(
5255 library,
5256 (space, entity),
5257 (reference, on, as_of),
5258 json,
5259 environment,
5260 output,
5261 );
5262 };
5263 let mut shown = Vec::new();
5264 let what = (reference, on, as_of);
5265 show_entity(
5266 library,
5267 (space, entity),
5268 what,
5269 json,
5270 environment,
5271 &mut shown,
5272 )?;
5273 if json {
5274 let mut value: serde_json::Value = serde_json::from_slice(&shown)
5275 .map_err(|error| CliError::Io(io::Error::other(error)))?;
5276 value["diff"] = trees::diff_json(&diff);
5277 return output::print_json(&value, output);
5278 }
5279 output.write_all(&shown)?;
5280 writeln!(output)?;
5281 trees::diff_text(&diff, output)
5282}
5283
5284fn show_entity<E: Environment>(
5286 library: &Library,
5287 (space, entity): (SpaceId, EntityId),
5288 (reference, on, as_of): (&str, Option<Day>, Option<Moment>),
5289 json: bool,
5290 environment: &E,
5291 output: &mut dyn Write,
5292) -> Result<(), CliError> {
5293 let Some(as_of) = as_of else {
5294 let day = dating(environment, environment.now(), on).day;
5295 return show(library, space, entity, When::given(day, on), json, output);
5296 };
5297 let zone = environment.time_zone();
5298 let (millis, as_of_day) = as_of.resolve(&zone)?;
5299 let when = When {
5300 day: on.unwrap_or(as_of_day),
5301 as_of: millis,
5302 given: Some(on.unwrap_or(as_of_day)),
5303 };
5304 let recorded = match millis {
5305 Some(millis) => library
5306 .entity_as_of(space, entity, when.day, millis)?
5307 .is_some(),
5308 None => false,
5309 };
5310 if !recorded {
5311 return Err(CliError::NotYet {
5312 entity: reference.to_owned(),
5313 when: millis.map_or_else(
5314 || "1970".to_owned(),
5315 |millis| output::moment_text(millis, &zone),
5316 ),
5317 });
5318 }
5319 show(library, space, entity, when, json, output)
5320}
5321
5322fn reading_command<E: Environment>(
5325 library: &Library,
5326 cli: &Cli,
5327 library_folder: &Path,
5328 environment: &E,
5329 output: &mut dyn Write,
5330) -> Result<(), CliError> {
5331 let json = cli.json;
5332 match &cli.command {
5333 Command::Status { .. } => {
5334 let mut checkouts = Vec::new();
5335 for space in library.spaces() {
5336 checkouts.extend(library.checkouts(space)?);
5337 }
5338 let checks = library
5339 .sync_records(UnwrapErr(SysRng))
5340 .ok()
5341 .and_then(|records| library.check_status(&records, environment.now()).ok());
5342 let name_of = |space, file: Option<EntityId>| match file {
5343 Some(file) => library.name(space, file).ok().flatten(),
5344 None => library.space_name(space).ok().flatten(),
5345 };
5346 let zone = environment.time_zone();
5347 let checks = output::Checks {
5348 status: checks.as_ref(),
5349 name_of: &name_of,
5350 zone: &zone,
5351 };
5352 let mut thumbnails = std::collections::BTreeMap::new();
5353 for space in library.spaces() {
5354 thumbnails.insert(space, library.thumbnail_counts(space)?);
5355 }
5356 output::status(
5357 (&library.status()?, &checkouts, &thumbnails),
5358 checks,
5359 library_folder,
5360 json,
5361 output,
5362 )
5363 }
5364 Command::Show { entity, on, as_of } => {
5365 show_command(library, (entity, *on, *as_of), json, environment, output)
5366 }
5367 Command::History { entity, field } => history_command(
5368 library,
5369 (entity, field.as_deref()),
5370 json,
5371 environment,
5372 output,
5373 ),
5374 Command::Export { folder, current } => {
5375 export_command(library, folder, *current, json, output)
5376 }
5377 Command::Find { words, all } => {
5378 let words = words.join(" ");
5379 let first = if *all { usize::MAX } else { FIND_FIRST };
5380 let mut groups = Vec::new();
5381 for space in spaces_to_read(library) {
5382 let found = library.search_first(space, &words, first, |entity, _| {
5385 Ok(library.moved_into(space, entity)?.is_none())
5386 })?;
5387 groups.push((library.space_name(space)?, found));
5388 }
5389 let missed = not_looked_in(library)?;
5390 output::found_in_spaces((&groups, &missed), json, output)
5391 }
5392 Command::List {
5393 kind,
5394 conditions,
5395 sort,
5396 on,
5397 } => {
5398 let list = (kind.as_deref(), conditions.as_slice(), sort.as_deref());
5399 list_command(library, list, *on, json, environment, output)
5400 }
5401 _ => unreachable!("only commands that read come here"),
5402 }
5403}
5404
5405fn export_command(
5407 library: &Library,
5408 folder: &Path,
5409 current: bool,
5410 json: bool,
5411 output: &mut dyn Write,
5412) -> Result<(), CliError> {
5413 let kind = if current {
5414 nibkeep_node::ExportKind::Current
5415 } else {
5416 nibkeep_node::ExportKind::Full
5417 };
5418 let exported = library.export(library.default_space(), folder, kind)?;
5419 output::exported(&exported, folder, kind, json, output)
5420}
5421
5422fn verify_export_command(
5425 library: &Library,
5426 folder: &Path,
5427 json: bool,
5428 output: &mut dyn Write,
5429) -> Result<(), CliError> {
5430 let check = library.verify_export(folder)?;
5431 output::export_check(&check, folder, json, output)?;
5432 match check.problems.len() {
5433 0 => Ok(()),
5434 problems => Err(CliError::UnsoundExport(problems)),
5435 }
5436}
5437
5438fn verify_command<E: Environment>(
5441 library: &mut Library,
5442 export: Option<&Path>,
5443 json: bool,
5444 environment: &E,
5445 output: &mut dyn Write,
5446) -> Result<(), CliError> {
5447 if let Some(folder) = export {
5448 return verify_export_command(library, folder, json, output);
5449 }
5450 let report = library.verify(environment.now())?;
5451 let set_aside = report.spaces.iter().any(|space| {
5454 space
5455 .problems
5456 .iter()
5457 .any(|problem| matches!(problem, nibkeep_node::Problem::DamagedBlob(_)))
5458 });
5459 if set_aside && let Ok(records) = library.sync_records(UnwrapErr(SysRng)) {
5460 let _ = records.ask(None, environment.now());
5461 }
5462 output::report(&report, json, output)?;
5463 let problems = report.problems();
5464 if problems > 0 {
5465 return Err(CliError::Unsound(problems));
5466 }
5467 Ok(())
5468}
5469
5470fn list_command<E: Environment>(
5472 library: &Library,
5473 list: (Option<&str>, &[String], Option<&str>),
5474 on: Option<Day>,
5475 json: bool,
5476 environment: &E,
5477 output: &mut dyn Write,
5478) -> Result<(), CliError> {
5479 let mut groups = Vec::new();
5482 let mut failed = None;
5483 for space in spaces_to_read(library) {
5484 match listed_in(library, space, list, on, environment) {
5485 Ok(listed) => groups.push((space, listed)),
5486 Err(
5488 error @ (CliError::NoType(_)
5489 | CliError::AmbiguousType { .. }
5490 | CliError::NoField { .. }
5491 | CliError::AmbiguousField { .. }),
5492 ) => {
5493 failed = failed.or(Some(error));
5494 }
5495 Err(error) => return Err(error),
5496 }
5497 }
5498 if groups.is_empty()
5499 && let Some(error) = failed
5500 {
5501 return Err(error);
5502 }
5503 let missed = not_looked_in(library)?;
5504 output::entities_in_spaces((&named_groups(library, groups)?, &missed), json, output)
5505}
5506
5507fn not_looked_in(library: &Library) -> Result<Vec<String>, CliError> {
5510 if library.chosen_space().is_some() {
5511 return Ok(Vec::new());
5512 }
5513 let looked_in = library.spaces();
5514 Ok(library
5515 .known_spaces()?
5516 .into_iter()
5517 .filter(|known| !looked_in.contains(&known.space))
5518 .map(|known| known.name.unwrap_or_else(|| known.space.to_string()))
5519 .collect())
5520}
5521
5522fn spaces_to_read(library: &Library) -> Vec<nibkeep_base::SpaceId> {
5524 match library.chosen_space() {
5525 Some(space) => vec![space],
5526 None => library.spaces(),
5527 }
5528}
5529
5530const FIND_FIRST: usize = 50;
5534
5535type NamedGroup = (Option<String>, Vec<nibkeep_node::Listed>);
5537
5538fn named_groups(
5541 library: &Library,
5542 groups: Vec<(nibkeep_base::SpaceId, Vec<nibkeep_node::Listed>)>,
5543) -> Result<Vec<NamedGroup>, CliError> {
5544 groups
5545 .into_iter()
5546 .map(|(space, listed)| {
5547 let mut kept = Vec::new();
5548 for entity in listed {
5549 if library.moved_into(space, entity.id)?.is_none() {
5550 kept.push(entity);
5551 }
5552 }
5553 Ok((library.space_name(space)?, kept))
5554 })
5555 .collect()
5556}
5557
5558fn listed_in<E: Environment>(
5560 library: &Library,
5561 space: nibkeep_base::SpaceId,
5562 (kind, conditions, sort): (Option<&str>, &[String], Option<&str>),
5563 on: Option<Day>,
5564 environment: &E,
5565) -> Result<Vec<nibkeep_node::Listed>, CliError> {
5566 let types = library.types(space)?;
5567 let kind = match kind {
5568 Some(kind) => Some(types::type_named(kind, &types)?),
5569 None => None,
5570 };
5571 let mut held: Option<Vec<TypeName>> = None;
5574 let mut field_named = |text: &str| -> Result<FieldName, CliError> {
5575 let Some(kind) = &kind else {
5576 let every: Vec<TypeName> = types
5577 .iter()
5578 .map(|definition| definition.name().clone())
5579 .collect();
5580 return types::field_named(text, &types, &every);
5581 };
5582 types::field_of_listed(text, &types, kind, || {
5583 if held.is_none() {
5584 held = Some(library.types_with(space, kind)?.into_iter().collect());
5585 }
5586 Ok(held.as_deref().unwrap_or_default())
5587 })
5588 };
5589 let mut conditions_given = Vec::new();
5590 for condition in conditions {
5591 let (field, text) = condition
5592 .split_once('=')
5593 .filter(|(_, text)| !text.is_empty())
5594 .ok_or_else(|| CliError::Assignment(condition.clone()))?;
5595 let field = field_named(field)?;
5596 if is_secret(library, space, &field) {
5597 return Err(CliError::SecretField(field));
5598 }
5599 let value = types::value(text, &field, &types, library, space)?;
5600 conditions_given.push((field, value));
5601 }
5602 let order_by = match sort {
5603 Some(field) => {
5604 let field = field_named(field)?;
5605 if is_secret(library, space, &field) {
5606 return Err(CliError::SecretField(field));
5607 }
5608 Some(field)
5609 }
5610 None => None,
5611 };
5612 let listing = nibkeep_node::Listing {
5613 of_type: kind,
5614 conditions: conditions_given,
5615 order_by,
5616 on,
5617 };
5618 let today = dating(environment, environment.now(), None).day;
5619 Ok(library.list(space, &listing, today)?)
5620}
5621
5622fn merge_command<E: Environment>(
5625 library: &mut Library,
5626 (reference, other, undo): (&str, Option<&str>, bool),
5627 json: bool,
5628 environment: &mut E,
5629 output: &mut dyn Write,
5630) -> Result<(), CliError> {
5631 let (space, found) = library.locate(reference)?;
5632 library.choose_space(Some(space))?;
5634 let now = environment.now();
5635 let shown = if undo {
5636 let member = match other {
5637 Some(other) => match library.find_merged(space, found, other) {
5638 Err(NodeError::NotMerged(_)) if library.merged(space, found)?.is_empty() => {
5639 return Err(CliError::NothingMerged(reference.to_owned()));
5640 }
5641 Err(NodeError::NotMerged(_)) => {
5642 return Err(CliError::NotMergedInto {
5643 entity: reference.to_owned(),
5644 other: other.to_owned(),
5645 });
5646 }
5647 found => found?,
5648 },
5649 None => match library.merged(space, found)?.as_slice() {
5650 [] => return Err(CliError::NothingMerged(reference.to_owned())),
5651 [only] => only.id,
5652 merged => {
5653 return Err(CliError::WhichMerged {
5654 entity: reference.to_owned(),
5655 candidates: output::listed_names(merged),
5656 });
5657 }
5658 },
5659 };
5660 library.undo_merge(space, member, now, environment.rng())?;
5661 member
5662 } else {
5663 let from = match library.find_merged(space, found, reference) {
5665 Ok(member) => member,
5666 Err(NodeError::NotMerged(_)) => found,
5667 Err(error) => return Err(error.into()),
5668 };
5669 let other = other.unwrap_or_default();
5670 let into = library.find_entity(space, other)?;
5671 library
5672 .merge_entities(space, from, into, now, environment.rng())
5673 .map_err(|error| match error {
5674 NodeError::SameEntity(_) => CliError::OneAlready {
5675 entity: reference.to_owned(),
5676 into: other.to_owned(),
5677 },
5678 error => error.into(),
5679 })?;
5680 into
5681 };
5682 let day = dating(environment, now, None).day;
5683 show(library, space, shown, When::on(day), json, output)
5684}
5685
5686fn history_command<E: Environment>(
5689 library: &Library,
5690 (reference, field): (&str, Option<&str>),
5691 json: bool,
5692 environment: &E,
5693 output: &mut dyn Write,
5694) -> Result<(), CliError> {
5695 let (space, entity) = library.locate_or_deleted(reference)?;
5696 let mut history = library
5697 .history(space, entity, None)?
5698 .ok_or_else(|| NodeError::NoEntity(entity.to_string()))?;
5699 if let Some(field) = field {
5701 let had: Vec<_> = history
5702 .fields
5703 .iter()
5704 .map(|past| past.field.clone())
5705 .collect();
5706 let wanted = types::field_among(field, &had).map_err(|error| {
5707 let day = dating(environment, environment.now(), None).day;
5709 let view = library.entity(space, entity, day).ok().flatten();
5710 let types = library.types(space).ok();
5711 let secret = types
5712 .zip(view)
5713 .and_then(|(types, view)| types::field_named(field, &types, &view.types).ok())
5714 .filter(|field| is_secret(library, space, field));
5715 secret.map_or(error, CliError::SecretHistory)
5716 })?;
5717 history.fields.retain(|past| past.field == wanted);
5718 }
5719 let name_of = |entity| library.name(space, entity).ok().flatten();
5720 output::history(&history, &name_of, &environment.time_zone(), json, output)
5721}
5722
5723fn new_command<E: Environment>(
5726 library: &mut Library,
5727 (kind, values, language): (&str, &[String], Option<&Tag>),
5728 json: bool,
5729 environment: &mut E,
5730 output: &mut dyn Write,
5731) -> Result<(), CliError> {
5732 let space = library.default_space();
5733 let types = library.types(space)?;
5734 let mut kinds: Vec<TypeName> = Vec::new();
5735 for name in kind.split(',') {
5736 let name = types::type_named(name.trim(), &types)?;
5737 if nibkeep_node::OWN_RECORDS.contains(&name) {
5739 return Err(NodeError::OwnType(name).into());
5740 }
5741 if !kinds.contains(&name) {
5742 kinds.push(name);
5743 }
5744 }
5745 let mut parsed = Vec::new();
5746 for assignment in values {
5747 let (field, text) = assignment
5748 .split_once('=')
5749 .ok_or_else(|| CliError::Assignment(assignment.clone()))?;
5750 let field = types::field_named(field, &types, &kinds)?;
5751 if is_secret(library, space, &field) {
5752 return Err(CliError::SecretField(field));
5753 }
5754 let value = types::value(text, &field, &types, library, space)?;
5755 parsed.push((field, value));
5756 }
5757 let recorded_before = library.same_relationship(space, &kinds, &parsed)?;
5759 let now = environment.now();
5760 let rng = environment.rng();
5761 let entity = match language {
5762 Some(language) => {
5763 library.create_entity_with_language(space, &kinds, parsed, language, now, rng)?
5764 }
5765 None => library.create_entity(space, &kinds, parsed, now, rng)?,
5766 };
5767 let day = dating(environment, now, None).day;
5768 show_added(
5769 library,
5770 space,
5771 entity,
5772 &recorded_before,
5773 When::on(day),
5774 json,
5775 output,
5776 )
5777}
5778
5779fn languages_command<E: Environment>(
5781 library: &mut Library,
5782 command: &Command,
5783 json: bool,
5784 environment: &mut E,
5785 output: &mut dyn Write,
5786) -> Result<(), CliError> {
5787 let Command::Languages {
5788 ranges,
5789 device,
5790 app,
5791 clear,
5792 } = command
5793 else {
5794 unreachable!("only for nib languages");
5795 };
5796 let whose = match (device, app) {
5797 (true, _) => LanguagesFor::Device,
5798 (_, true) => LanguagesFor::Replica,
5799 _ => LanguagesFor::User,
5800 };
5801 let set = match ranges {
5802 Some(ranges) => Some(Some(ranges.parse::<Languages>()?)),
5803 None if *clear => Some(None),
5804 None => None,
5805 };
5806 if let Some(languages) = set {
5807 let now = environment.now();
5808 library.set_languages(whose, languages.as_ref(), now, environment.rng())?;
5809 }
5810 output::languages(&library.language_settings()?, json, output)
5811}
5812
5813fn edit_command<E: Environment>(
5815 library: &mut Library,
5816 arguments: &EditArgs,
5817 json: bool,
5818 environment: &mut E,
5819 output: &mut dyn Write,
5820) -> Result<(), CliError> {
5821 let EditArgs {
5822 entity,
5823 changes,
5824 date,
5825 on,
5826 delete,
5827 restore,
5828 language,
5829 form,
5830 form_of,
5831 } = arguments;
5832 let (space, id) = library.locate_or_deleted(entity)?;
5833 library.choose_space(Some(space))?;
5835 let now = environment.now();
5837 let mut dating = dating(environment, now, *on);
5838 if let Some(date) = date {
5839 dating = dating.with_valid_time(date.clone());
5840 }
5841 if let Some(language) = language {
5842 dating = dating.with_language(language.clone());
5843 }
5844 let view = library
5845 .entity(space, id, dating.day)?
5846 .ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
5847 let forms = match (form_of, form) {
5848 (Some(of), _) => Forms::Of(of),
5849 (None, true) => Forms::OfTheOnly,
5850 (None, false) => Forms::No,
5851 };
5852 let mut edits = edits(changes, forms, &view, library, space)?;
5853 if *delete {
5854 edits.push(Edit::Delete);
5855 }
5856 if *restore {
5857 edits.push(Edit::Restore);
5858 }
5859 library.edit_entity(space, id, edits, &dating, now, environment.rng())?;
5860 show(
5861 library,
5862 space,
5863 id,
5864 When::given(dating.day, *on),
5865 json,
5866 output,
5867 )
5868}
5869
5870fn purge_command<E: Environment>(
5874 library: &mut Library,
5875 (entity, assignment, confirmed): (&str, &str, bool),
5876 json: bool,
5877 environment: &mut E,
5878 timings: &mut Timings,
5879 output: &mut dyn Write,
5880) -> Result<(), CliError> {
5881 let (space, id) = library.locate_or_deleted(entity)?;
5882 library.choose_space(Some(space))?;
5884 let view = library
5885 .entity(space, id, dating(environment, environment.now(), None).day)?
5886 .ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
5887 let (field, text) = assignment
5888 .split_once('=')
5889 .ok_or_else(|| CliError::Assignment(assignment.to_owned()))?;
5890 let types = library.types(space)?;
5891 let field = types::field_named(field, &types, &view.types)?;
5892 let secret = is_secret(library, space, &field);
5893 if secret && !text.is_empty() {
5894 return Err(CliError::SecretGiven(field));
5895 }
5896 let value = if text.is_empty() {
5897 None
5898 } else {
5899 Some(types::value(text, &field, &types, library, space)?)
5900 };
5901 if secret && library.secrets_protection()?.is_some() {
5903 unlock_secrets(library, false, environment, timings)?;
5904 }
5905 let purged = purge_values(
5906 library,
5907 (id, &field, value.as_ref()),
5908 confirmed,
5909 environment,
5910 );
5911 library.lock_secrets();
5912 let purged = purged?;
5913 let name_of = |entity| library.name(space, entity).ok().flatten();
5914 let elsewhere = space_names(library, &purged.elsewhere);
5915 output::purge(
5916 &purged,
5917 (&field, &name_of),
5918 &elsewhere,
5919 confirmed,
5920 json,
5921 output,
5922 )?;
5923 if confirmed {
5924 Ok(())
5925 } else {
5926 Err(CliError::Unconfirmed)
5927 }
5928}
5929
5930fn purges_waiting_command<E: Environment>(
5933 library: &mut Library,
5934 command: Option<&PurgesCommand>,
5935 json: bool,
5936 environment: &mut E,
5937 output: &mut dyn Write,
5938) -> Result<(), CliError> {
5939 let zone = environment.time_zone();
5940 let records = library.sync_records(UnwrapErr(SysRng))?;
5942 let remembered: BTreeMap<EntityId, PathBuf> = records
5943 .backup_folders()?
5944 .into_iter()
5945 .map(|(backup, found)| (backup, found.folder))
5946 .collect();
5947 let found = library.find_backups(&remembered)?;
5948 let Some(command) = command else {
5949 let mut waiting = library.waiting_purges()?;
5950 waiting.extend(library.waiting_purges_on(&found)?);
5951 let mut spaces = Vec::new();
5952 for purge in &waiting {
5953 spaces.push(space_display_name(library, purge.space)?);
5954 }
5955 let days = library.own_wait_days()?;
5956 return output::waiting_purges((&waiting, &spaces), days, &zone, json, output);
5957 };
5958 let (name, on, yes, stopping) = match command {
5959 PurgesCommand::Stop { purge, on, yes } => (purge, on, *yes, true),
5960 PurgesCommand::End { purge, on, yes } => (purge, on, *yes, false),
5961 };
5962 let waiting = library.find_waiting_purges(name, (&found, on.as_deref()))?;
5963 let space = space_display_name(library, waiting[0].space)?;
5964 if yes {
5965 let now = environment.now();
5966 let updated = if stopping {
5967 library.stop_purge(&waiting, now, environment.rng())?
5968 } else {
5969 library.end_wait(&waiting, now)?.1
5970 };
5971 let kept = library.changes_kept()?;
5973 for backup in updated {
5974 if let Some(on) = waiting
5975 .iter()
5976 .filter_map(|place| place.on.as_ref())
5977 .find(|on| on.backup == backup.id)
5978 {
5979 records.record_backup(on.backup, &on.folder, Some((now, kept)))?;
5980 }
5981 }
5982 }
5983 output::purge_waited((&waiting, &space), (stopping, yes), &zone, json, output)?;
5984 if yes {
5985 Ok(())
5986 } else {
5987 Err(CliError::Unconfirmed)
5988 }
5989}
5990
5991fn move_command<E: Environment>(
5996 library: &mut Library,
5997 ((entity, to, without_history, confirmed), (keep_behind, leave_secrets)): (
5998 (&str, &str, bool, bool),
5999 (bool, bool),
6000 ),
6001 json: bool,
6002 environment: &mut E,
6003 timings: &mut Timings,
6004 output: &mut dyn Write,
6005) -> Result<(), CliError> {
6006 let (from, found) = library.locate(entity)?;
6007 let to = library.find_space(to)?;
6008 let preview = library.move_preview(from, found, to)?;
6009 let name = |space: nibkeep_base::SpaceId| -> Result<String, CliError> {
6010 Ok(library
6011 .space_name(space)?
6012 .unwrap_or_else(|| space.to_string()))
6013 };
6014 let (from_name, to_name) = (name(from)?, name(to)?);
6015 let others = !preview.losing.is_empty() || !preview.gaining.is_empty();
6018 if (preview.entities.len() > 1 || !preview.staying.is_empty() || others) && !confirmed {
6019 let name_of = |entity| library.name(from, entity).ok().flatten();
6020 output::move_preview(&preview, (&from_name, &to_name), &name_of, json, output)?;
6021 return Err(CliError::UnconfirmedMove);
6022 }
6023 let history = if without_history {
6024 MoveHistory::Leave
6025 } else {
6026 MoveHistory::Bring
6027 };
6028 let behind = if keep_behind {
6029 nibkeep_node::Behind::Keep
6030 } else {
6031 nibkeep_node::Behind::Purge
6032 };
6033 let secrets = if leave_secrets {
6034 MoveSecrets::Leave
6035 } else {
6036 MoveSecrets::Bring
6037 };
6038 if preview.secrets && !leave_secrets && library.secrets_protection()?.is_some() {
6040 unlock_secrets(library, false, environment, timings)?;
6041 }
6042 let now = environment.now();
6043 let moved = library.move_entity(
6044 from,
6045 found,
6046 to,
6047 history,
6048 behind,
6049 secrets,
6050 now,
6051 environment.rng(),
6052 );
6053 library.lock_secrets();
6054 let moved = moved?;
6055 output::moved(moved, preview.entities.len(), &to_name, json, output)?;
6056 output::seen_first(
6057 &preview.gaining,
6058 history == MoveHistory::Bring,
6059 json,
6060 output,
6061 )?;
6062 if behind == nibkeep_node::Behind::Purge {
6063 output::purged_later(&preview, &from_name, json, output)?;
6064 }
6065 Ok(())
6066}
6067
6068fn purge_either<E: Environment>(
6071 library: &mut Library,
6072 (entity, value, confirmed): (&str, Option<&str>, bool),
6073 json: bool,
6074 environment: &mut E,
6075 timings: &mut Timings,
6076 output: &mut dyn Write,
6077) -> Result<(), CliError> {
6078 match value {
6079 Some(value) => purge_command(
6080 library,
6081 (entity, value, confirmed),
6082 json,
6083 environment,
6084 timings,
6085 output,
6086 ),
6087 None => purge_behind_command(
6088 library,
6089 (entity, confirmed),
6090 json,
6091 environment,
6092 timings,
6093 output,
6094 ),
6095 }
6096}
6097
6098fn purge_behind_command<E: Environment>(
6103 library: &mut Library,
6104 (entity, confirmed): (&str, bool),
6105 json: bool,
6106 environment: &mut E,
6107 timings: &mut Timings,
6108 output: &mut dyn Write,
6109) -> Result<(), CliError> {
6110 let mut asked = None;
6113 for space in library.spaces() {
6114 if let Ok(found) = library.find_entity_or_deleted(space, entity)
6115 && library.behind(space, found)?.is_some()
6116 {
6117 asked = Some((space, found));
6118 break;
6119 }
6120 }
6121 let Some((space, found)) = asked else {
6122 return Err(NodeError::NoPurgeAsked(entity.to_owned()).into());
6123 };
6124 let mut secret = library.may_hold_secrets(space, found)?;
6126 if let Some((there, now)) = library.moved_into(space, found)? {
6127 secret |= library.may_hold_secrets(there, now)?;
6128 }
6129 if secret && library.secrets_protection()?.is_some() {
6130 unlock_secrets(library, false, environment, timings)?;
6131 }
6132 let purged = purge_behind_found(
6133 library,
6134 (space, found, confirmed),
6135 json,
6136 environment,
6137 output,
6138 );
6139 library.lock_secrets();
6140 purged
6141}
6142
6143fn purge_behind_found<E: Environment>(
6146 library: &mut Library,
6147 (space, found, confirmed): (nibkeep_base::SpaceId, nibkeep_base::EntityId, bool),
6148 json: bool,
6149 environment: &mut E,
6150 output: &mut dyn Write,
6151) -> Result<(), CliError> {
6152 let remaining = library.behind(space, found)?.unwrap_or_default();
6153 if !confirmed && remaining > 0 {
6154 output::purge_behind(remaining, false, json, output)?;
6155 return Err(CliError::Unconfirmed);
6156 }
6157 let now = environment.now();
6158 let purged = library.purge_behind(space, found, now, environment.rng())?;
6159 output::purge_behind(purged, true, json, output)
6160}
6161
6162fn space_names(library: &Library, spaces: &[nibkeep_base::SpaceId]) -> Vec<String> {
6164 spaces
6165 .iter()
6166 .map(|&space| {
6167 library
6168 .space_name(space)
6169 .ok()
6170 .flatten()
6171 .unwrap_or_else(|| space.to_string())
6172 })
6173 .collect()
6174}
6175
6176fn sorted_space_names(library: &Library, spaces: &[nibkeep_base::SpaceId]) -> Vec<String> {
6178 let mut names = space_names(library, spaces);
6179 names.sort();
6180 names
6181}
6182
6183fn purge_values<E: Environment>(
6186 library: &mut Library,
6187 (entity, field, value): (
6188 nibkeep_base::EntityId,
6189 &FieldName,
6190 Option<&nibkeep_model::Value>,
6191 ),
6192 confirmed: bool,
6193 environment: &mut E,
6194) -> Result<nibkeep_node::Purge, NodeError> {
6195 let space = library.default_space();
6196 if confirmed {
6197 let now = environment.now();
6198 library.purge(space, entity, field, value, now, environment.rng())
6199 } else {
6200 library.purgeable(space, entity, field, value)
6201 }
6202}
6203
6204fn takeout_command<E: Environment>(
6208 library: &mut Library,
6209 (parts, from): (&[PathBuf], Option<&str>),
6210 json: bool,
6211 environment: &mut E,
6212 output: &mut dyn Write,
6213) -> Result<(), CliError> {
6214 let space = library.default_space();
6215 let takeout = nibkeep_import::Takeout::open(parts).map_err(import_error)?;
6216 let started = environment.now();
6217 let began = std::time::Instant::now();
6218 let now = move || started + u64::try_from(began.elapsed().as_millis()).unwrap_or(0);
6219 library.install_policies(
6220 space,
6221 environment.downloads().as_deref(),
6222 now(),
6223 environment.rng(),
6224 )?;
6225 let mut found = output::FilesAdded::default();
6226 let mut pictures = Vec::new();
6227 let mut thumbnails_rng = UnwrapErr(SysRng);
6228 let source = from.unwrap_or(nibkeep_import::GOOGLE_PHOTOS);
6229 let report = takeout
6230 .import(
6231 library,
6232 (space, source),
6233 &now,
6234 environment.rng(),
6235 &mut |library, imported| {
6236 if let Some(added) = &imported.added
6237 && !added.known
6238 {
6239 pictures.push(added.content);
6240 }
6241 if pictures.len() >= THUMBNAIL_ROUND {
6242 thumbnails_of(
6243 library,
6244 (space, &mut pictures),
6245 &mut found,
6246 (now(), &mut thumbnails_rng),
6247 );
6248 }
6249 Ok(())
6250 },
6251 )
6252 .map_err(import_error)?;
6253 thumbnails_of(
6254 library,
6255 (space, &mut pictures),
6256 &mut found,
6257 (now(), &mut thumbnails_rng),
6258 );
6259 output::takeout_imported((&report, source), &found, json, output)?;
6260 match report.failed.len() {
6261 0 => Ok(()),
6262 failed => Err(CliError::FilesFailed(failed)),
6263 }
6264}
6265
6266fn import_error(error: nibkeep_import::ImportError) -> CliError {
6268 match error {
6269 nibkeep_import::ImportError::Node(error) => error.into(),
6270 other => CliError::Import(other.to_string()),
6271 }
6272}
6273
6274fn path_in_source(given: &[PathBuf], file: &Path) -> Option<String> {
6277 let root = given.iter().find(|given| file.starts_with(given))?;
6278 let base = root.parent().unwrap_or(Path::new(""));
6279 let within = file.strip_prefix(base).ok()?;
6280 let names: Vec<String> = within
6281 .components()
6282 .filter_map(|part| match part {
6283 std::path::Component::Normal(name) => Some(name.to_string_lossy().into_owned()),
6284 _ => None,
6285 })
6286 .collect();
6287 (!names.is_empty()).then(|| names.join("/"))
6288}
6289
6290fn file_add_command<E: Environment>(
6294 library: &mut Library,
6295 (paths, own, from): (&[PathBuf], &Path, Option<&str>),
6296 json: bool,
6297 environment: &mut E,
6298 output: &mut dyn Write,
6299) -> Result<(), CliError> {
6300 let space = library.default_space();
6301 let source = match from {
6302 Some(name) => {
6303 let now = environment.now();
6304 Some(library.source_named(space, name, now, environment.rng())?)
6305 }
6306 None => None,
6307 };
6308 let mut found = output::FilesAdded::default();
6309 let mut files = Vec::new();
6310 let own = std::fs::canonicalize(own).unwrap_or_else(|_| own.to_owned());
6312 for path in paths {
6313 gather(path, (true, &own), &mut files, &mut found);
6314 }
6315 if !json {
6316 for (path, reason) in &found.failed {
6317 output::file_failed(path, reason, output)?;
6318 }
6319 }
6320 let downloads = environment.downloads();
6321 let now = environment.now();
6322 library.install_policies(space, downloads.as_deref(), now, environment.rng())?;
6323 let mut pictures = Vec::new();
6325 for path in files {
6326 if pictures.len() >= THUMBNAIL_ROUND {
6327 thumbnail_round(library, (space, &mut pictures), &mut found, environment);
6328 }
6329 if !json && let Ok(Some(question)) = library.question_for(space, &path) {
6331 let asked = environment.ask(&output::question(&path, &question))?;
6332 let answer = asked.and_then(|answer| match answer.to_lowercase().as_str() {
6333 "y" | "yes" => Some(true),
6334 "n" | "no" => Some(false),
6335 _ => None,
6336 });
6337 if let Some(again) = answer {
6338 let now = environment.now();
6339 library.answer(space, &question, again, now, environment.rng())?;
6340 }
6341 }
6342 let now = environment.now();
6343 let from = nibkeep_node::FileFrom {
6344 source,
6345 source_path: source.and_then(|_| path_in_source(paths, &path)),
6346 ..nibkeep_node::FileFrom::default()
6347 };
6348 match library.add_file_from(space, &path, &from, now, environment.rng()) {
6349 Ok(added) => {
6350 if !json {
6351 let name_of = |entity| library.name(space, entity).ok().flatten();
6352 output::file_added(&path, &added, &name_of, output)?;
6353 }
6354 if !added.known {
6357 pictures.push(added.content);
6358 }
6359 found.added.push((path, added));
6360 }
6361 Err(NodeError::Unreadable { reason, .. }) => {
6362 if !json {
6363 output::file_failed(&path, &reason, output)?;
6364 }
6365 found.failed.push((path, reason));
6366 }
6367 Err(NodeError::CheckedOut(_) | NodeError::InTree(_)) if !paths.contains(&path) => {
6369 found.left_out += 1;
6370 }
6371 Err(error @ (NodeError::CheckedOut(_) | NodeError::InTree(_))) => {
6372 let reason = if matches!(error, NodeError::InTree(_)) {
6373 "in a tree; nib commit records it"
6374 } else {
6375 "a checkout; nib file checkin records its edits"
6376 };
6377 if !json {
6378 output::file_failed(&path, reason, output)?;
6379 }
6380 found.failed.push((path, reason.to_owned()));
6381 }
6382 Err(error) => {
6383 thumbnail_round(library, (space, &mut pictures), &mut found, environment);
6384 output::files_added(&found, json, output)?;
6385 return Err(error.into());
6386 }
6387 }
6388 }
6389 thumbnail_round(library, (space, &mut pictures), &mut found, environment);
6390 output::files_added(&found, json, output)?;
6391 match found.failed.len() {
6392 0 => Ok(()),
6393 failed => Err(CliError::FilesFailed(failed)),
6394 }
6395}
6396
6397fn thumbnail_round<E: Environment>(
6401 library: &mut Library,
6402 (space, pictures): (SpaceId, &mut Vec<nibkeep_base::Hash>),
6403 found: &mut output::FilesAdded,
6404 environment: &mut E,
6405) {
6406 let now = environment.now();
6407 thumbnails_of(library, (space, pictures), found, (now, environment.rng()));
6408}
6409
6410fn thumbnails_of(
6412 library: &mut Library,
6413 (space, pictures): (SpaceId, &mut Vec<nibkeep_base::Hash>),
6414 found: &mut output::FilesAdded,
6415 (now, rng): (u64, &mut impl getrandom::rand_core::CryptoRng),
6416) {
6417 if found.thumbnails_failed.is_none() && !pictures.is_empty() {
6418 match library.make_thumbnails(space, pictures, now, rng) {
6419 Ok(made) => found.thumbnails += made,
6420 Err(error) => found.thumbnails_failed = Some(error.to_string()),
6421 }
6422 }
6423 pictures.clear();
6424}
6425
6426fn file_command<E: Environment>(
6428 library: &mut Library,
6429 (command, folder): (&FileCommand, &Path),
6430 cli: &Cli,
6431 environment: &mut E,
6432 timings: &mut Timings,
6433 output: &mut dyn Write,
6434) -> Result<(), CliError> {
6435 let json = cli.json;
6436 match command {
6437 FileCommand::Add {
6438 paths,
6439 secret: true,
6440 to,
6441 ..
6442 } => {
6443 let added =
6444 secret_file_add_command(library, (paths, to), json, environment, timings, output);
6445 library.lock_secrets();
6446 added
6447 }
6448 FileCommand::Add { paths, from, .. } => {
6449 let own = folder.join(LIBRARY_DATA);
6450 let added = (paths.as_slice(), &*own, from.as_deref());
6451 file_add_command(library, added, json, environment, output)
6452 }
6453 FileCommand::Checkout { file, path } => {
6454 let checkout = (file.as_str(), path.as_deref());
6455 file_checkout_command(library, checkout, cli, environment, output)
6456 }
6457 FileCommand::Pin { file, device } | FileCommand::Unpin { file, device } => {
6458 let pinned = matches!(command, FileCommand::Pin { .. });
6459 let (space, file) = library.locate(file)?;
6460 let (device, device_name) = if let Some(device) = device {
6461 one_device(library, device)?
6462 } else {
6463 let this = library.replicas()?.into_iter().find(|replica| replica.this);
6464 (
6465 this.as_ref()
6466 .and_then(|replica| replica.device)
6467 .ok_or_else(|| NodeError::WhichDevice("this device".to_owned()))?,
6468 this.and_then(|replica| replica.device_name),
6469 )
6470 };
6471 let now = environment.now();
6472 library.pin_file((space, file), device, pinned, now, environment.rng())?;
6473 let name = library.name(space, file)?;
6474 output::pinned(
6475 (file, name.as_deref()),
6476 (device, device_name.as_deref()),
6477 pinned,
6478 json,
6479 output,
6480 )
6481 }
6482 FileCommand::Checkin { copy, keep, force } => {
6483 let checkin = (copy.as_str(), *keep, *force);
6484 file_checkin_command(library, checkin, json, environment, output)
6485 }
6486 FileCommand::Where { file } => {
6487 let (space, file) = library.locate(file)?;
6488 let copies = library.copies_of(space, file, environment.now())?;
6489 let name = library.name(space, file)?;
6490 let zone = environment.time_zone();
6491 output::file_copies((&copies, name.as_deref()), &zone, json, output)
6492 }
6493 FileCommand::Thumbnail { file, path } => {
6494 let (space, file) = library.locate(file)?;
6495 let path = absolute(path, environment)?;
6496 let thumbnail = library
6497 .thumbnail(space, file)?
6498 .ok_or_else(|| CliError::NoThumbnail(file.to_string()))?;
6499 match library.save_thumbnail(space, &thumbnail, &path) {
6500 Err(NodeError::PlaceTaken(path)) => return Err(CliError::Exists(path)),
6501 saved => saved?,
6502 }
6503 output::thumbnail_written(&thumbnail, &path, json, output)
6504 }
6505 FileCommand::Thumbnails => {
6506 let space = library.default_space();
6507 let now = environment.now();
6508 let mut progress = |made: nibkeep_node::ThumbnailsMade, of: usize| {
6510 let done = made.made + made.unreadable + made.not_here;
6511 if of > THUMBNAIL_ROUND && done < of {
6512 let _ = output::progress(&format!("{done} of {of} picturesā¦"), json, output);
6513 }
6514 };
6515 let made = library.make_missing_thumbnails(
6516 space,
6517 THUMBNAIL_ROUND,
6518 now,
6519 environment.rng(),
6520 &mut progress,
6521 )?;
6522 let left = library.missing_thumbnails(space)?.len();
6523 output::thumbnails_made(made, left, json, output)
6524 }
6525 }
6526}
6527
6528const THUMBNAIL_ROUND: usize = 64;
6532
6533struct RustDecoders;
6536
6537impl nibkeep_node::Thumbnailer for RustDecoders {
6538 fn made_with(&self) -> &str {
6539 nibkeep_thumbnails::MADE_WITH
6540 }
6541
6542 fn reads(&self, media_type: &str) -> bool {
6543 nibkeep_thumbnails::reads(media_type)
6544 }
6545
6546 fn make(&self, picture: &[u8]) -> Option<nibkeep_node::Thumbnail> {
6547 let made = nibkeep_thumbnails::make(picture).ok()?;
6548 Some(nibkeep_node::Thumbnail {
6549 jpeg: made.jpeg,
6550 width: made.width,
6551 height: made.height,
6552 picture_hash: Some(made.picture_hash),
6553 })
6554 }
6555}
6556
6557fn file_checkout_command<E: Environment>(
6560 library: &mut Library,
6561 (file, place): (&str, Option<&Path>),
6562 cli: &Cli,
6563 environment: &mut E,
6564 output: &mut dyn Write,
6565) -> Result<(), CliError> {
6566 let json = cli.json;
6567 let (space, file) = library.locate(file)?;
6568 library.choose_space(Some(space))?;
6570 let place = match place {
6571 Some(place) => absolute(place, environment)?,
6572 None => current_dir(environment)?,
6573 };
6574 let now = environment.now();
6575 let checked_out = match library.checkout(space, file, &place, now, environment.rng()) {
6576 Err(NodeError::SecretFile(name)) => return Err(CliError::SecretFileCheckout(name)),
6577 Err(NodeError::NoCopyHere(name)) => {
6579 let (holders, reached) = fetch((space, file), library, cli, environment, output)?;
6580 let now = environment.now();
6581 match library.checkout(space, file, &place, now, environment.rng()) {
6582 Err(NodeError::NoCopyHere(_)) if !reached.is_empty() => {
6583 return Err(CliError::NotGiven {
6584 name,
6585 holders: reached,
6586 });
6587 }
6588 Err(NodeError::NoCopyHere(_)) if !holders.is_empty() => {
6589 return Err(CliError::NotFetched { name, holders });
6590 }
6591 checked_out => checked_out?,
6592 }
6593 }
6594 checked_out => checked_out?,
6595 };
6596 let name = library.name(space, checked_out.file)?;
6597 output::checked_out(&checked_out, name.as_deref(), json, output)
6598}
6599
6600const FETCH_WAIT: Duration = Duration::from_secs(10);
6603
6604fn fetch<E: Environment>(
6609 (space, file): (nibkeep_base::SpaceId, EntityId),
6610 library: &mut Library,
6611 cli: &Cli,
6612 environment: &mut E,
6613 output: &mut dyn Write,
6614) -> Result<(Vec<String>, Vec<String>), CliError> {
6615 let holders = library.holders_of(space, file)?;
6616 let name_of = |replica: &nibkeep_node::Replica| {
6617 let app = replica.name.clone().unwrap_or_else(|| "nib".to_owned());
6618 match &replica.device_name {
6619 Some(device) => format!("{app} on {device}"),
6620 None => app,
6621 }
6622 };
6623 let names: Vec<String> = holders.iter().map(name_of).collect();
6624 if holders.is_empty() {
6625 return Ok((names, Vec::new()));
6626 }
6627 output::progress(
6628 &format!("Fetching it from {}ā¦", names.join(", ")),
6629 cli.json,
6630 output,
6631 )?;
6632 let waited = Instant::now();
6633 let _role = loop {
6634 if let Some(role) = library.take_role()? {
6635 break role;
6636 }
6637 let records = library.sync_records(UnwrapErr(SysRng))?;
6638 if let Some(holder) = records.holder()? {
6639 let asked = environment.now();
6640 let asks = holders
6641 .iter()
6642 .map(|replica| records.ask(Some(replica.id), asked))
6643 .collect::<Result<Vec<_>, _>>()?;
6644 let mut released = false;
6645 while !released
6646 && asks
6647 .iter()
6648 .any(|ask| matches!(records.answered(*ask), Ok(None)))
6649 {
6650 if library.take_role()?.is_some() {
6651 released = true;
6652 } else if waited.elapsed() > FETCH_WAIT + ASK_WAIT {
6653 return Err(CliError::NotAnswered(holder.program));
6654 } else {
6655 std::thread::sleep(Duration::from_millis(100));
6656 }
6657 }
6658 if !released {
6659 library.catch_up()?;
6660 let synced = records.synced_since(asked)?;
6661 let reached = holders
6662 .iter()
6663 .filter(|replica| synced.contains_key(&replica.id))
6664 .map(name_of)
6665 .collect();
6666 return Ok((names, reached));
6667 }
6668 continue;
6669 }
6670 if waited.elapsed() > FETCH_WAIT + ASK_WAIT {
6671 return Err(CliError::NotAnswered("another program".to_owned()));
6672 }
6673 std::thread::sleep(Duration::from_millis(100));
6674 };
6675 let network = library.network(cli.network(false))?;
6676 let endpoints = holders
6677 .iter()
6678 .filter_map(|replica| replica.endpoint)
6679 .collect();
6680 let found = network.find(&endpoints, FETCH_WAIT);
6681 let now = clock(environment);
6682 let synced =
6684 nibkeep_node::sync_with_found(library, &network, holders, &found, &now, environment.rng());
6685 let reached = synced
6686 .iter()
6687 .filter(|with| with.synced.is_ok())
6688 .map(|with| name_of(&with.replica))
6689 .collect();
6690 Ok((names, reached))
6691}
6692
6693fn one_device(library: &Library, device: &str) -> Result<(EntityId, Option<String>), CliError> {
6696 let replicas = library.replicas_named(device)?;
6697 let devices: std::collections::BTreeSet<EntityId> = replicas
6698 .iter()
6699 .filter_map(|replica| replica.device)
6700 .collect();
6701 let mut found = devices.into_iter();
6702 let (Some(chosen), None) = (found.next(), found.next()) else {
6703 return Err(NodeError::WhichDevice(format!(
6704 "{device} names no one device of yours; nib device list shows them"
6705 ))
6706 .into());
6707 };
6708 let name = replicas
6709 .iter()
6710 .find(|replica| replica.device == Some(chosen))
6711 .and_then(|replica| replica.device_name.clone());
6712 Ok((chosen, name))
6713}
6714
6715fn devices_named(library: &Library, devices: &[String]) -> Result<Vec<EntityId>, CliError> {
6718 let mut records = Vec::new();
6719 for device in devices {
6720 let named: Vec<EntityId> = library
6721 .replicas_named(device)?
6722 .into_iter()
6723 .filter(|replica| !replica.revoked && !replica.ai_agent && !replica.this)
6724 .map(|replica| replica.id)
6725 .collect();
6726 if named.is_empty() {
6727 return Err(NodeError::WhichDevice(format!(
6728 "{device} names no other device of yours; nib device list shows them"
6729 ))
6730 .into());
6731 }
6732 records.extend(named);
6733 }
6734 Ok(records)
6735}
6736
6737#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6740pub struct Keeps(Option<u64>);
6741
6742#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6745pub struct Waits(Option<u64>);
6746
6747fn parse_waits(text: &str) -> Result<Waits, String> {
6749 let text = text.trim().to_ascii_lowercase();
6750 match text.as_str() {
6751 "default" => return Ok(Waits(None)),
6752 "none" | "0" => return Ok(Waits(Some(0))),
6753 _ => {}
6754 }
6755 let digits = text
6756 .strip_suffix("days")
6757 .or_else(|| text.strip_suffix("day"))
6758 .or_else(|| text.strip_suffix('d'))
6759 .unwrap_or(&text)
6760 .trim();
6761 match digits.parse::<u64>() {
6762 Ok(days @ 1..=nibkeep_node::MOST_WAIT_DAYS) => Ok(Waits(Some(days))),
6763 _ => Err("days from 1 to 365, such as 30, or none, or default".to_owned()),
6764 }
6765}
6766
6767fn parse_keeps(text: &str) -> Result<Keeps, String> {
6769 if text.trim().eq_ignore_ascii_case("default") {
6770 return Ok(Keeps(None));
6771 }
6772 parse_size(text).map(|size| Keeps(Some(size)))
6773}
6774
6775fn secret_file_add_command<E: Environment>(
6779 library: &mut Library,
6780 (paths, to): (&[PathBuf], &[String]),
6781 json: bool,
6782 environment: &mut E,
6783 timings: &mut Timings,
6784 output: &mut dyn Write,
6785) -> Result<(), CliError> {
6786 let space = library.default_space();
6787 let mut attached_to = Vec::with_capacity(to.len());
6788 for entity in to {
6789 attached_to.push(library.find_entity(space, entity)?);
6790 }
6791 let mut files = Vec::with_capacity(paths.len());
6793 for path in paths {
6794 let path = absolute(path, environment)?;
6795 if path.is_dir() {
6796 return Err(CliError::SecretFolder(path));
6797 }
6798 files.push(path);
6799 }
6800 unlock_secrets(library, true, environment, timings)?;
6801 let mut added = Vec::with_capacity(files.len());
6802 let mut failed = Vec::new();
6803 for path in files {
6804 let file = match std::fs::File::open(&path) {
6806 Ok(file) => file,
6807 Err(error) => {
6808 if !json {
6809 output::file_failed(&path, &error.to_string(), output)?;
6810 }
6811 failed.push((path, error.to_string()));
6812 continue;
6813 }
6814 };
6815 let name = path
6816 .file_name()
6817 .map_or_default(|name| name.to_string_lossy().into_owned());
6818 let now = environment.now();
6819 let secret_file =
6820 match library.add_secret_file(space, &name, file, &attached_to, now, environment.rng())
6821 {
6822 Ok(secret_file) => secret_file,
6823 Err(NodeError::Unreadable { reason, .. }) => {
6824 if !json {
6825 output::file_failed(&path, &reason, output)?;
6826 }
6827 failed.push((path, reason));
6828 continue;
6829 }
6830 Err(error) => return Err(error.into()),
6831 };
6832 if !json {
6833 let name_of = |entity| library.name(space, entity).ok().flatten();
6834 output::secret_file_added(&path, &secret_file, (&attached_to, &name_of), output)?;
6835 }
6836 added.push((path, name, secret_file));
6837 }
6838 output::secret_files_added((&added, &failed), &attached_to, json, output)?;
6839 match failed.len() {
6840 0 => Ok(()),
6841 failed => Err(CliError::FilesFailed(failed)),
6842 }
6843}
6844
6845fn file_checkin_command<E: Environment>(
6848 library: &mut Library,
6849 (copy, keep, force): (&str, bool, bool),
6850 json: bool,
6851 environment: &mut E,
6852 output: &mut dyn Write,
6853) -> Result<(), CliError> {
6854 if library.chosen_space().is_none() {
6856 for space in library.spaces() {
6857 library.choose_space(Some(space))?;
6858 if find_checkout(library, copy, environment).is_ok() {
6859 break;
6860 }
6861 library.choose_space(None)?;
6862 }
6863 }
6864 let space = library.default_space();
6865 let checkout = find_checkout(library, copy, environment)?;
6866 let now = environment.now();
6867 let recorded = match library.record_edits(space, checkout.id, force, now, environment.rng()) {
6868 Err(NodeError::Stale(path)) => return Err(CliError::Stale(path)),
6869 recorded => recorded?,
6870 };
6871 let ended = if keep {
6872 None
6873 } else {
6874 let now = environment.now();
6875 Some(library.end_checkout(space, checkout.id, now, environment.rng())?)
6876 };
6877 let mut thumbnail_failed = None;
6880 if let Some(version) = recorded.version {
6881 let now = environment.now();
6882 if let Err(error) = library.make_thumbnails(space, &[version], now, environment.rng()) {
6883 thumbnail_failed = Some(error.to_string());
6884 }
6885 }
6886 let name = library.name(space, checkout.file)?;
6887 let checked_in = output::CheckedIn {
6888 checkout: &checkout,
6889 recorded,
6890 ended: ended.as_ref(),
6891 name: name.as_deref(),
6892 thumbnail_failed: thumbnail_failed.as_deref(),
6893 };
6894 output::checked_in(&checked_in, json, output)
6895}
6896
6897fn find_checkout<E: Environment>(
6901 library: &Library,
6902 copy: &str,
6903 environment: &E,
6904) -> Result<Checkout, CliError> {
6905 let space = library.default_space();
6906 let path = absolute(Path::new(copy), environment)?;
6907 if let Some(checkout) = library.checkout_at(space, &path)? {
6908 return Ok(checkout);
6909 }
6910 let file = match library.find_entity(space, copy) {
6911 Ok(file) => file,
6912 Err(NodeError::NoEntity(_)) => return Err(NodeError::NotCheckedOut(copy.to_owned()).into()),
6913 Err(error) => return Err(error.into()),
6914 };
6915 let mut checkouts = library.checkouts_of(space, file)?;
6916 match checkouts.len() {
6917 0 => Err(NodeError::NotCheckedOut(copy.to_owned()).into()),
6918 1 => Ok(checkouts.remove(0)),
6919 _ => Err(NodeError::WhichCheckout {
6920 file: copy.to_owned(),
6921 paths: checkouts
6922 .into_iter()
6923 .map(|checkout| checkout.path)
6924 .collect(),
6925 }
6926 .into()),
6927 }
6928}
6929
6930fn backup_edit<E: Environment>(
6932 library: &mut Library,
6933 command: &BackupCommand,
6934 environment: &mut E,
6935 json: bool,
6936 output: &mut dyn Write,
6937) -> Result<(), CliError> {
6938 let BackupCommand::Edit {
6939 backup,
6940 name,
6941 spaces,
6942 policies,
6943 every_policy,
6944 away,
6945 home,
6946 waits,
6947 } = command
6948 else {
6949 unreachable!("backup_command passes only an edit");
6950 };
6951
6952 let known = library.find_backup(backup)?;
6953 let spaces = (!spaces.is_empty())
6954 .then(|| {
6955 spaces
6956 .iter()
6957 .map(|space| library.find_space(space))
6958 .collect::<Result<Vec<_>, _>>()
6959 })
6960 .transpose()?;
6961 let of = spaces.clone().unwrap_or_else(|| known.spaces.clone());
6962 let policies = if *every_policy {
6963 Some(Vec::new())
6964 } else if policies.is_empty() {
6965 None
6966 } else {
6967 Some(backup_policies(library, &of, policies, environment)?)
6968 };
6969 let edit = BackupEdit {
6970 name: name.clone(),
6971 spaces,
6972 policies,
6973 away: (*away || *home).then_some(*away),
6974 waits: waits.map(|Waits(days)| days),
6975 };
6976 let now = environment.now();
6977 library.edit_backup(known.id, &edit, now, environment.rng())?;
6978 let edited = library.find_backup(&known.id.to_string())?;
6979 output::backup_edited(&edited, json, output)
6980}
6981
6982fn safekeeping_command<E: Environment>(
6985 library: &mut Library,
6986 cli: &Cli,
6987 environment: &mut E,
6988 timings: &mut Timings,
6989 output: &mut dyn Write,
6990) -> Result<(), CliError> {
6991 match &cli.command {
6992 Command::Backup { command } => backup_command(library, command, cli, environment, output),
6993 Command::Recovery { command } => {
6994 recovery_command(library, command, cli.json, environment, timings, output)
6995 }
6996 _ => unreachable!("only nib backup and nib recovery come here"),
6997 }
6998}
6999
7000const CODE_TRIES: usize = 3;
7002
7003fn typed_recovery_code<E: Environment>(
7006 prompt: &str,
7007 environment: &mut E,
7008 json: bool,
7009 output: &mut dyn Write,
7010) -> Result<RecoveryCode, CliError> {
7011 for _ in 0..CODE_TRIES {
7012 let typed = environment.passphrase(prompt)?;
7013 match RecoveryCode::from_text(&typed) {
7014 Ok(code) => return Ok(code),
7015 Err(error) if !json => writeln!(output, "{error}.")?,
7016 Err(_) => {}
7017 }
7018 }
7019 Err(CliError::NotARecoveryCode)
7020}
7021
7022fn recovery_new_command<E: Environment>(
7024 library: &mut Library,
7025 (secrets, revoke_older): (bool, bool),
7026 json: bool,
7027 environment: &mut E,
7028 output: &mut dyn Write,
7029) -> Result<(), CliError> {
7030 let code = RecoveryCode::generate(environment.rng());
7031 output::recovery_shown(&code, json, output)?;
7032 let mut stands = None;
7034 for _ in 0..if json { 0 } else { CODE_TRIES } {
7035 let prompt = "Type the code back, or press Enter to do it later: ";
7038 let Ok(typed) = environment.passphrase(prompt) else {
7039 break;
7040 };
7041 if typed.trim().is_empty() {
7042 break;
7043 }
7044 match RecoveryCode::from_text(&typed) {
7045 Ok(typed) if typed.same_as(&code) => {
7046 let now = environment.now();
7047 stands = Some(library.add_recovery_code(&code, secrets, now, environment.rng())?);
7048 break;
7049 }
7050 Ok(_) => writeln!(output, "That is another code than the one shown.")?,
7051 Err(error) => writeln!(output, "{error}.")?,
7052 }
7053 }
7054 let replaced = if stands.is_some() {
7056 let now = environment.now();
7057 library.revoke_replaced_recovery_codes(revoke_older, now, environment.rng())?
7058 } else {
7059 Vec::new()
7060 };
7061 let codes = library.recovery_codes()?;
7062 output::recovery_made(&code, stands.as_ref(), (&replaced, &codes), json, output)
7063}
7064
7065fn recovery_command<E: Environment>(
7067 library: &mut Library,
7068 command: &RecoveryCommand,
7069 json: bool,
7070 environment: &mut E,
7071 timings: &mut Timings,
7072 output: &mut dyn Write,
7073) -> Result<(), CliError> {
7074 const TYPE_IT: &str = "The recovery code: ";
7075 if let RecoveryCommand::New { secrets: true, .. }
7077 | RecoveryCommand::Confirm { secrets: true, .. }
7078 | RecoveryCommand::Check { secrets: true } = command
7079 {
7080 unlock_secrets(library, false, environment, timings)?;
7081 }
7082 match command {
7083 RecoveryCommand::New {
7084 secrets,
7085 revoke_older,
7086 } => {
7087 let new = (*secrets, *revoke_older);
7088 recovery_new_command(library, new, json, environment, output)
7089 }
7090 RecoveryCommand::Confirm {
7091 secrets,
7092 revoke_older,
7093 } => {
7094 let code = typed_recovery_code(TYPE_IT, environment, json, output)?;
7095 let standing = library
7096 .check_recovery_code(&code)?
7097 .code
7098 .filter(|named| !named.revoked);
7099 let already = standing.is_some();
7100 let named = match standing {
7101 Some(named) if !*secrets || named.holds_secrets => named,
7102 _ => {
7103 let now = environment.now();
7104 library.add_recovery_code(&code, *secrets, now, environment.rng())?
7105 }
7106 };
7107 let at_once = *revoke_older && named.replaced_by.is_none();
7110 let now = environment.now();
7111 let replaced =
7112 library.revoke_replaced_recovery_codes(at_once, now, environment.rng())?;
7113 let codes = library.recovery_codes()?;
7114 output::recovery_confirmed(&named, already, (&replaced, &codes), json, output)
7115 }
7116 RecoveryCommand::List => {
7117 let zone = environment.time_zone();
7118 output::recovery_list(&library.recovery_codes()?, &zone, json, output)
7119 }
7120 RecoveryCommand::Check { .. } => {
7121 let code = typed_recovery_code(TYPE_IT, environment, json, output)?;
7122 let check = library.check_recovery_code(&code)?;
7123 output::recovery_checked(&check, json, output)?;
7124 if check.code.is_some() {
7125 Ok(())
7126 } else {
7127 Err(CliError::UnknownRecoveryCode)
7128 }
7129 }
7130 RecoveryCommand::Revoke { code, yes } => {
7131 let mut named = library.find_recovery_code(code)?;
7132 if *yes {
7133 let now = environment.now();
7134 named = library.revoke_recovery_code(code, now, environment.rng())?;
7135 }
7136 let zone = environment.time_zone();
7137 output::recovery_revoked(&named, &zone, json, output)?;
7138 if *yes {
7139 Ok(())
7140 } else {
7141 Err(CliError::UnconfirmedRevoke)
7142 }
7143 }
7144 RecoveryCommand::Restore { .. } | RecoveryCommand::FromCopy { .. } => {
7145 unreachable!("run_command makes the library")
7146 }
7147 }
7148}
7149
7150fn backup_command<E: Environment>(
7152 library: &mut Library,
7153 command: &BackupCommand,
7154 cli: &Cli,
7155 environment: &mut E,
7156 output: &mut dyn Write,
7157) -> Result<(), CliError> {
7158 let json = cli.json;
7159 let records = library.sync_records(UnwrapErr(SysRng))?;
7160 let remembered: BTreeMap<EntityId, PathBuf> = records
7161 .backup_folders()?
7162 .into_iter()
7163 .map(|(backup, found)| (backup, found.folder))
7164 .collect();
7165 match command {
7166 BackupCommand::New {
7167 folder,
7168 name,
7169 spaces,
7170 policies,
7171 away,
7172 waits,
7173 } => {
7174 let spaces = spaces
7175 .iter()
7176 .map(|space| library.find_space(space))
7177 .collect::<Result<Vec<_>, _>>()?;
7178 let policies = backup_policies(library, &spaces, policies, environment)?;
7179 let name = name.clone().unwrap_or_else(|| {
7180 folder.file_name().map_or_else(
7181 || "Backup".to_owned(),
7182 |name| name.to_string_lossy().into_owned(),
7183 )
7184 });
7185 let new = NewBackup {
7186 name,
7187 spaces,
7188 policies,
7189 away: *away,
7190 waits: waits.and_then(|Waits(days)| days),
7191 };
7192 backup_add(library, (folder, &new), &records, environment, json, output)
7193 }
7194 BackupCommand::List => backup_list(library, &remembered, environment, json, output),
7195 BackupCommand::Update { backup, at } => {
7196 let chosen = backups_to_update(library, backup.as_deref(), at.as_deref(), &remembered)?;
7197 let mut failed = None;
7198 for (backup, folder) in chosen {
7199 let folder = std::path::absolute(&folder).unwrap_or(folder);
7200 let now = || environment.now();
7201 let updated = library.update_backup(&backup, &folder, &now, &|| false);
7202 if let Ok(Some(_)) = &updated {
7203 let kept = library.changes_kept()?;
7204 records.record_backup(backup.id, &folder, Some((now(), kept)))?;
7205 }
7206 let shown = output::backup_updated(&backup, &folder, &updated, json, output);
7207 if let Err(error) = updated {
7208 failed.get_or_insert(error);
7209 }
7210 shown?;
7211 }
7212 failed.map_or(Ok(()), |error| Err(error.into()))
7213 }
7214 BackupCommand::Edit { .. } => backup_edit(library, command, environment, json, output),
7215 BackupCommand::Remove { backup } => {
7216 let known = library.find_backup(backup)?;
7217 let now = environment.now();
7218 library.remove_backup(known.id, now, environment.rng())?;
7219 let folder = remembered.get(&known.id);
7220 output::backup_removed(&known, folder.map(PathBuf::as_path), json, output)
7221 }
7222 }
7223}
7224
7225fn backup_add<E: Environment>(
7227 library: &mut Library,
7228 (folder, new): (&Path, &NewBackup),
7229 records: &nibkeep_node::Records,
7230 environment: &mut E,
7231 json: bool,
7232 output: &mut dyn Write,
7233) -> Result<(), CliError> {
7234 let now = environment.now();
7235 let added = library.add_backup(folder, new, now, environment.rng())?;
7236 let folder = std::path::absolute(folder).unwrap_or_else(|_| folder.to_owned());
7237 let now = || environment.now();
7238 let updated = library
7239 .update_backup(&added.backup, &folder, &now, &|| false)?
7240 .unwrap_or_default();
7241 records.record_backup(
7242 added.backup.id,
7243 &folder,
7244 Some((now(), library.changes_kept()?)),
7245 )?;
7246 output::backup_added(&added, &folder, &updated, json, output)
7247}
7248
7249fn backup_list<E: Environment>(
7251 library: &Library,
7252 remembered: &BTreeMap<EntityId, PathBuf>,
7253 environment: &E,
7254 json: bool,
7255 output: &mut dyn Write,
7256) -> Result<(), CliError> {
7257 let found: BTreeMap<EntityId, PathBuf> = library
7258 .find_backups(remembered)?
7259 .into_iter()
7260 .map(|(backup, folder)| (backup.id, folder))
7261 .collect();
7262 let now = environment.now();
7263 let mut listed = Vec::new();
7264 for backup in library.backups()? {
7265 let state = found
7266 .get(&backup.id)
7267 .and_then(|folder| library.backup_state(&backup, folder, now).ok());
7268 let spaces = backup
7269 .spaces
7270 .iter()
7271 .map(|space| {
7272 library
7273 .space_name(*space)
7274 .ok()
7275 .flatten()
7276 .unwrap_or_else(|| space.to_string())
7277 })
7278 .collect();
7279 let policies = backup
7280 .policies
7281 .iter()
7282 .map(|policy| {
7283 backup
7284 .spaces
7285 .iter()
7286 .find_map(|space| library.name(*space, *policy).ok().flatten())
7287 .unwrap_or_else(|| policy.to_string())
7288 })
7289 .collect();
7290 let folder = found.get(&backup.id).cloned();
7291 listed.push(output::ListedBackup {
7292 backup,
7293 folder,
7294 state,
7295 spaces,
7296 policies,
7297 });
7298 }
7299 output::backups(&listed, json, output)
7300}
7301
7302fn backups_to_update(
7306 library: &Library,
7307 backup: Option<&str>,
7308 at: Option<&Path>,
7309 remembered: &BTreeMap<EntityId, PathBuf>,
7310) -> Result<Vec<(Backup, PathBuf)>, NodeError> {
7311 Ok(match (backup, at) {
7312 (Some(reference), Some(folder)) => {
7313 vec![(library.find_backup(reference)?, folder.to_owned())]
7314 }
7315 (None, Some(folder)) => {
7316 let named = library
7317 .backups()?
7318 .into_iter()
7319 .find(|known| nibkeep_node::backup_named_at(folder) == Some(known.id))
7320 .ok_or_else(|| {
7321 NodeError::WhichBackup(format!("{} is no backup of yours", folder.display()))
7322 })?;
7323 vec![(named, folder.to_owned())]
7324 }
7325 (Some(reference), None) => {
7326 let backup = library.find_backup(reference)?;
7327 let found = library
7328 .find_backups(remembered)?
7329 .into_iter()
7330 .find(|(known, _)| known.id == backup.id)
7331 .ok_or_else(|| {
7332 NodeError::WhichBackup(format!(
7333 "this computer does not find the backup {}; plug it in, or say where it is with --at",
7334 backup.name
7335 ))
7336 })?;
7337 vec![found]
7338 }
7339 (None, None) => library.find_backups(remembered)?,
7340 })
7341}
7342
7343fn backup_policies<E: Environment>(
7346 library: &mut Library,
7347 spaces: &[SpaceId],
7348 names: &[String],
7349 environment: &mut E,
7350) -> Result<Vec<EntityId>, CliError> {
7351 if names.is_empty() {
7353 return Ok(Vec::new());
7354 }
7355 let spaces = if spaces.is_empty() {
7356 library.spaces()
7357 } else {
7358 spaces.to_vec()
7359 };
7360 let downloads = environment.downloads();
7361 for space in &spaces {
7362 let now = environment.now();
7363 library.install_policies(*space, downloads.as_deref(), now, environment.rng())?;
7364 }
7365 let mut found = Vec::new();
7366 for name in names {
7367 let policies: Vec<EntityId> = spaces
7368 .iter()
7369 .filter_map(|space| library.find_policy(*space, name).ok())
7370 .collect();
7371 if policies.is_empty() {
7372 return Err(NodeError::NoEntity(format!(
7373 "no policy of the backup's spaces is named {name}"
7374 ))
7375 .into());
7376 }
7377 found.extend(policies);
7378 }
7379 found.sort();
7380 found.dedup();
7381 Ok(found)
7382}
7383
7384fn policy_command<E: Environment>(
7387 library: &mut Library,
7388 command: &PolicyCommand,
7389 json: bool,
7390 environment: &mut E,
7391 output: &mut dyn Write,
7392) -> Result<(), CliError> {
7393 let space = library.default_space();
7394 let downloads = environment.downloads();
7395 let now = environment.now();
7396 library.install_policies(space, downloads.as_deref(), now, environment.rng())?;
7397 match command {
7398 PolicyCommand::List => {
7399 let policies = library.policies(space)?;
7400 let rules = library.rules(space)?;
7401 let name_of = |entity| library.name(space, entity).ok().flatten();
7402 output::policies(&policies, &rules, &name_of, json, output)
7403 }
7404 PolicyCommand::Show { policy } => {
7405 let id = library.find_policy(space, policy)?;
7406 let policies = library.policies(space)?;
7407 let rules = library.rules(space)?;
7408 let name_of = |entity| library.name(space, entity).ok().flatten();
7409 output::policy(id, &policies, &rules, &name_of, json, output)
7410 }
7411 PolicyCommand::New {
7412 name,
7413 copies,
7414 away,
7415 archived,
7416 in_place,
7417 } => {
7418 let needs = Needs {
7419 copies: *copies,
7420 away: *away,
7421 archived: *archived,
7422 kept: if *in_place {
7423 Kept::InPlace
7424 } else {
7425 Kept::Store
7426 },
7427 };
7428 let id = library.add_policy(space, name, needs, now, environment.rng())?;
7429 policy_changed("Added", id, library, json, output)
7430 }
7431 PolicyCommand::Edit {
7432 policy,
7433 name,
7434 copies,
7435 away,
7436 archived,
7437 in_place,
7438 store,
7439 } => {
7440 let id = library.find_policy(space, policy)?;
7441 let kept = match (*in_place, *store) {
7442 (true, _) => Some(Kept::InPlace),
7443 (_, true) => Some(Kept::Store),
7444 _ => None,
7445 };
7446 let edit = PolicyEdit {
7447 name: name.clone(),
7448 copies: *copies,
7449 away: *away,
7450 archived: *archived,
7451 kept,
7452 };
7453 library.edit_policy(space, id, &edit, now, environment.rng())?;
7454 policy_changed("Changed", id, library, json, output)
7455 }
7456 PolicyCommand::Remove { policy } => {
7457 let id = library.find_policy(space, policy)?;
7458 let name = library
7459 .policies(space)?
7460 .into_iter()
7461 .find(|known| known.id == id)
7462 .and_then(|known| known.name);
7463 library.remove_policy(space, id, now, environment.rng())?;
7464 output::removed_policy(id, name.as_deref(), json, output)
7465 }
7466 PolicyCommand::Rule { command } => {
7467 rule_command(library, command, json, environment, output)
7468 }
7469 PolicyCommand::Set {
7470 entity,
7471 policy,
7472 clear: _,
7473 } => {
7474 let id = library.find_entity(space, entity)?;
7475 let policy = policy
7476 .as_deref()
7477 .map(|policy| library.find_policy(space, policy))
7478 .transpose()?;
7479 library.set_policy(space, id, policy, now, environment.rng())?;
7480 why(library, id, json, output)
7481 }
7482 PolicyCommand::Why { entity } => {
7483 let id = library.find_entity(space, entity)?;
7484 why(library, id, json, output)
7485 }
7486 PolicyCommand::Check => {
7487 let check = library.check_policies(space, environment.now())?;
7488 let name_of = |entity| library.name(space, entity).ok().flatten();
7489 let zone = environment.time_zone();
7490 output::policy_check(&check, (&name_of, &zone), json, output)
7491 }
7492 }
7493}
7494
7495fn rule_command<E: Environment>(
7497 library: &mut Library,
7498 command: &RuleCommand,
7499 json: bool,
7500 environment: &mut E,
7501 output: &mut dyn Write,
7502) -> Result<(), CliError> {
7503 let space = library.default_space();
7504 let now = environment.now();
7505 match command {
7506 RuleCommand::New {
7507 policy,
7508 of_type,
7509 has,
7510 folder,
7511 media_type,
7512 larger_than,
7513 asks_above,
7514 place,
7515 } => {
7516 let types = library.types(space)?;
7517 let rule = NewRule {
7518 of_type: of_type
7519 .as_deref()
7520 .map(|name| types::type_named(name, &types))
7521 .transpose()?,
7522 has: has
7523 .as_deref()
7524 .map(|field| types::field_named(field, &types, &[FILE, PHOTO, VIDEO]))
7525 .transpose()?,
7526 folder: folder.clone(),
7527 media_type: media_type.clone(),
7528 larger_than: *larger_than,
7529 asks_above: *asks_above,
7530 ..NewRule::new(library.find_policy(space, policy)?)
7531 };
7532 let place = place_of(library, place)?.unwrap_or(Place::BeforeTheRest);
7533 let id = library.add_rule(space, &rule, place, now, environment.rng())?;
7534 rule_changed("Added", id, library, json, output)
7535 }
7536 RuleCommand::Remove { rule } => {
7537 let id = rule_named(library, rule)?;
7538 library.remove_rule(space, id, now, environment.rng())?;
7539 output::removed_rule(id, json, output)
7540 }
7541 RuleCommand::Move { rule, place } => {
7542 let id = rule_named(library, rule)?;
7543 let place = place_of(library, place)?.ok_or(CliError::WhereTo)?;
7544 library.move_rule(space, id, place, now, environment.rng())?;
7545 rule_changed("Moved", id, library, json, output)
7546 }
7547 }
7548}
7549
7550fn rule_changed(
7552 what: &str,
7553 id: EntityId,
7554 library: &Library,
7555 json: bool,
7556 output: &mut dyn Write,
7557) -> Result<(), CliError> {
7558 let space = library.default_space();
7559 let rules = library.rules(space)?;
7560 let policies = library.policies(space)?;
7561 let name_of = |entity| library.name(space, entity).ok().flatten();
7562 output::rule_changed(what, id, &rules, &policies, &name_of, json, output)
7563}
7564
7565fn policy_changed(
7567 what: &str,
7568 id: EntityId,
7569 library: &Library,
7570 json: bool,
7571 output: &mut dyn Write,
7572) -> Result<(), CliError> {
7573 let policies = library.policies(library.default_space())?;
7574 match policies.iter().find(|policy| policy.id == id) {
7575 Some(policy) => output::policy_changed(what, policy, json, output),
7576 None => Ok(()),
7577 }
7578}
7579
7580fn rule_named(library: &Library, text: &str) -> Result<EntityId, CliError> {
7583 let rules = library.rules(library.default_space())?;
7584 if let Some(rule) = text
7586 .parse::<usize>()
7587 .ok()
7588 .and_then(|number| number.checked_sub(1))
7589 .and_then(|index| rules.get(index))
7590 {
7591 return Ok(rule.id);
7592 }
7593 let lowered = text.to_lowercase();
7594 let found: Vec<EntityId> = rules
7595 .iter()
7596 .map(|rule| rule.id)
7597 .filter(|id| {
7598 let id = id.to_string();
7599 id == lowered || (lowered.len() >= 6 && id.starts_with(&lowered))
7600 })
7601 .collect();
7602 match found.as_slice() {
7603 [one] => Ok(*one),
7604 _ => Err(CliError::NoRule(text.to_owned())),
7605 }
7606}
7607
7608fn place_of(library: &Library, place: &PlaceArgs) -> Result<Option<Place>, CliError> {
7610 Ok(if place.first {
7611 Some(Place::First)
7612 } else if place.last {
7613 Some(Place::Last)
7614 } else if let Some(rule) = &place.before {
7615 Some(Place::Before(rule_named(library, rule)?))
7616 } else if let Some(rule) = &place.after {
7617 Some(Place::After(rule_named(library, rule)?))
7618 } else {
7619 None
7620 })
7621}
7622
7623fn why(
7625 library: &Library,
7626 entity: EntityId,
7627 json: bool,
7628 output: &mut dyn Write,
7629) -> Result<(), CliError> {
7630 let space = library.default_space();
7631 let choice = library.policy_of(space, entity)?;
7632 let policies = library.policies(space)?;
7633 let rules = library.rules(space)?;
7634 let name_of = |entity| library.name(space, entity).ok().flatten();
7635 output::why(&choice, &policies, &rules, &name_of, json, output)
7636}
7637
7638fn parse_size(text: &str) -> Result<u64, String> {
7641 let text = text.trim();
7642 let digits = text
7643 .find(|c: char| !c.is_ascii_digit())
7644 .unwrap_or(text.len());
7645 let (number, unit) = text.split_at(digits);
7646 let number: u64 = number
7647 .parse()
7648 .map_err(|_| format!("{text} is not a size, such as 500MB or 2GiB"))?;
7649 let unit = unit.trim().to_lowercase();
7650 let size: u64 = match unit.as_str() {
7651 "" | "b" => 1,
7652 "kb" => 1_000,
7653 "mb" => 1_000_000,
7654 "gb" => 1_000_000_000,
7655 "tb" => 1_000_000_000_000,
7656 "kib" => 1 << 10,
7657 "mib" => 1 << 20,
7658 "gib" => 1 << 30,
7659 "tib" => 1 << 40,
7660 _ => {
7661 return Err(format!(
7662 "{unit} is not a unit of size: B, kB, MB, GB, TB, KiB, MiB, GiB or TiB"
7663 ));
7664 }
7665 };
7666 number
7667 .checked_mul(size)
7668 .ok_or_else(|| format!("{text} is too large"))
7669}
7670
7671fn gather(
7677 path: &Path,
7678 (given, own): (bool, &Path),
7679 files: &mut Vec<PathBuf>,
7680 found: &mut output::FilesAdded,
7681) {
7682 let mut fail = |reason: String| found.failed.push((path.to_owned(), reason));
7683 let metadata = if given {
7684 std::fs::metadata(path)
7685 } else {
7686 std::fs::symlink_metadata(path)
7687 };
7688 let metadata = match metadata {
7689 Ok(metadata) => metadata,
7690 Err(error) => return fail(error.to_string()),
7691 };
7692 let is_own = || std::fs::canonicalize(path).is_ok_and(|resolved| resolved.starts_with(own));
7693 if given && (metadata.is_file() || metadata.is_dir()) && is_own() {
7694 return fail("the library's own folder holds it".to_owned());
7695 }
7696 if metadata.is_file() {
7697 files.push(path.to_owned());
7698 } else if metadata.is_dir() {
7699 if !given && is_own() {
7700 found.left_out += 1;
7701 return;
7702 }
7703 let entries = match std::fs::read_dir(path) {
7704 Ok(entries) => entries,
7705 Err(error) => return fail(error.to_string()),
7706 };
7707 let mut inside = Vec::new();
7708 for entry in entries {
7709 match entry {
7710 Ok(entry) => inside.push(entry.path()),
7711 Err(error) => fail(error.to_string()),
7713 }
7714 }
7715 inside.sort();
7716 for entry in inside {
7717 let hidden = entry
7718 .file_name()
7719 .is_some_and(|name| name.to_string_lossy().starts_with('.'));
7720 if hidden {
7721 found.left_out += 1;
7722 } else {
7723 gather(&entry, (false, own), files, found);
7724 }
7725 }
7726 } else if given {
7727 fail("neither a file nor a folder".to_owned());
7728 } else {
7729 found.left_out += 1;
7731 }
7732}
7733
7734fn secret_command<E: Environment>(
7736 library: &mut Library,
7737 command: &SecretCommand,
7738 json: bool,
7739 environment: &mut E,
7740 timings: &mut Timings,
7741 output: &mut dyn Write,
7742) -> Result<(), CliError> {
7743 let (SecretCommand::Set { entity, field, .. }
7744 | SecretCommand::Show { entity, field }
7745 | SecretCommand::History { entity, field }
7746 | SecretCommand::Clear { entity, field }
7747 | SecretCommand::Purge { entity, field, .. }) = command
7748 else {
7749 return entityless_secret_command(library, command, json, environment, timings, output);
7750 };
7751 let (space, id) = library.locate_or_deleted(entity)?;
7752 library.choose_space(Some(space))?;
7754 let day = dating(environment, environment.now(), None).day;
7755 let view = library
7756 .entity(space, id, day)?
7757 .ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
7758 let types = library.types(space)?;
7759 let field = types::field_named(field, &types, &view.types)?;
7760 if !is_secret(library, space, &field) {
7761 return Err(CliError::NotSecret(field));
7762 }
7763 let generated = generated_secret(command, &field, environment)?;
7765 let set = matches!(command, SecretCommand::Set { .. });
7766 unlock_secrets(library, set, environment, timings)?;
7767 let no_value = || CliError::NoSecretValue {
7768 entity: entity.clone(),
7769 field: field.clone(),
7770 };
7771 let done = match command {
7772 SecretCommand::Set { .. } => set_secret(
7773 library,
7774 (id, &field, &types),
7775 generated,
7776 environment,
7777 timings,
7778 ),
7779 SecretCommand::Clear { .. } => edit_now(
7780 library,
7781 id,
7782 Edit::Set(field.clone(), Vec::new()),
7783 environment,
7784 ),
7785 SecretCommand::Purge { yes, .. } => (|| {
7786 let asked = Instant::now();
7787 let text = environment.passphrase(&format!("The value of {field} to purge: "))?;
7788 add(&mut timings.waiting, asked.elapsed());
7789 if text.is_empty() {
7790 return Err(CliError::EmptyValue);
7791 }
7792 let value = types::value(&text, &field, &types, library, space)?;
7793 let purged = purge_values(library, (id, &field, Some(&value)), *yes, environment)?;
7794 let name_of = |entity| library.name(space, entity).ok().flatten();
7795 let elsewhere = space_names(library, &purged.elsewhere);
7796 output::purge(&purged, (&field, &name_of), &elsewhere, *yes, json, output)
7797 })(),
7798 SecretCommand::Show { .. } => (|| {
7799 let view = library
7800 .entity(space, id, day)?
7801 .ok_or_else(|| NodeError::NoEntity(entity.clone()))?;
7802 let values = view.values(&field);
7803 if values.is_empty() {
7804 return Err(no_value());
7805 }
7806 let name_of = |entity| library.name(space, entity).ok().flatten();
7807 output::secret_values(view.id, &field, values, &name_of, json, output)
7808 })(),
7809 SecretCommand::History { .. } => {
7810 let history = (entity.as_str(), Some(field.as_str()));
7811 history_command(library, history, json, environment, output).map_err(
7812 |error| match error {
7813 CliError::SecretHistory(_) => no_value(),
7814 other => other,
7815 },
7816 )
7817 }
7818 SecretCommand::Copy { .. }
7819 | SecretCommand::Generate { .. }
7820 | SecretCommand::Code { .. }
7821 | SecretCommand::Ask { .. }
7822 | SecretCommand::Give { .. }
7823 | SecretCommand::FromCopy
7824 | SecretCommand::Save { .. } => {
7825 unreachable!("answered above")
7826 }
7827 };
7828 library.lock_secrets();
7829 done?;
7830 match command {
7831 SecretCommand::Set { .. } | SecretCommand::Clear { .. } => {
7832 let day = dating(environment, environment.now(), None).day;
7833 show(library, space, id, When::on(day), json, output)
7834 }
7835 SecretCommand::Purge { yes: false, .. } => Err(CliError::Unconfirmed),
7836 _ => Ok(()),
7837 }
7838}
7839
7840fn entityless_secret_command<E: Environment>(
7843 library: &mut Library,
7844 command: &SecretCommand,
7845 json: bool,
7846 environment: &mut E,
7847 timings: &mut Timings,
7848 output: &mut dyn Write,
7849) -> Result<(), CliError> {
7850 match command {
7851 SecretCommand::Code { entity, field } => {
7852 let code = (entity.as_str(), field.as_deref());
7853 code_command(library, code, json, environment, timings, output)
7854 }
7855 SecretCommand::Ask { from } => match shared_space(library) {
7856 Some(space) => {
7857 let asking = (space, from.as_str());
7858 ask_space_command(library, asking, json, environment, timings, output)
7859 }
7860 None => ask_command(library, from, json, environment, timings, output),
7861 },
7862 SecretCommand::Give { device } => match shared_space(library) {
7863 Some(space) => {
7864 let giving = (space, device.as_str());
7865 give_space_command(library, giving, json, environment, timings, output)
7866 }
7867 None => give_command(library, device, json, environment, timings, output),
7868 },
7869 SecretCommand::FromCopy => {
7870 from_copy_secrets_command(library, json, environment, timings, output)
7871 }
7872 SecretCommand::Save { file, path } => {
7873 let save = (file.as_str(), path.as_deref());
7874 let saved = secret_save_command(library, save, json, environment, timings, output);
7875 library.lock_secrets();
7876 saved
7877 }
7878 _ => unreachable!("run_command runs nib secret generate and copy"),
7881 }
7882}
7883
7884fn secret_save_command<E: Environment>(
7888 library: &mut Library,
7889 (file, place): (&str, Option<&Path>),
7890 json: bool,
7891 environment: &mut E,
7892 timings: &mut Timings,
7893 output: &mut dyn Write,
7894) -> Result<(), CliError> {
7895 let (space, file) = library.locate(file)?;
7896 library.choose_space(Some(space))?;
7898 let place = match place {
7899 Some(place) => absolute(place, environment)?,
7900 None => current_dir(environment)?,
7901 };
7902 unlock_secrets(library, false, environment, timings)?;
7903 let saved = library.save_secret_file(space, file, &place)?;
7904 let name = library.name(space, file)?;
7905 output::secret_saved((file, name.as_deref()), &saved, json, output)
7906}
7907
7908fn shared_space(library: &Library) -> Option<SpaceId> {
7911 library.chosen_space().filter(|&space| {
7912 space != library.personal_space()
7913 && library
7914 .members(space)
7915 .is_ok_and(|members| members.iter().any(|member| !member.this_user))
7916 })
7917}
7918
7919fn member_device(
7923 library: &Library,
7924 space: SpaceId,
7925 name: &str,
7926 wanted: impl Fn(&nibkeep_node::MemberReplica) -> bool,
7927) -> Result<(String, nibkeep_node::MemberReplica), CliError> {
7928 let mut found = Vec::new();
7929 for member in library.members(space)? {
7930 for replica in member.replicas {
7931 let id = replica.record.to_string();
7932 let named = replica.device.as_deref() == Some(name)
7933 || id == name
7934 || (name.len() >= 8 && id.starts_with(name));
7935 if named && !replica.this && !replica.revoked && wanted(&replica) {
7936 found.push((member.name.clone().unwrap_or_default(), replica));
7937 }
7938 }
7939 }
7940 match found.len() {
7941 1 => Ok(found.remove(0)),
7942 0 => Err(NodeError::WhichDevice(format!(
7943 "no other member's device in the space that is {name} can do that; nib space \
7944 members shows them"
7945 ))
7946 .into()),
7947 _ => Err(NodeError::WhichDevice(format!(
7948 "{name} names several devices in the space; give the ID of the one you mean, as \
7949 nib space show --json shows it"
7950 ))
7951 .into()),
7952 }
7953}
7954
7955fn ask_space_command<E: Environment>(
7958 library: &mut Library,
7959 (space, from): (SpaceId, &str),
7960 json: bool,
7961 environment: &mut E,
7962 timings: &mut Timings,
7963 output: &mut dyn Write,
7964) -> Result<(), CliError> {
7965 let (member, device) = member_device(library, space, from, |replica| replica.holds_secrets)?;
7966 if library.secrets_protection()?.is_none() {
7967 return Err(NodeError::SetUpSecretsFirst.into());
7968 }
7969 unlock_secrets(library, false, environment, timings)?;
7970 let now = environment.now();
7971 let asked = library.ask_for_space_secrets(space, device.record, now, environment.rng());
7972 library.lock_secrets();
7973 asked?;
7974 let name = library.space_name(space)?.unwrap_or_default();
7975 output::asked_for_space_secrets(&name, (&member, &device), json, output)
7976}
7977
7978fn give_space_command<E: Environment>(
7981 library: &mut Library,
7982 (space, to): (SpaceId, &str),
7983 json: bool,
7984 environment: &mut E,
7985 timings: &mut Timings,
7986 output: &mut dyn Write,
7987) -> Result<(), CliError> {
7988 let (member, device) = member_device(library, space, to, |replica| replica.asks_for_secrets)?;
7989 unlock_secrets(library, false, environment, timings)?;
7990 let now = environment.now();
7991 let given = library.give_space_secrets(space, device.record, now, environment.rng());
7992 library.lock_secrets();
7993 let keys = given?;
7994 let name = library.space_name(space)?.unwrap_or_default();
7995 output::gave_space_secrets(&name, (&member, &device), keys, json, output)
7996}
7997
7998fn ask_command<E: Environment>(
8003 library: &mut Library,
8004 from: &str,
8005 json: bool,
8006 environment: &mut E,
8007 timings: &mut Timings,
8008 output: &mut dyn Write,
8009) -> Result<(), CliError> {
8010 let Some(from) = library
8012 .replicas_named(from)?
8013 .into_iter()
8014 .find(|replica| replica.holds_secrets && !replica.this && !replica.revoked)
8015 else {
8016 return Err(NodeError::WhichDevice(
8017 "that device does not hold the secrets, or has not said so yet: unlock its secrets \
8018 once"
8019 .to_owned(),
8020 )
8021 .into());
8022 };
8023 let now = environment.now();
8024 if library.secrets_state()? == SecretsState::Asked {
8025 library.ask_secrets_from(from.id, now, environment.rng())?;
8026 } else {
8027 library.check_may_ask(from.id)?;
8029 let passphrase = ask_twice(
8030 environment,
8031 timings,
8032 (
8033 "A passphrase for the secrets on this device, not the library's: ",
8034 "The passphrase again: ",
8035 ),
8036 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
8037 )?;
8038 let protection = NewProtection::Passphrase(&passphrase, environment.passphrase_params());
8039 let now = environment.now();
8040 let asked = library.ask_for_secrets(from.id, &protection, now, environment.rng());
8041 library.lock_secrets();
8042 asked?;
8043 }
8044 let own = library.replicas()?.into_iter().find(|replica| replica.this);
8045 output::asked_for_secrets(own.as_ref(), &from, json, output)
8046}
8047
8048fn give_command<E: Environment>(
8051 library: &mut Library,
8052 device: &str,
8053 json: bool,
8054 environment: &mut E,
8055 timings: &mut Timings,
8056 output: &mut dyn Write,
8057) -> Result<(), CliError> {
8058 let named: Vec<Replica> = library
8060 .replicas_named(device)?
8061 .into_iter()
8062 .filter(|replica| !replica.this && !replica.revoked)
8063 .collect();
8064 if named.is_empty() {
8065 return Err(NodeError::WhichDevice(
8066 "that names no other device of yours that is not revoked".to_owned(),
8067 )
8068 .into());
8069 }
8070 let own = library.replicas()?.into_iter().find(|replica| replica.this);
8071 let own = own.map(|replica| replica.id);
8072 let asking: Vec<Replica> = named
8073 .iter()
8074 .filter(|replica| replica.asks_for_secrets && replica.secrets_from == own)
8075 .cloned()
8076 .collect();
8077 if asking.is_empty() {
8078 return Err(if named.iter().any(|replica| replica.asks_for_secrets) {
8079 NodeError::WhichDevice("that device asks another of yours for the secrets".to_owned())
8080 } else {
8081 NodeError::NotAsked
8082 }
8083 .into());
8084 }
8085 unlock_secrets(library, false, environment, timings)?;
8086 let mut given = Vec::new();
8087 let mut failed = None;
8088 for replica in asking {
8089 let now = environment.now();
8090 match library.give_secrets(replica.id, now, environment.rng()) {
8091 Ok(keys) => given.push((replica, keys)),
8092 Err(error) => {
8093 failed = Some(error);
8094 break;
8095 }
8096 }
8097 }
8098 library.lock_secrets();
8099 output::gave_secrets(&given, json, output)?;
8101 match failed {
8102 Some(error) => Err(error.into()),
8103 None => Ok(()),
8104 }
8105}
8106
8107fn generated_secret<E: Environment>(
8111 command: &SecretCommand,
8112 field: &FieldName,
8113 environment: &mut E,
8114) -> Result<Option<zeroize::Zeroizing<String>>, CliError> {
8115 let SecretCommand::Set {
8116 generate, recipe, ..
8117 } = command
8118 else {
8119 return Ok(None);
8120 };
8121 if !generate {
8122 return if recipe.given() {
8123 Err(CliError::RecipeWithoutGenerate)
8124 } else {
8125 Ok(None)
8126 };
8127 }
8128 if *field == nibkeep_std::ONE_TIME_CODE {
8129 return Err(CliError::GeneratedOneTimeCode(field.clone()));
8130 }
8131 Ok(Some(nibkeep_passwords::generate(
8132 &recipe.recipe(),
8133 environment.rng(),
8134 )?))
8135}
8136
8137fn set_secret<E: Environment>(
8140 library: &mut Library,
8141 (id, field, types): (EntityId, &FieldName, &nibkeep_model::Types),
8142 generated: Option<zeroize::Zeroizing<String>>,
8143 environment: &mut E,
8144 timings: &mut Timings,
8145) -> Result<(), CliError> {
8146 let text = if let Some(generated) = generated {
8147 generated
8148 } else {
8149 ask_twice(
8150 environment,
8151 timings,
8152 (&format!("{field}: "), &format!("{field} again: ")),
8153 (|| CliError::EmptyValue, || CliError::ValuesDiffer),
8154 )?
8155 };
8156 if *field == nibkeep_std::ONE_TIME_CODE {
8158 nibkeep_passwords::OneTimeCode::check(&text)?;
8159 }
8160 let space = library.default_space();
8161 let value = types::value(&text, field, types, library, space)?;
8162 edit_now(
8163 library,
8164 id,
8165 Edit::Set(field.clone(), vec![value]),
8166 environment,
8167 )
8168}
8169
8170fn code_command<E: Environment>(
8173 library: &mut Library,
8174 (entity, field): (&str, Option<&str>),
8175 json: bool,
8176 environment: &mut E,
8177 timings: &mut Timings,
8178 output: &mut dyn Write,
8179) -> Result<(), CliError> {
8180 let default = nibkeep_std::ONE_TIME_CODE;
8181 let field = field.unwrap_or(default.as_str());
8182 let read = read_secret(library, entity, field, environment, timings)?;
8183 let generator = nibkeep_passwords::OneTimeCode::parse(&read.values[0])?;
8184 output::one_time_code(&generator, environment.now() / 1000, json, output)
8185}
8186
8187struct SecretRead {
8189 entity: EntityId,
8191 name: String,
8193 field: FieldName,
8195 values: Vec<zeroize::Zeroizing<String>>,
8197}
8198
8199fn read_secret<E: Environment>(
8202 library: &mut Library,
8203 entity: &str,
8204 field: &str,
8205 environment: &mut E,
8206 timings: &mut Timings,
8207) -> Result<SecretRead, CliError> {
8208 let (space, id) = library.locate_or_deleted(entity)?;
8209 library.choose_space(Some(space))?;
8211 let day = dating(environment, environment.now(), None).day;
8212 let view = library
8213 .entity(space, id, day)?
8214 .ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
8215 let types = library.types(space)?;
8216 let field = types::field_named(field, &types, &view.types)?;
8217 if !is_secret(library, space, &field) {
8218 return Err(CliError::NotSecret(field));
8219 }
8220 unlock_secrets(library, false, environment, timings)?;
8221 let read = library.entity(space, id, day);
8222 library.lock_secrets();
8223 let view = read?.ok_or_else(|| NodeError::NoEntity(entity.to_owned()))?;
8224 let name_of = |entity| library.name(space, entity).ok().flatten();
8225 let values: Vec<zeroize::Zeroizing<String>> = view
8226 .values(&field)
8227 .iter()
8228 .map(|shown| zeroize::Zeroizing::new(output::value_text(&shown.value, &name_of)))
8229 .collect();
8230 if values.is_empty() {
8231 return Err(CliError::NoSecretValue {
8232 entity: entity.to_owned(),
8233 field,
8234 });
8235 }
8236 Ok(SecretRead {
8237 entity: view.id,
8238 name: view.name.unwrap_or_else(|| entity.to_owned()),
8239 field,
8240 values,
8241 })
8242}
8243
8244fn copy_and_clear<E: Environment>(
8248 board: Box<dyn nibkeep_passwords::Board>,
8249 read: &SecretRead,
8250 clear_after: u64,
8251 json: bool,
8252 environment: &mut E,
8253 output: &mut dyn Write,
8254) -> Result<(), CliError> {
8255 environment.interruptible();
8256 let mut clipboard = nibkeep_passwords::Clipboard::new(board, environment.rng());
8257 clipboard.copy_secret(&read.values[0])?;
8258 let printed = if json {
8259 Ok(())
8260 } else {
8261 output::copied(
8262 &read.field,
8263 &read.name,
8264 read.values.len(),
8265 clear_after,
8266 output,
8267 )
8268 .and_then(|()| Ok(output.flush()?))
8269 };
8270 let interrupted = printed.is_ok() && environment.wait(Duration::from_secs(clear_after));
8271 let cleared = clipboard.clear_if_ours().or_else(|_| {
8273 std::thread::sleep(Duration::from_millis(200));
8274 clipboard.clear_if_ours()
8275 });
8276 printed?;
8277 output::copy_ended(
8278 (read.entity, &read.field, read.values.len()),
8279 (cleared?, interrupted),
8280 json,
8281 output,
8282 )
8283}
8284
8285fn generate_command<E: Environment>(
8287 recipe: &RecipeArgs,
8288 json: bool,
8289 environment: &mut E,
8290 output: &mut dyn Write,
8291) -> Result<(), CliError> {
8292 let recipe = recipe.recipe();
8293 let password = nibkeep_passwords::generate(&recipe, environment.rng())?;
8294 output::generated(&password, recipe.bits(), json, output)
8295}
8296
8297fn import_command<E: Environment>(
8300 library: &mut Library,
8301 (paths, from): (&[PathBuf], Option<&str>),
8302 json: bool,
8303 environment: &mut E,
8304 output: &mut dyn Write,
8305) -> Result<(), CliError> {
8306 if let [folder] = paths
8309 && ["manifest.json", "SHA256SUMS"]
8310 .iter()
8311 .any(|name| folder.join(name).is_file())
8312 {
8313 if from.is_some() {
8314 return Err(CliError::Import(
8315 "--from names the source of Google Takeout's photos; an export keeps where its files came from".to_owned(),
8316 ));
8317 }
8318 let space = library.default_space();
8319 let imported = library.import(space, folder, environment.now(), environment.rng())?;
8320 return output::imported(&imported, folder, json, output);
8321 }
8322 takeout_command(library, (paths, from), json, environment, output)
8323}
8324
8325fn protect_command<E: Environment>(
8328 library: &mut Library,
8329 (passphrase, secrets): (bool, bool),
8330 json: bool,
8331 environment: &mut E,
8332 timings: &mut Timings,
8333 output: &mut dyn Write,
8334) -> Result<(), CliError> {
8335 if !passphrase && !environment.keystore() {
8337 return Err(CliError::NoKeystoreToProtect);
8338 }
8339 if secrets {
8340 unlock_secrets(library, false, environment, timings)?;
8341 }
8342 let protected = (|| {
8343 let typed = if passphrase {
8344 let prompt = if secrets {
8345 "A new passphrase for the secrets, not the library's: "
8346 } else {
8347 "A new passphrase for the library: "
8348 };
8349 Some(ask_twice(
8350 environment,
8351 timings,
8352 (prompt, "The passphrase again: "),
8353 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
8354 )?)
8355 } else {
8356 None
8357 };
8358 let params = environment.passphrase_params();
8359 let protection = match &typed {
8360 Some(passphrase) => NewProtection::Passphrase(passphrase, params),
8361 None => NewProtection::Keystore {
8362 service: KEYSTORE_SERVICE,
8363 },
8364 };
8365 let protected = if secrets {
8366 library.protect_secrets(&protection, environment.rng())
8367 } else {
8368 library.protect(&protection, environment.rng())
8369 };
8370 protected.map_err(|error| match error {
8371 error @ NodeError::Keys(KeysError::Keystore(_)) => CliError::KeystoreToProtect(error),
8372 other => CliError::Node(other),
8373 })
8374 })();
8375 library.lock_secrets();
8376 protected?;
8377 output::protected(secrets, passphrase, json, output)
8378}
8379
8380fn edit_now<E: Environment>(
8383 library: &mut Library,
8384 entity: nibkeep_base::EntityId,
8385 edit: Edit,
8386 environment: &mut E,
8387) -> Result<(), CliError> {
8388 let space = library.default_space();
8389 let now = environment.now();
8390 let dating = dating(environment, now, None);
8391 library.edit_entity(space, entity, vec![edit], &dating, now, environment.rng())?;
8392 Ok(())
8393}
8394
8395fn is_secret(library: &Library, space: nibkeep_base::SpaceId, field: &FieldName) -> bool {
8397 library
8398 .secret_fields(space)
8399 .is_some_and(|secret| secret.contains(field))
8400}
8401
8402pub(crate) fn unlock_secrets<E: Environment>(
8408 library: &mut Library,
8409 set_up: bool,
8410 environment: &mut E,
8411 timings: &mut Timings,
8412) -> Result<(), CliError> {
8413 match library.secrets_protection()? {
8414 None if !set_up => return Err(CliError::NoSecrets),
8415 None => {
8416 let passphrase = ask_twice(
8417 environment,
8418 timings,
8419 (
8420 "The library's first secret. A passphrase for its secrets, not the library's: ",
8421 "The passphrase again: ",
8422 ),
8423 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
8424 )?;
8425 let protection =
8426 NewProtection::Passphrase(&passphrase, environment.passphrase_params());
8427 let now = environment.now();
8428 return Ok(library.set_up_secrets(&protection, now, environment.rng())?);
8429 }
8430 Some(Protection::Passphrase { .. }) => {
8431 let asked = Instant::now();
8432 let passphrase = environment.passphrase("Passphrase for secrets: ")?;
8433 add(&mut timings.waiting, asked.elapsed());
8434 library.unlock_secrets(&Unlocker::Passphrase(&passphrase))?;
8435 }
8436 Some(Protection::Keystore { .. }) => {
8437 if !environment.keystore() {
8438 return Err(CliError::NoKeystore);
8439 }
8440 library.unlock_secrets(&Unlocker::Keystore)?;
8441 }
8442 }
8443 let now = environment.now();
8444 let settled = library.settle_secrets(now, environment.rng());
8445 let personal = library.personal_space();
8448 if settled.is_err() || !library.secrets_unlocked(personal) {
8449 library.lock_secrets();
8450 }
8451 settled?;
8452 if library.secrets_unlocked(personal) {
8453 Ok(())
8454 } else {
8455 Err(NodeError::SecretsAsked.into())
8456 }
8457}
8458
8459type Mistyped = (fn() -> CliError, fn() -> CliError);
8461
8462fn ask_once<E: Environment>(
8464 environment: &mut E,
8465 timings: &mut Timings,
8466 prompt: &str,
8467) -> Result<zeroize::Zeroizing<String>, CliError> {
8468 let asked = Instant::now();
8469 let typed = environment.passphrase(prompt);
8470 add(&mut timings.waiting, asked.elapsed());
8471 Ok(typed?)
8472}
8473
8474fn ask_twice<E: Environment>(
8478 environment: &mut E,
8479 timings: &mut Timings,
8480 (prompt, again): (&str, &str),
8481 (empty, differ): Mistyped,
8482) -> Result<zeroize::Zeroizing<String>, CliError> {
8483 let asked = Instant::now();
8484 let first = environment.passphrase(prompt);
8485 let second = match &first {
8486 Ok(first) if !first.is_empty() => Some(environment.passphrase(again)),
8487 _ => None,
8488 };
8489 add(&mut timings.waiting, asked.elapsed());
8490 let first = first?;
8491 let Some(second) = second else {
8492 return Err(empty());
8493 };
8494 if *first != *second? {
8495 return Err(differ());
8496 }
8497 Ok(first)
8498}
8499
8500fn type_command<E: Environment>(
8502 library: &mut Library,
8503 command: &TypeCommand,
8504 json: bool,
8505 environment: &mut E,
8506 output: &mut dyn Write,
8507) -> Result<(), CliError> {
8508 let space = library.default_space();
8509 let (name, types) = match command {
8510 TypeCommand::Add { name, fields } => {
8511 let name: TypeName = types::name(name)?;
8512 let fields = fields
8513 .iter()
8514 .map(|field| types::field(field))
8515 .collect::<Result<Vec<_>, _>>()?;
8516 let known = library.types(space)?;
8518 let type_known = types::standard_type_known(&known, &name);
8519 types::check_standard(name.as_str(), "type", type_known)?;
8520 for (field, definition) in &fields {
8521 let field_known = types::standard_field_known(&known, field, definition);
8522 types::check_standard(field.as_str(), "field", field_known)?;
8523 if let Some(reverse) = definition.reverse() {
8524 let reverse_known = types::standard_reverse_known(&known, reverse);
8525 types::check_standard(reverse.as_str(), "field", reverse_known)?;
8526 }
8527 }
8528 let definition = library.types(space)?.extend(name.clone(), fields);
8529 let now = environment.now();
8530 let types = library.define_type(space, &definition, now, environment.rng())?;
8531 (name, types)
8532 }
8533 TypeCommand::Show { name } => (types::name(name)?, library.types(space)?),
8534 TypeCommand::List => {
8535 let types = library.types(space)?;
8536 return output::type_list(&types, library.languages(), json, output);
8537 }
8538 };
8539 let definition = types.get(&name).ok_or(CliError::NoType(name))?;
8540 let secret = library.secret_fields(space).cloned().unwrap_or_default();
8542 output::type_definition(definition, (library.languages(), &secret), json, output)
8543}
8544
8545fn space_command<E: Environment>(
8548 library: &mut Library,
8549 command: &SpaceCommand,
8550 cli: &Cli,
8551 environment: &mut E,
8552 output: &mut dyn Write,
8553) -> Result<(), CliError> {
8554 let json = cli.json;
8555 match command {
8556 SpaceCommand::New { .. }
8557 | SpaceCommand::Take { .. }
8558 | SpaceCommand::Drop { .. }
8559 | SpaceCommand::Allow { .. } => taking_command(library, command, json, environment, output),
8560 SpaceCommand::AddGroup { .. }
8561 | SpaceCommand::RemoveGroup { .. }
8562 | SpaceCommand::Agree { .. }
8563 | SpaceCommand::Withdraw { .. } => group_command(library, command, json, environment, output),
8564 SpaceCommand::List => {
8565 let status = library.status()?;
8566 let known = library.known_spaces()?;
8567 let requests = library.space_requests()?;
8568 output::spaces(
8569 (&status.spaces, &known, &requests),
8570 library.personal_space(),
8571 json,
8572 output,
8573 )
8574 }
8575 SpaceCommand::Show { space } => {
8576 show_space_command(library, space, json, environment, output)
8577 }
8578 SpaceCommand::Rename { space, name } => {
8579 let space = library.find_space(space)?;
8580 let now = environment.now();
8581 library.rename_space(space, name, now, environment.rng())?;
8582 output::space_renamed(space, name, json, output)
8583 }
8584 SpaceCommand::Invite {
8585 space,
8586 role,
8587 person,
8588 yes,
8589 ..
8590 } => {
8591 let space = library.find_space(space)?;
8592 let person = person
8593 .as_deref()
8594 .map(|person| library.find_person(space, person))
8595 .transpose()?;
8596 let invitation = nibkeep_node::Invitation {
8597 space,
8598 role: role.role(),
8599 person,
8600 };
8601 invite_command(library, (&invitation, *yes), cli, environment, output)
8602 }
8603 SpaceCommand::Join { code, yes, on } => {
8604 let also = devices_named(library, on)?;
8605 join_space_command(library, (code, *yes, &also), cli, environment, output)
8606 }
8607 SpaceCommand::AiAgents { space, switch } => {
8608 let space = library.find_space(space)?;
8609 if let Some(switch) = switch {
8610 let now = environment.now();
8611 library.allow_ai_agents(space, *switch == Switch::On, now, environment.rng())?;
8612 }
8613 let allowed = library.ai_agents_allowed(space)?;
8614 output::ai_agents_allowed(allowed, json, output)
8615 }
8616 SpaceCommand::Link {
8617 space,
8618 member,
8619 person,
8620 } => link_command(
8621 library,
8622 (space, member, person.as_deref()),
8623 json,
8624 environment,
8625 output,
8626 ),
8627 SpaceCommand::Accept { space, member, yes } => {
8628 accept_in_space_command(library, (space, member, *yes), json, environment, output)
8629 }
8630 SpaceCommand::Leave { space, yes } => {
8631 let space = library.find_space(space)?;
8632 leave_command(library, (space, *yes), json, environment, output)
8633 }
8634 SpaceCommand::Remove { space, member, yes } => {
8635 remove_command(library, (space, member, *yes), json, environment, output)
8636 }
8637 SpaceCommand::LetIn { .. }
8638 | SpaceCommand::MakeDirect { .. }
8639 | SpaceCommand::Confirm { .. } => direct_command(library, command, json, environment, output),
8640 SpaceCommand::Claim { .. } | SpaceCommand::Reject { .. } => {
8641 claim_command(library, command, json, environment, output)
8642 }
8643 SpaceCommand::Role {
8644 space,
8645 member,
8646 role,
8647 } => role_command(library, (space, member, *role), json, environment, output),
8648 }
8649}
8650
8651fn taking_command<E: Environment>(
8655 library: &mut Library,
8656 command: &SpaceCommand,
8657 json: bool,
8658 environment: &mut E,
8659 output: &mut dyn Write,
8660) -> Result<(), CliError> {
8661 match command {
8662 SpaceCommand::New { name, group, on } => {
8663 let also = devices_named(library, on)?;
8664 let now = environment.now();
8665 let space = if *group {
8666 library.create_group_on(name, &also, now, environment.rng())?
8667 } else {
8668 library.create_space_on(name, &also, now, environment.rng())?
8669 };
8670 output::space_made(space, name, json, output)
8671 }
8672 SpaceCommand::Take { wanted } => {
8673 let space = library.find_known_space(wanted)?;
8674 let now = environment.now();
8675 let taking = library.take_space(space, now, environment.rng())?;
8676 let name = library
8677 .known_spaces()?
8678 .into_iter()
8679 .find(|known| known.space == space)
8680 .and_then(|known| known.name)
8681 .unwrap_or_else(|| space.to_string());
8682 let this = library
8683 .replicas()?
8684 .into_iter()
8685 .find(|replica| replica.this)
8686 .ok_or(NodeError::NotListed)?;
8687 let named = (this.device_name.as_deref(), this.id);
8688 output::space_taken((space, &name), taking, named, json, output)
8689 }
8690 SpaceCommand::Drop { wanted } => {
8691 let space = library.find_space(wanted)?;
8692 let name = library
8693 .space_name(space)?
8694 .unwrap_or_else(|| space.to_string());
8695 let now = environment.now();
8696 let dropping = library.drop_space(space, now, environment.rng())?;
8697 output::space_dropping(&dropping, &name, json, output)
8698 }
8699 SpaceCommand::Allow { space, device } => {
8700 let space = library.find_space(space)?;
8701 let replicas = devices_named(library, std::slice::from_ref(device))?;
8702 let request = library
8703 .space_requests()?
8704 .into_iter()
8705 .find(|request| request.space == space && replicas.contains(&request.replica))
8706 .ok_or(NodeError::NoRequest)?;
8707 let now = environment.now();
8708 library.allow_space(space, request.replica, now, environment.rng())?;
8709 output::space_allowed(&request, json, output)
8710 }
8711 _ => unreachable!("only nib space new, take, drop and allow come here"),
8712 }
8713}
8714
8715fn role_command<E: Environment>(
8717 library: &mut Library,
8718 (space, member, role): (&str, &str, RoleArg),
8719 json: bool,
8720 environment: &mut E,
8721 output: &mut dyn Write,
8722) -> Result<(), CliError> {
8723 let space = library.find_space(space)?;
8724 let member = library.find_member(space, member)?;
8725 let now = environment.now();
8726 library.give_role(space, member, role.role(), now, environment.rng())?;
8727 let name = library
8728 .members(space)?
8729 .into_iter()
8730 .find(|found| found.record == member)
8731 .and_then(|found| found.name);
8732 output::role_given(name.as_deref(), role.role(), json, output)
8733}
8734
8735fn accept_in_space_command<E: Environment>(
8738 library: &mut Library,
8739 (space, member, confirmed): (&str, &str, bool),
8740 json: bool,
8741 environment: &mut E,
8742 output: &mut dyn Write,
8743) -> Result<(), CliError> {
8744 let space = library.find_space(space)?;
8745 let chosen = library.find_member(space, member)?;
8747 let members = library.members(space)?;
8748 let user = members
8749 .iter()
8750 .find(|found| found.record == chosen)
8751 .and_then(|found| found.user);
8752 let records: Vec<_> = members
8753 .iter()
8754 .filter(|found| found.record == chosen || (user.is_some() && found.user == user))
8755 .map(|found| found.record)
8756 .collect();
8757 let changes: Vec<_> = library
8758 .set_aside_in(space)?
8759 .into_iter()
8760 .filter(|aside| {
8761 aside.acceptable && aside.member.is_some_and(|member| records.contains(&member))
8762 })
8763 .map(|aside| aside.change)
8764 .collect();
8765 let accepted = if confirmed {
8766 let now = environment.now();
8767 library.accept_set_aside_in(space, &changes, now, environment.rng())?
8768 } else {
8769 library.check_admin(space, "accept changes that were set aside")?;
8770 changes.len()
8771 };
8772 output::accepted(accepted, confirmed, json, output)?;
8773 if confirmed || accepted == 0 {
8774 Ok(())
8775 } else {
8776 Err(CliError::UnconfirmedAccept)
8777 }
8778}
8779
8780fn leave_command<E: Environment>(
8783 library: &mut Library,
8784 (space, confirmed): (nibkeep_base::SpaceId, bool),
8785 json: bool,
8786 environment: &mut E,
8787 output: &mut dyn Write,
8788) -> Result<(), CliError> {
8789 let name = library
8790 .space_name(space)?
8791 .unwrap_or_else(|| space.to_string());
8792 if !confirmed {
8793 let closes = library.check_leave(space)?;
8794 output::leaving(&name, closes, json, output)?;
8795 return Err(CliError::UnconfirmedLeave);
8796 }
8797 let now = environment.now();
8798 let closed = library.leave(space, now, environment.rng())?;
8799 output::left(&name, closed, json, output)
8800}
8801
8802fn space_display_name(library: &Library, space: nibkeep_base::SpaceId) -> Result<String, CliError> {
8804 Ok(library
8805 .space_name(space)?
8806 .unwrap_or_else(|| space.to_string()))
8807}
8808
8809fn keep_out_command<E: Environment>(
8812 library: &mut Library,
8813 (space, member, confirmed): (nibkeep_base::SpaceId, &str, bool),
8814 json: bool,
8815 environment: &mut E,
8816 output: &mut dyn Write,
8817) -> Result<(), CliError> {
8818 let found = library.find_group_member(space, member)?;
8819 let name = space_display_name(library, space)?;
8820 if !confirmed {
8821 library.check_admin(space, "keep members out")?;
8822 output::removing((&name, Some(member)), json, output)?;
8823 return Err(CliError::UnconfirmedRemove);
8824 }
8825 let now = environment.now();
8826 library.keep_out(space, found, now, environment.rng())?;
8827 output::removed((&name, Some(member)), json, output)
8828}
8829
8830fn remove_command<E: Environment>(
8833 library: &mut Library,
8834 (space, member, confirmed): (&str, &str, bool),
8835 json: bool,
8836 environment: &mut E,
8837 output: &mut dyn Write,
8838) -> Result<(), CliError> {
8839 let space = library.find_space(space)?;
8840 let record = match library.find_member(space, member) {
8841 Ok(record) => record,
8842 Err(NodeError::NoMember(_)) => {
8844 return keep_out_command(
8845 library,
8846 (space, member, confirmed),
8847 json,
8848 environment,
8849 output,
8850 );
8851 }
8852 Err(error) => return Err(error.into()),
8853 };
8854 if library.check_remove(space, record)? {
8856 return leave_command(library, (space, confirmed), json, environment, output);
8857 }
8858 let space_name = space_display_name(library, space)?;
8859 let name = library
8860 .members(space)?
8861 .into_iter()
8862 .find(|found| found.record == record)
8863 .and_then(|found| found.name);
8864 if !confirmed {
8865 output::removing((&space_name, name.as_deref()), json, output)?;
8866 return Err(CliError::UnconfirmedRemove);
8867 }
8868 let now = environment.now();
8869 library.remove_member(space, record, now, environment.rng())?;
8870 output::removed((&space_name, name.as_deref()), json, output)
8871}
8872
8873fn show_space_command<E: Environment>(
8877 library: &Library,
8878 space: &str,
8879 json: bool,
8880 environment: &E,
8881 output: &mut dyn Write,
8882) -> Result<(), CliError> {
8883 let space = library.find_space(space)?;
8884 let members = library.members(space)?;
8885 let mut names = std::collections::BTreeMap::new();
8886 for member in &members {
8887 let link = member.person;
8888 for person in [link.holds, link.by_admin, link.by_member]
8889 .into_iter()
8890 .flatten()
8891 {
8892 if let Some(name) = library.name(space, person)? {
8893 names.insert(person, name);
8894 }
8895 }
8896 }
8897 let requests = if library.is_group(space)? {
8898 Some(library.join_requests(space)?)
8899 } else {
8900 None
8901 };
8902 let shown = output::SpaceShown {
8903 members: &members,
8904 names: &names,
8905 groups: &library.space_groups(space)?,
8906 requests: requests.as_deref(),
8907 claims: &library.claims(space)?,
8908 set_aside: &library.set_aside_in(space)?,
8909 };
8910 output::space_shown(&shown, &environment.time_zone(), json, output)
8911}
8912
8913fn purge_or_list<E: Environment>(
8916 library: &mut Library,
8917 cli: &Cli,
8918 environment: &mut E,
8919 timings: &mut Timings,
8920 output: &mut dyn Write,
8921) -> Result<(), CliError> {
8922 let Command::Purge {
8923 entity, value, yes, ..
8924 } = &cli.command
8925 else {
8926 unreachable!("nib purge is the command");
8927 };
8928 let Some(entity) = entity else {
8929 return behind_command(library, cli, output);
8930 };
8931 let purge = (entity.as_str(), value.as_deref(), *yes);
8932 purge_either(library, purge, cli.json, environment, timings, output)
8933}
8934
8935fn behind_command(library: &Library, cli: &Cli, output: &mut dyn Write) -> Result<(), CliError> {
8938 let spaces = if cli.space.is_some() {
8939 vec![library.default_space()]
8940 } else {
8941 library.spaces()
8942 };
8943 let mut shown = Vec::new();
8944 for left_in in spaces {
8945 for request in library.purge_requests(left_in)? {
8946 let (now_in, moved) = request.moved_into;
8947 shown.push(output::LeftBehind {
8948 request,
8949 left_in: (left_in, library.space_name(left_in)?),
8950 name: library.name(now_in, moved)?,
8951 now_in: library.space_name(now_in)?,
8952 });
8953 }
8954 }
8955 output::purge_requests(&shown, cli.json, output)
8956}
8957
8958fn claim_command<E: Environment>(
8961 library: &mut Library,
8962 command: &SpaceCommand,
8963 json: bool,
8964 environment: &mut E,
8965 output: &mut dyn Write,
8966) -> Result<(), CliError> {
8967 match command {
8968 SpaceCommand::Claim { space, yes } => {
8969 let space = library.find_space(space)?;
8970 let name = space_display_name(library, space)?;
8971 if !*yes {
8972 library.check_claim(space)?;
8973 output::claiming(&name, json, output)?;
8974 return Err(CliError::UnconfirmedClaim);
8975 }
8976 let now = environment.now();
8977 library.claim_admin(space, now, environment.rng())?;
8978 output::claimed(&name, json, output)
8979 }
8980 SpaceCommand::Reject { space, member } => {
8981 let space = library.find_space(space)?;
8982 let record = library.find_member(space, member)?;
8983 let now = environment.now();
8984 library.reject_claim(space, record, now, environment.rng())?;
8985 let name = space_display_name(library, space)?;
8986 output::rejected_claim((&name, member), json, output)
8987 }
8988 _ => unreachable!("space_command passes only these"),
8989 }
8990}
8991
8992fn direct_command<E: Environment>(
8995 library: &mut Library,
8996 command: &SpaceCommand,
8997 json: bool,
8998 environment: &mut E,
8999 output: &mut dyn Write,
9000) -> Result<(), CliError> {
9001 match command {
9002 SpaceCommand::LetIn { space, member } => {
9003 let space = library.find_space(space)?;
9004 let found = library.find_group_member(space, member)?;
9005 let now = environment.now();
9006 library.let_in(space, found, now, environment.rng())?;
9007 let name = space_display_name(library, space)?;
9008 output::let_in((&name, member), json, output)
9009 }
9010 SpaceCommand::MakeDirect {
9011 space,
9012 member,
9013 role,
9014 } => {
9015 let space = library.find_space(space)?;
9016 let found = library.find_group_member(space, member)?;
9017 let now = environment.now();
9018 library.make_direct(space, found, role.role(), now, environment.rng())?;
9019 let name = space_display_name(library, space)?;
9020 output::made_direct((&name, member), role.role(), json, output)
9021 }
9022 SpaceCommand::Confirm { space } => {
9023 let space = library.find_space(space)?;
9024 let now = environment.now();
9025 library.confirm_direct(space, now, environment.rng())?;
9026 let name = space_display_name(library, space)?;
9027 output::confirmed_direct(&name, json, output)
9028 }
9029 _ => unreachable!("space_command passes only these"),
9030 }
9031}
9032
9033fn group_command<E: Environment>(
9036 library: &mut Library,
9037 command: &SpaceCommand,
9038 json: bool,
9039 environment: &mut E,
9040 output: &mut dyn Write,
9041) -> Result<(), CliError> {
9042 match command {
9043 SpaceCommand::AddGroup { space, group, role } => {
9044 let (space, group) = (library.find_space(space)?, library.find_space(group)?);
9045 let now = environment.now();
9046 library.add_group(space, group, role.role(), now, environment.rng())?;
9047 let groups = library.space_groups(space)?;
9048 output::space_groups(&groups, json, output)
9049 }
9050 SpaceCommand::RemoveGroup { space, group } => {
9051 let (space, group) = (library.find_space(space)?, library.find_space(group)?);
9052 let now = environment.now();
9053 library.remove_group(space, group, now, environment.rng())?;
9054 output::space_groups(&library.space_groups(space)?, json, output)
9055 }
9056 SpaceCommand::Agree { group, space } | SpaceCommand::Withdraw { group, space } => {
9057 let group = library.find_space(group)?;
9058 let space = requested_space(library, group, space)?;
9059 let now = environment.now();
9060 if matches!(command, SpaceCommand::Withdraw { .. }) {
9061 library.withdraw_group(group, space, now, environment.rng())?;
9062 } else {
9063 library.agree_to_join(group, space, now, environment.rng())?;
9064 }
9065 output::join_requests(&library.join_requests(group)?, json, output)
9066 }
9067 _ => Ok(()),
9068 }
9069}
9070
9071fn requested_space(
9074 library: &Library,
9075 group: nibkeep_base::SpaceId,
9076 reference: &str,
9077) -> Result<nibkeep_base::SpaceId, CliError> {
9078 let lowered = reference.to_lowercase();
9079 let requests = library.join_requests(group)?;
9080 let by_name: Vec<nibkeep_base::SpaceId> = requests
9083 .iter()
9084 .filter(|request| {
9085 request
9086 .name
9087 .as_deref()
9088 .is_some_and(|name| name.to_lowercase() == lowered)
9089 })
9090 .map(|request| request.space)
9091 .collect();
9092 let found: Vec<nibkeep_base::SpaceId> = if by_name.is_empty() && lowered.len() >= 4 {
9093 requests
9094 .iter()
9095 .filter(|request| request.space.to_string().starts_with(&lowered))
9096 .map(|request| request.space)
9097 .collect()
9098 } else {
9099 by_name
9100 };
9101 match found.as_slice() {
9102 [space] => Ok(*space),
9103 [] => Err(nibkeep_node::NodeError::NoGroupRequest.into()),
9104 _ => Err(nibkeep_node::NodeError::SpacesNamed(reference.to_owned()).into()),
9105 }
9106}
9107
9108fn link_command<E: Environment>(
9110 library: &mut Library,
9111 (space, member, person): (&str, &str, Option<&str>),
9112 json: bool,
9113 environment: &mut E,
9114 output: &mut dyn Write,
9115) -> Result<(), CliError> {
9116 let space = library.find_space(space)?;
9117 let member = library.find_member(space, member)?;
9118 let person = person
9119 .map(|person| library.find_person(space, person))
9120 .transpose()?;
9121 let now = environment.now();
9122 library.link_member(space, member, person, now, environment.rng())?;
9123 let found = library
9124 .members(space)?
9125 .into_iter()
9126 .find(|found| found.record == member);
9127 let name = found.as_ref().and_then(|found| found.name.clone());
9128 let link = found.map_or_default(|found| found.person);
9129 let person = match person {
9130 Some(person) => Some((person, library.name(space, person)?)),
9131 None => None,
9132 };
9133 output::linked(name.as_deref(), (person, link), json, output)
9134}
9135
9136const INVITATION_MINUTES: u64 = 10;
9138
9139fn invite_command<E: Environment>(
9142 library: &mut Library,
9143 (invitation, confirmed): (&nibkeep_node::Invitation, bool),
9144 cli: &Cli,
9145 environment: &mut E,
9146 output: &mut dyn Write,
9147) -> Result<(), CliError> {
9148 let json = cli.json;
9149 let (space, role) = (invitation.space, invitation.role);
9150 library.check_admin(space, "invite")?;
9152 if !confirmed && !environment.can_ask() {
9153 return Err(CliError::UnconfirmedInvite);
9154 }
9155 let name = library
9156 .space_name(space)?
9157 .unwrap_or_else(|| space.to_string());
9158 let suggest = role != MemberRole::Admin && library.suggests_second_admin(space)?;
9159 let _borrowed =
9162 nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
9163 let code = PairingCode::generate(environment.rng());
9164 let network = library.network(cli.network(true))?;
9165 output::port_taken(&network, json, output)?;
9166 output::invitation_code(
9167 &code,
9168 (&name, role),
9169 (INVITATION_MINUTES, suggest),
9170 json,
9171 output,
9172 )?;
9173 let now = clock(environment);
9174 let mut unasked = false;
9175 let mut confirm = |invitee: &nibkeep_node::Invitee| {
9176 if confirmed {
9177 return true;
9178 }
9179 let question = output::invitee_question(invitee, (&name, role));
9180 if let Ok(Some(answer)) = environment.ask(&question) {
9181 matches!(answer.to_lowercase().as_str(), "y" | "yes")
9182 } else {
9183 unasked = true;
9184 false
9185 }
9186 };
9187 let printing = RefCell::new(output);
9188 let wrong_try = |error: &NodeError, left: usize| {
9189 let _ = output::wrong_try(error, left, json, &mut **printing.borrow_mut());
9190 };
9191 let invited = nibkeep_node::invite(
9192 library,
9193 &network,
9194 invitation,
9195 &code,
9196 &mut confirm,
9197 nibkeep_node::Showing {
9198 timeout: Duration::from_mins(INVITATION_MINUTES),
9199 wrong_try: &wrong_try,
9200 },
9201 &now,
9202 &mut UnwrapErr(SysRng),
9203 );
9204 match invited {
9205 Err(NodeError::Declined) if unasked => Err(CliError::UnconfirmedInvite),
9206 invited => output::invited(&invited?, (&name, role), json, printing.into_inner()),
9207 }
9208}
9209
9210fn join_space_command<E: Environment>(
9214 library: &mut Library,
9215 (code, confirmed, also): (&PairingCode, bool, &[EntityId]),
9216 cli: &Cli,
9217 environment: &mut E,
9218 output: &mut dyn Write,
9219) -> Result<(), CliError> {
9220 let json = cli.json;
9221 library.check_not_ai_agent("join spaces")?;
9222 let _borrowed =
9223 nibkeep_node::borrow_network(library, &AtomicBool::new(false), UnwrapErr(SysRng))?;
9224 let network = library.network(cli.network(false))?;
9225 output::progress("Looking for the device that shows the codeā¦", json, output)?;
9226 let now = clock(environment);
9227 let joined = nibkeep_node::join_space(
9228 library,
9229 &network,
9230 code,
9231 FIND_SPONSOR,
9232 &now,
9233 environment.rng(),
9234 )?;
9235 if !also.is_empty() {
9237 let now = environment.now();
9238 library.give_space(joined.space, also, now, environment.rng())?;
9239 }
9240 let linked = match &joined.person {
9241 None => None,
9242 Some((person, name)) => {
9243 let yes = confirmed
9245 || matches!(
9246 environment.ask(&output::person_question(name, &joined.name)),
9247 Ok(Some(answer)) if matches!(answer.to_lowercase().as_str(), "y" | "yes")
9248 );
9249 let now = environment.now();
9250 let linked = yes
9251 && match library.link_member(
9252 joined.space,
9253 joined.member,
9254 Some(*person),
9255 now,
9256 environment.rng(),
9257 ) {
9258 Ok(()) => true,
9259 Err(error) => {
9260 environment.note(&format!("could not link you to {name}: {error}"));
9261 false
9262 }
9263 };
9264 Some(linked)
9265 }
9266 };
9267 output::joined_space(&joined, linked, json, output)
9268}
9269
9270fn no_journal(error: CliError, directory: &Path) -> CliError {
9273 match error {
9274 CliError::Node(NodeError::NoJournal) => CliError::NoJournal(directory.to_owned()),
9275 other => other,
9276 }
9277}
9278
9279fn init<E: Environment>(
9282 directory: &Path,
9283 new: &NewLibrary<'_>,
9284 (passphrase, file): (bool, Option<&Path>),
9285 environment: &mut E,
9286 timings: &mut Timings,
9287) -> Result<Library, CliError> {
9288 if Library::exists(directory) {
9291 return Err(match Library::protection(directory) {
9292 Err(NodeError::Unfinished) => unfinished(directory),
9293 Err(NodeError::Copied) => CliError::CopiedHere(directory.to_owned()),
9294 _ => NodeError::Exists.into(),
9295 });
9296 }
9297 if let Some(first) = new_passphrase((passphrase, file), environment, timings)? {
9298 let protection = NewProtection::Passphrase(&first, environment.passphrase_params());
9299 create(directory, new, &protection, environment)
9300 } else {
9301 let protection = NewProtection::Keystore {
9302 service: KEYSTORE_SERVICE,
9303 };
9304 create(directory, new, &protection, environment).map_err(|error| match error {
9305 CliError::Node(error @ NodeError::Keys(KeysError::Keystore(_))) => {
9306 CliError::Keystore(error)
9307 }
9308 other => other,
9309 })
9310 }
9311}
9312
9313fn new_passphrase<E: Environment>(
9318 (passphrase, file): (bool, Option<&Path>),
9319 environment: &mut E,
9320 timings: &mut Timings,
9321) -> Result<Option<zeroize::Zeroizing<String>>, CliError> {
9322 if !(passphrase || file.is_some() || !environment.keystore()) {
9323 return Ok(None);
9324 }
9325 Ok(Some(match file {
9326 Some(file) => passphrase_in(file)?,
9327 None => ask_twice(
9328 environment,
9329 timings,
9330 ("A passphrase for the library: ", "The passphrase again: "),
9331 (|| CliError::EmptyPassphrase, || CliError::PassphrasesDiffer),
9332 )?,
9333 }))
9334}
9335
9336fn passphrase_in(path: &Path) -> Result<zeroize::Zeroizing<String>, CliError> {
9337 use std::io::Read;
9338 let unreadable = |error: io::Error| CliError::PassphraseFile {
9339 path: path.to_owned(),
9340 error,
9341 };
9342 let mut file = std::fs::File::open(path).map_err(unreadable)?;
9343 let metadata = file.metadata().map_err(unreadable)?;
9344 #[cfg(unix)]
9345 {
9346 use std::os::unix::fs::PermissionsExt;
9347 if metadata.permissions().mode() & 0o077 != 0 {
9348 return Err(CliError::PassphraseFileOpen(path.to_owned()));
9349 }
9350 }
9351 let room = usize::try_from(metadata.len()).unwrap_or(0);
9353 let mut text = zeroize::Zeroizing::new(String::with_capacity(room + 1));
9354 file.read_to_string(&mut text).map_err(unreadable)?;
9355 let end = text.find(['\n', '\r']).unwrap_or(text.len());
9356 text.truncate(end);
9357 if text.is_empty() {
9358 return Err(CliError::EmptyPassphrase);
9359 }
9360 Ok(text)
9361}
9362
9363fn create<E: Environment>(
9364 directory: &Path,
9365 new: &NewLibrary<'_>,
9366 protection: &NewProtection<'_>,
9367 environment: &mut E,
9368) -> Result<Library, CliError> {
9369 let now = environment.now();
9370 let mut library = Library::create(directory, new, protection, now, environment.rng())?;
9371 library.make_thumbnails_with(Arc::new(RustDecoders));
9372 Ok(library)
9373}
9374
9375fn open<E: Environment>(
9377 directory: &Path,
9378 passphrase_file: Option<&Path>,
9379 environment: &mut E,
9380 timings: &mut Timings,
9381) -> Result<Library, CliError> {
9382 let started = Instant::now();
9383 let mut waited = Duration::ZERO;
9384 let (mut library, opening) = match Library::protection(directory)? {
9385 Protection::Passphrase { .. } => {
9386 let passphrase = if let Some(file) = passphrase_file {
9387 passphrase_in(file)?
9388 } else {
9389 let asked = Instant::now();
9390 let passphrase = environment.passphrase("Passphrase: ")?;
9391 waited = asked.elapsed();
9392 add(&mut timings.waiting, waited);
9393 passphrase
9394 };
9395 Library::open_timed(directory, &Unlocker::Passphrase(&passphrase))?
9396 }
9397 Protection::Keystore { .. } => {
9398 if !environment.keystore() {
9399 return Err(CliError::NoKeystore);
9400 }
9401 Library::open_timed(directory, &Unlocker::Keystore)?
9402 }
9403 };
9404 add(
9407 &mut timings.unlock,
9408 started.elapsed().saturating_sub(waited + opening.spaces),
9409 );
9410 add(&mut timings.open, opening.spaces);
9411 library.make_thumbnails_with(Arc::new(RustDecoders));
9412 Ok(library)
9413}
9414
9415#[cfg(test)]
9416mod tests {
9417 use std::io::{self, Write};
9418
9419 use super::{CliError, UntilUnread, parse_size};
9420
9421 struct Closing {
9423 written: Vec<u8>,
9424 room: usize,
9425 error: io::ErrorKind,
9426 }
9427
9428 impl Write for Closing {
9429 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
9430 if self.written.len() + bytes.len() > self.room {
9431 return Err(self.error.into());
9432 }
9433 self.written.extend_from_slice(bytes);
9434 Ok(bytes.len())
9435 }
9436
9437 fn flush(&mut self) -> io::Result<()> {
9438 Ok(())
9439 }
9440 }
9441
9442 #[test]
9443 fn output_that_nothing_reads_is_taken_and_not_written() {
9444 let closing = Closing {
9445 written: Vec::new(),
9446 room: 6,
9447 error: io::ErrorKind::BrokenPipe,
9448 };
9449 let mut output = UntilUnread::new(closing);
9450 writeln!(output, "first").expect("written");
9451 writeln!(output, "second").expect("taken");
9452 writeln!(output, "third").expect("taken");
9453 output.flush().expect("flushed");
9454 assert_eq!(output.inner.written, b"first\n");
9455 assert!(output.unread);
9456 let mut full = UntilUnread::new(Closing {
9458 written: Vec::new(),
9459 room: 0,
9460 error: io::ErrorKind::StorageFull,
9461 });
9462 assert_eq!(
9463 writeln!(full, "first").expect_err("full").kind(),
9464 io::ErrorKind::StorageFull
9465 );
9466 assert!(!full.unread);
9467 }
9468
9469 #[test]
9470 fn sizes_are_read_in_bytes_and_units() {
9471 assert_eq!(parse_size("1073741824"), Ok(1 << 30));
9472 assert_eq!(parse_size("1GiB"), Ok(1 << 30));
9473 assert_eq!(parse_size("500 MB"), Ok(500_000_000));
9474 assert_eq!(parse_size("10b"), Ok(10));
9475 assert!(parse_size("1.5GB").is_err());
9476 assert!(parse_size("GB").is_err());
9477 assert!(parse_size("2PB").is_err());
9478 assert!(parse_size("99999999TiB").is_err());
9479 assert_eq!(super::output::size_text(1 << 30), "1 GiB");
9480 assert_eq!(super::output::size_text(500_000_000), "500 MB");
9481 assert_eq!(super::output::size_text(22), "22 bytes");
9482 }
9483
9484 #[test]
9485 fn an_unsound_library_counts_its_problems() {
9486 assert_eq!(
9487 CliError::Unsound(1).to_string(),
9488 "the library has a problem"
9489 );
9490 assert_eq!(
9491 CliError::Unsound(3).to_string(),
9492 "the library has 3 problems"
9493 );
9494 }
9495}